Hi I tried implementing the code from : http://support.microsoft.com/kb/306158. But I am allitle bit confused of how it works.
for example: if(impersonateValidUser("username", "domain", "password")) //where do I get this information?
I have attached the code behind that I currenlty have, please let me know what should be changed.
Thank you,
public const int LOGON32_LOGON_INTERACTIVE = 2;
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);
private void Page_Load(object sender, System.EventArgs e)
{
try
{
//System.Security.Principal.WindowsImpersonationContext i ;
string username = ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate().ToString();
if(impersonateValidUser(username, "domain", "password"))
{
//Insert your code that runs under the security context of a specific user here.
Response.Write("<BR>|Insert your code that runs under the security context of a specific user here.");
undoImpersonation();
}
else
{
//Your impersonation failed. Therefore, include a fail-safe mechanism here.
Response.Write("<BR>|Your impersonation failed");
}
}
catch(Exception ex)
{
Response.Write("<BR>|"+ ex.Message+ "|<BR>");
}
}
private 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;
}
private void undoImpersonation()
{
impersonationContext.Undo();
}
==========web config file===============
<system.web>
<identity impersonate="true" />
</system.web>