Share via


SqlContext.WindowsIdentity Property

Definition

The Microsoft Windows identity of the caller.

public:
 static property System::Security::Principal::WindowsIdentity ^ WindowsIdentity { System::Security::Principal::WindowsIdentity ^ get(); };
public static System.Security.Principal.WindowsIdentity WindowsIdentity { get; }
static member WindowsIdentity : System.Security.Principal.WindowsIdentity
Public Shared ReadOnly Property WindowsIdentity As WindowsIdentity

Property Value

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

Examples

The following example shows how to get the Windows identity of the calling client and impersonate the client.

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;
}
Dim clientId As WindowsIdentity
Dim impersonatedUser As WindowsImpersonationContext

clientId = SqlContext.WindowsIdentity

Try 
   Try
   
      impersonatedUser = clientId.Impersonate()

      If impersonatedUser IsNot Nothing Then
         ' Perform some action using impersonation.
      End If

   Finally

     If impersonatedUser IsNot Nothing Then
         impersonatedUser.Undo
     End If

   End Try

Catch e As Exception

   throw e

End Try

Remarks

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.

Applies to