Sometimes it is required to authenticate the user when username and password are known. For this the windows API LogonUser function is used. This function, with little bit .NET code, can be used to fully authenticate the thread in .NET as it would be started by that interactive user.
Following code shows how to do that:
[DllImport("advapi32.dll")]
protected static extern bool
LogonUser(String lpszUsername,
String lpszDomain,
String lpszPassword,
int dwLogonType,
int dwLogonProvider,
out int phToken);
public static void Authenticate(string userName,
string password)
{
int token;
bool loggedOn = LogonUser(userName,
null, password,
2/*2 is if local user is logged on.*/,
0, out token);
if (!loggedOn)
{
throw new SecurityException("...");
}
else
{
IntPtr token2 = new IntPtr(token);
WindowsIdentity mWI = new WindowsIdentity(token2);
WindowsImpersonationContext mwic = mWI.Impersonate();
// Test
WindowsIdentity mWI1 = WindowsIdentity.GetCurrent();
}
}
More about impersonation can be found here.