public static WindowsPrincipal GetPrincipalFromUserIdentity(UserIdentity user)
{
if (UserIdentity.IsDefault(user))
{
return null;
}
// validate the credentials.
IntPtr token = IntPtr.Zero;
bool result = LogonUser(
user.Username,
user.Domain,
user.Password,
LOGON32_LOGON_NETWORK,
LOGON32_PROVIDER_DEFAULT,
ref token);
if (!result)
{
throw ServiceResultException.Create(
StatusCodes.BadIdentityTokenRejected,
"Could not logon as user '{0}'. Reason: {1}.",
user.Username,
GetSystemMessage(Marshal.GetLastWin32Error(), LOCALE_SYSTEM_DEFAULT));
}
try
{
// create the windows identity.
WindowsIdentity identity = new WindowsIdentity(token);
// validate the identity.
identity.Impersonate();
// return a principal.
return new WindowsPrincipal(identity);
}
finally
{
CloseHandle(token);
}
}