Ok, I am trying to authenticate a user by Domain, then check to see if the user is in my custom database. All I want to do here is check to see if the user exists on the domain, and then the application database handles everything else about the user...Please help. Thanks
The below code is right from here
http://support.microsoft.com/?scid=306158
If I create a local machine user, and specify the machine name here, I am able to login.
<add key="Domain" value="Machine_Name" />
But, if I specify the Domain name (which is really what I need to do), I always get Login Failed
<add key="Domain" value="DOMAIN_Name" />
private void _btnLogin_Click(object sender, System.EventArgs e)
{
WinFormAuth wa = new WinFormAuth();
string _domain = System.Configuration.ConfigurationSettings.AppSettings["Domain"];
//Do DB Lookup
try
{
if(wa.impersonateValidUser(_userName.Text, _domain, _password.Text))
{
//Insert your code that runs under the security context of a specific user here.
wa.undoImpersonation();
if(Request.QueryString["url"]==null)
Response.Redirect("dashboard_summary.aspx");
else
Response.Redirect(Request.QueryString["url"]);
}
else
{
//Your impersonation failed. Therefore, include a fail-safe mechanism here.
_lblMessage.Text="Login Failed";
}
}
catch(Exception ex)
{
_lblMessage.Text=ex.Message;
}
}
public class WinFormAuth
{
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);
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;
}
public void undoImpersonation()
{
impersonationContext.Undo();
}
} |