Export (0) Print
Expand All

SqlContext.WindowsIdentity Property

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

Supported in: 4.5, 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Show:
© 2014 Microsoft