Export (0) Print
Expand All

SecurityContext Class

Note: This class is new in the .NET Framework version 2.0.

Encapsulates and propagates all security-related data for execution contexts transferred across threads. This class cannot be inherited.

Namespace: System.Security
Assembly: mscorlib (in mscorlib.dll)

public ref class SecurityContext sealed
public final class SecurityContext
public final class SecurityContext

A SecurityContext object captures all security-related information for a logical thread, including the information contained in the WindowsIdentity and CompressedStack objects. This configuration allows the Windows identity and the security elements on the stack to be propagated automatically when the SecurityContext is copied and transferred across asynchronous threads.

The SecurityContext is part of the larger ExecutionContext and flows or migrates when the ExecutionContext flows or migrates.

The following code example shows the use of members of the SecurityContext class.

No code example is currently available or this language may not be supported.
import System.*;
import System.Threading.*;
import System.Security.*;
import System.Security.Permissions.*;
import System.Security.Principal.*;
import System.Runtime.InteropServices.*;
class SecurityContextSample
    /** @attribute SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)
    public static void main(String[] args)
            Console.WriteLine("Executing the Main method in the primary "
                + "thread.");
            FileDialogPermission fdp = new FileDialogPermission(

            // Do not allow the security context to pass across threads;
            // suppress its flow.
            AsyncFlowControl aFC = SecurityContext.SuppressFlow();

            System.Threading.Thread t1 = new System.Threading.Thread(
                new ThreadStart(DemandPermission));
            Console.WriteLine("Is the flow suppressed? "
                + SecurityContext.IsFlowSuppressed());

            Console.WriteLine("Restore the flow.");

            Console.WriteLine("Is the flow suppressed? "
                + SecurityContext.IsFlowSuppressed());
            System.Threading.Thread t2 = new System.Threading.Thread(
                new ThreadStart(DemandPermission));
            // Show the Deny is no longer present.
            System.Threading.Thread t3 = new System.Threading.Thread(
                new ThreadStart(DemandPermission));
            // Set the security context on the thread that contains the Deny.

            ImpersonateUser iU = new ImpersonateUser();
            System.Threading.Thread t5 = new System.Threading.Thread(
                new ThreadStart(CheckIdentity));
            Console.WriteLine("Suppress the flow of the Windows identity.");
            AsyncFlowControl aFC2 = SecurityContext.SuppressFlowWindowsIdentity();
            Console.WriteLine("Has the Windows identity flow been suppressed?"
                + SecurityContext.IsWindowsIdentityFlowSuppressed());

            System.Threading.Thread t6 = new System.Threading.Thread(
                new ThreadStart(CheckIdentity));
            // Restore the flow of the Windows identity for the impersonated
            // user.
            Console.WriteLine("User name after restoring the Windows identity"
                + " flow with Undo: " + WindowsIdentity.GetCurrent().get_Name());
            Console.WriteLine("This sample completed successfully;"
                + " press Enter to exit.");
        catch (System.Exception e)
    } //main

    // Test method to be called on a second thread.
    static void DemandPermission()
            Console.WriteLine("This is the thread executing the "
                + "DemandPermission method.");
            (new FileDialogPermission(FileDialogPermissionAccess.OpenSave)).
            Console.WriteLine("FileDialogPermission was successsfully"
                + " demanded.");
        catch (System.Exception e)
    } //DemandPermission

    static void CheckIdentity()
        Console.WriteLine("Current user: "
            + WindowsIdentity.GetCurrent().get_Name());
    } //CheckIdentity

} //SecurityContextSample

    // Perform user impersonation.
public class ImpersonateUser
    /** @attribute DllImport("advapi32.dll", SetLastError = true)
    public static native boolean LogonUser(String lpszUserName,
        String lpszDomain, String lpszPassword, int dwLogonType,
        int dwLogonProvider, /** @ref */ IntPtr phToken);

    /** @attribute DllImport("kernel32.dll", CharSet = CharSet.Auto)
    public static native boolean CloseHandle(IntPtr handle);

    /** @attribute DllImport("advapi32.dll", CharSet = CharSet.Auto, 
     SetLastError = true)
    public static native boolean DuplicateToken(IntPtr existingTokenHandle,
        int SECURITY_IMPERSONATION_LEVEL, IntPtr duplicateTokenHandle);

    private static IntPtr tokenHandle = new IntPtr(0);
    private static IntPtr dupeTokenHandle = new IntPtr(0);
    private static WindowsImpersonationContext impersonatedUser;

    /** @attribute SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.UnmanagedCode)
    public void Impersonate()
            String userName, domainName;
            // Use the unmanaged LogonUser function to get the user token for
            // the specified user, domain, and password.
            // To impersonate a user on this machine, use the local machine
            // name for the domain name.
            Console.Write("Enter the name of the domain to log on to: ");
            domainName = Console.ReadLine();

            Console.Write("Enter the logon name of the user that you wish to"
                + " impersonate on {0}: ", domainName);
            userName = Console.ReadLine();

            Console.Write("Enter the password for {0}: ", userName);

            final int LOGON32_PROVIDER_DEFAULT = 0;
            // Passing this parameter causes LogonUser to create a primary
            // token.
            final int LOGON32_LOGON_INTERACTIVE = 2;
            tokenHandle = IntPtr.Zero;
            // Call  LogonUser to obtain a handle to an access token.
            boolean returnValue = LogonUser(userName, domainName,
                Console.ReadLine(), LOGON32_LOGON_INTERACTIVE,
                LOGON32_PROVIDER_DEFAULT, /** @out */ tokenHandle);

            Console.WriteLine("LogonUser has been called.");

            if (false == returnValue)
                int ret = Marshal.GetLastWin32Error();
                Console.WriteLine("LogonUser call failed with error code : "
                    + ret);
                throw new System.ComponentModel.Win32Exception(ret);
            Console.WriteLine("Did LogonUser succeed? "
                + ((returnValue) ? "Yes" : "No"));
            Console.WriteLine("Value of the Windows NT token: " + tokenHandle);
            // Check the identity.
            Console.WriteLine("User name before the impersonation: "
                + WindowsIdentity.GetCurrent().get_Name());

            WindowsIdentity newId = new WindowsIdentity(tokenHandle);
            impersonatedUser = newId.Impersonate();
            // Check the identity.
            Console.WriteLine("User name after the impersonation: "
                + WindowsIdentity.GetCurrent().get_Name());
        catch (System.Exception ex)
            Console.WriteLine("Exception occurred. " + ex.get_Message());
    } //Impersonate

    public void Undo()
        // Check the identity.
        Console.WriteLine("After Undo: "
            + WindowsIdentity.GetCurrent().get_Name());
        // Free the tokens.
        if (!tokenHandle.Equals(IntPtr.Zero))
    } //Undo
} //ImpersonateUser


Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows 2000 SP4, Windows Millennium Edition, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

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

.NET Framework

Supported in: 2.0

Community Additions

© 2015 Microsoft