title: How to check current active directory user used by SqlClient for SSPI Integrated Security in ASP.NET
body: <p><strong>Short question</strong>: How to check the current user used by integrated security SqlClient connection when the user is an Active Directory domain user forced through the "runas" command in a debug environment. All .NET methods found in similar questions reports uncorrect results.</p>
  
  <p><strong>Long question</strong></p>
  
  <p>I have an ASP.NET application using System.Data.SqlClient library to connect against a SqlServer database.</p>
  
  <p>The connection is performed through "Integrated Security = SSPI" with Active Directory domain users.</p>
  
  <p>I run debug from VisualStudio Community 2017 on my PC which is not joined to the Active Directory domain, but I'm able to connect with my Active Directory domain user to the database by running VisualStudio through the "RunAs" command like this:</p>
  
  <pre><code>C:\Windows\System32\runas.exe /user:&lt;domain&gt;\&lt;user&gt; /netonly "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\devenv.exe"
  </code></pre>
  
  <p>In this way the VisualStudio process runs with the domain user on my PC (altough the task manager shows the running user as local "mariano.paniga" user). This allows the IIS Express debug session to run with the same domain user and the connection to the database works fine.</p>
  
  <p>I need to check in my code the current user performing the action, but I'm not able to see what I consider the correct user connecting to the database (i.e. "/").</p>
  
  <p>This is the connection command</p>
  
  <pre><code>SqlConnection sqlConn = new SqlConnection("Initial Catalog = WL; Integrated Security = SSPI; Data Source = &lt;DB_Machine&gt;");
  </code></pre>
  
  <p>These are the ways I tried to check the current user and their actual results in my debug environment:</p>
  
  <pre><code>sb.Append(string.Format("{0} - Started handling insert from user {1}\n", DateTime.Now
  , System.Security.Principal.WindowsIdentity.GetCurrent().Name));
  sb.Append(string.Format("{0} - Debug HttpContext.Current.User.Identity.Name = {1}\n", DateTime.Now
  , HttpContext.Current.User.Identity.Name));
  sb.Append(string.Format("{0} - Debug System.Environment.UserName = {1}\n", DateTime.Now
  , System.Environment.UserName));
  sb.Append(string.Format("{0} - Debug Thread.CurrentPrincipal.Identity.Name = {1}\n", DateTime.Now
  , Thread.CurrentPrincipal.Identity.Name));
  </code></pre>
  
  <p>Results:</p>
  
  <pre><code>02/10/2019 10:08:51 - Started handling insert from user &lt;MYPC-NAME&gt;\mariano.paniga
  02/10/2019 10:08:51 - Debug HttpContext.Current.User.Identity.Name = 
  02/10/2019 10:08:51 - Debug System.Environment.UserName = mariano.paniga
  02/10/2019 10:08:51 - Debug Thread.CurrentPrincipal.Identity.Name = 
  </code></pre>