Wednesday, October 18, 2006

Impersonating windows users


This is a very common requirement for applications.

Use the System.Security.Principal.WindowsIdentity to impersonate the user you want then use this object in the Impersonate method of the WindowsIdentity object


Sample code:

using System.Security.Principal;
using System.Security.Permissions;
using System.Runtime.InteropServices;

//need to ensure that the thread has the permissions to do the impersonation
//this is at the namespace/class level, before the namespace preferably
[assembly:SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode=true, ControlPrincipal=true)]


//windows logon form
//this is within the class (after the class tags)
const int LOGON32_PROVIDER_DEFAULT = 0;
const int LOGON32_LOGON_INTERACTIVE = 2;
[DllImport("advapi32.dll"), SetLastError=true, CharSet=CharSet.Unicode)]
static extern bool LogonUser(string userName, string domain, string password, int logonType, int logonProvider, ref IntPtr accessToken);

IntPtr accessToken = IntPtr.Zero;

bool success = LogonUser("username",".","password",LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref accessToken);

if(!success){
--Marshal.GetLastWin32Error();
}else{
--WindowsIdentity identity = new WindowsIdentity(accessToken);
--WindowsImpersonationContext impContext = identity.Impersonate();
--impContxt.Undo();
}

No comments: