
Retrieving Windows Identity
CLR code executing inside SQL Server is always invoked in the context of the process account. If the code should perform certain actions using the identity of the calling user, instead of the SQL Server process identity, then an impersonation token should be obtained through the WindowsIdentity property of the SqlContext object. The WindowsIdentity property returns a WindowsIdentity instance representing the Microsoft Windows identity of the caller, or null if the client was authenticated using SQL Server Authentication. Only assemblies marked with EXTERNAL_ACCESS or UNSAFE permissions can access this property.
After obtaining the WindowsIdentity object, callers can impersonate the client account and perform actions on their behalf.
The identity of the caller is only available through SqlContext.WindowsIdentity if the client that initiated execution of the stored-procedure or function connected to the server using Windows Authentication. If SQL Server Authentication was used instead, this property is null and the code is unable to impersonate the caller.
Example
The following example shows how to get the Windows identity of the calling client and impersonate the client.
C#
[Microsoft.SqlServer.Server.SqlProcedure]
public static void WindowsIDTestProc()
{
WindowsIdentity clientId = null;
WindowsImpersonationContext impersonatedUser = null;
// Get the client ID.
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
{
// Undo impersonation.
if (impersonatedUser != null)
impersonatedUser.Undo();
}
}
catch
{
throw;
}
}
Visual Basic
<Microsoft.SqlServer.Server.SqlProcedure()> _
Public Shared Sub WindowsIDTestProcVB ()
Dim clientId As WindowsIdentity
Dim impersonatedUser As WindowsImpersonationContext
' Get the client ID.
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 IsNot Nothing Then
' Perform some action using impersonation.
End If
Finally
' Undo impersonation.
If impersonatedUser IsNot Nothing Then
impersonatedUser.Undo()
End If
End Try
Catch e As Exception
Throw e
End Try
End Sub