asp.net.netsqlclientrunassspi

How to check current active directory user used by SqlClient for SSPI Integrated Security in ASP.NET


Short question: 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.

Long question

I have an ASP.NET application using System.Data.SqlClient library to connect against a SqlServer database.

The connection is performed through "Integrated Security = SSPI" with Active Directory domain users.

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:

C:\Windows\System32\runas.exe /user:<domain>\<user> /netonly "C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\Common7\IDE\devenv.exe"

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.

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. "/").

This is the connection command

SqlConnection sqlConn = new SqlConnection("Initial Catalog = WL; Integrated Security = SSPI; Data Source = <DB_Machine>");

These are the ways I tried to check the current user and their actual results in my debug environment:

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));

Results:

02/10/2019 10:08:51 - Started handling insert from user <MYPC-NAME>\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 = 

Solution

  • Have you thought of sending the database

    select ORIGINAL_LOGIN()
    

    To purposely check the login used to start the connection. (I'm presuming that you'd just do that to help your debugging along it's way in your current environment)