public static ImpersonationContext LogonUser(UserNameSecurityToken identityToken, bool interactive)
{
if (identityToken == null)
{
throw ServiceResultException.Create(StatusCodes.BadIdentityTokenRejected, "Secuirty token is not a valid username token.");
}
// extract the username and domain from the security token.
string username = identityToken.UserName;
string domain = null;
int index = username.IndexOf('\\');
if (index != -1)
{
domain = username.Substring(0, index);
username = username.Substring(index+1);
}
// validate the credentials.
IntPtr handle = IntPtr.Zero;
int result = Win32.LogonUserW(
username,
domain,
identityToken.Password,
(interactive) ? Win32.LOGON32_LOGON_INTERACTIVE : Win32.LOGON32_LOGON_NETWORK,
Win32.LOGON32_PROVIDER_DEFAULT,
ref handle);
if (result == 0)
{
result = Marshal.GetLastWin32Error();
throw ServiceResultException.Create(
StatusCodes.BadIdentityTokenRejected,
"Could not logon as user '{0}'. Reason: {1}.",
identityToken.UserName,
result);
}
try
{
WindowsIdentity identity = new WindowsIdentity(handle);
ImpersonationContext context = new ImpersonationContext();
context.Principal = new WindowsPrincipal(identity);
context.Context = identity.Impersonate();
context.Handle = handle;
return context;
}
catch (Exception e)
{
Win32.CloseHandle(handle);
throw e;
}
}
#endregion