24-3-2009 14:6:17
public class WindowAuthenticate
{
[DllImport("advapi32.dll", SetLastError = true)]
static extern bool LogonUser(
string principal,
string authority,
string password,
LogonSessionType logonType,
LogonProvider logonProvider,
out IntPtr token);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr handle);
enum LogonSessionType : uint
{
Interactive = 2,
Network,
Batch,
Service,
NetworkCleartext = 8,
NewCredentials
}
enum LogonProvider : uint
{
Default = 0, // default for platform (use this!)
WinNT35, // sends smoke signals to authority
WinNT40, // uses NTLM
WinNT50 // negotiates Kerb or NTLM
}
public static bool UserLogin(string username, string domain, string password, System.Web.HttpResponse response)
{
IntPtr token = IntPtr.Zero;
WindowsImpersonationContext impersonatedUser = null;
try
{
// Create a token for DomainName\Bob
// Note: Credentials should be encrypted in configuration file
bool result = LogonUser(username, domain,
password,
LogonSessionType.Interactive,
LogonProvider.Default,
out token);
if (result)
{
WindowsIdentity id = new WindowsIdentity(token);
// Begin impersonation
impersonatedUser = id.Impersonate();
string full_username = WindowsIdentity.GetCurrent().Name;
System.Web.Security.FormsAuthentication.SetAuthCookie(full_username, false);
return true;
}
else
{
response.Write("</p>LogonUser failed: " +
Marshal.GetLastWin32Error().ToString());
}
}
catch
{
// Prevent any exceptions that occur while the thread is
// impersonating from propagating
}
finally
{
// Stop impersonation and revert to the process identity
if (impersonatedUser != null) impersonatedUser.Undo();
// Free the token
if (token != IntPtr.Zero) CloseHandle(token);
}
return false;
}
}