w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Impersonate a Active Directory user in MVC application with Windows Authentication
 using (new Impersonation()){
  // now working in context of whatever user you want

and this is the class

 [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
    public class Impersonation : IDisposable
    private readonly SafeTokenHandle _handle;
    private readonly WindowsImpersonationContext _context;

    //const int Logon32LogonNewCredentials = 9; 
    private const int Logon32LogonInteractive = 2;

    public Impersonation()
        var domain = "your domain;
        var username = "the user";
        var password = "their password";
        var ok = LogonUser(username, domain, password,
Logon32LogonInteractive, 0, out _handle);
        if (!ok)
            var errorCode = Marshal.GetLastWin32Error();
            throw new ApplicationException(string.Format("Could not
impersonate the elevated user.  LogonUser returned error code {0}.",
        _context =

    public void Dispose()

    [DllImport("advapi32.dll", SetLastError = true, CharSet =
    private static extern bool LogonUser(String lpszUsername, String
lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out
SafeTokenHandle phToken);

    public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
        private SafeTokenHandle()
            : base(true) { }

        [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool CloseHandle(IntPtr handle);

        protected override bool ReleaseHandle()
            return CloseHandle(handle);

© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.