Thursday, September 24, 2009

Impersonate User in Active Directory - ASP.NET

Via the following class you can athenticate s specific user to specific domain and after that you access the resources (such as Doc or anything else) , and finally call UndoImpersotae function to disconnect athenticated user.

For inctance your application is installed on AppServer.WemDomain.local and you need to access some resources on FileServer.FileDomain.local , so you should have a user in FileDomain.local and then authenticate it and access to the resources and then close athentication proccess all these thing is happened in background and the user could not understand where the file come from.

public class ImpersonateUser_ActiveDirectory
{

public const int LOGON32_LOGON_INTERACTIVE = 9;
public const int LOGON32_PROVIDER_DEFAULT = 0;
WindowsImpersonationContext impersonationContext;
[DllImport("advapi32.dll")]
public static extern int LogonUserA(String lpszUserName,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
ref IntPtr phToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int DuplicateToken(IntPtr hToken,
int impersonationLevel,
ref IntPtr hNewToken);
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool RevertToSelf();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);

//Athenticate specific user in Active Directory
public bool impersonateValidUser(String userName, String domain, String password)
{
WindowsIdentity tempWindowsIdentity;
IntPtr token = IntPtr.Zero;
IntPtr tokenDuplicate = IntPtr.Zero;
if (RevertToSelf())
{
if (LogonUserA(userName, domain, password, LOGON32_LOGON_INTERACTIVE,
LOGON32_PROVIDER_DEFAULT, ref token) != 0)
{
if (DuplicateToken(token, 2, ref tokenDuplicate) != 0)
{
tempWindowsIdentity = new WindowsIdentity(tokenDuplicate);
impersonationContext = tempWindowsIdentity.Impersonate();
if (impersonationContext != null)
{
CloseHandle(token);
CloseHandle(tokenDuplicate);
return true;
}
}
}
}
if (token != IntPtr.Zero)
CloseHandle(token);
if (tokenDuplicate != IntPtr.Zero)
CloseHandle(tokenDuplicate);
return false;
}

//Undo authentication for authenticated user
private void undoImpersonation()
{
impersonationContext.Undo();
}
}

--------------------------------------------------------

you can save user info and domain info in Web.config and read these information with the following syntax

string UserName = ConfigurationSettings.AppSettings["UserName"];

No comments:

Post a Comment

Thank you for sharing your knowledge and experiences with this weblog.