SqlContext.WindowsIdentity Property

 
System_CAPS_noteNote

The .NET API Reference documentation has a new home. Visit the .NET API Browser on docs.microsoft.com to see the new experience.

The Microsoft Windows identity of the caller.

Namespace:   Microsoft.SqlServer.Server
Assembly:  System.Data (in System.Data.dll)

public static WindowsIdentity WindowsIdentity { get; }

Property Value

Type: System.Security.Principal.WindowsIdentity

A WindowsIdentity instance representing the Windows identity of the caller, or null if the client was authenticated using SQL Server Authentication.

Common language runtime (CLR) code inside SQL Server is always invoked in the context of the process account. If it is necessary for the code to perform an action using calling user’s identity instead of the SQL Server process identity, then an impersonation token should be obtained through this property. After obtaining the WindowsIdentity object, callers can impersonate the client account and perform actions on their behalf.

If invoked from outside SQL Server, a NotSupportedException is thrown.

Only assemblies marked with EXTERNAL_ACCESS or UNSAFE permissions can access this property.

This property is read-only.

The following example shows how to get the Windows identity of the calling client and impersonate the client. See "Impersonation Sample" in SQL Server Books Online for an example of impersonation using the WindowsIdentity property.

WindowsIdentity clientId = null;
WindowsImpersonationContext impersonatedUser = null;

clientId = SqlContext.WindowsIdentity;

// This outer try block is used to thwart exception filter attacks which would prevent
// the inner finally block from executing and resetting the impersonation.
try
{
   try
   {
      impersonatedUser = clientId.Impersonate();
      if (impersonatedUser != null)
      {
        // Perform some action using impersonation.
      }

   }
   finally
   {
      if (impersonatedUser != null)
         impersonatedUser.Undo();
   }
}
catch
{
   throw;
}

.NET Framework
Available since 2.0
Return to top
Show: