Tuesday, December 30, 2008

Windows Identity Impersonation

Sometime in window application it is required that it run in context of user account other than current login account.Few condition that required this is

1) Window Application that authenticate and authorize user by his/her user account.

2) SharePoint sometime required this to gain access of resource that is not granted for SharePoint users.

You can use following code to impersonate particular user.

[System.Runtime.InteropServices.DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(
String lpszUsername,
String lpszDomain,
        String lpszPassword,
        int dwLogonType,
        int dwLogonProvider,
        ref IntPtr phToken);
        [System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public extern static bool CloseHandle(IntPtr handle);

        static void Main(string[] args)
        {

            IntPtr usertoken = new IntPtr(0);
            bool b = LogonUser("test", "local", "123", 2, 0, ref usertoken);
            if (b == true)
            {
                System.Security.Principal.WindowsIdentity iden = new System.Security.Principal.WindowsIdentity(usertoken);
                System.Security.Principal.WindowsImpersonationContext con = iden.Impersonate();

// You Code that required impersonation

con.undo()

}

}

Note : Impersonation can be used in any type of application. (Window Application , Web Application , Class Library).

In Web Application web.config contains specific <identity> attribute for impersonation.

No comments: