//-----------------------------------------------------------------------
//
// Copyright (C) 2011 Microsoft Corporation
//
//-----------------------------------------------------------------------
namespace Microsoft.Samples.Management.OData.RoleBasedPlugins
{
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
///
/// Provide Helper functions for getting WindowsIdentity
///
public static class WindowsIdentityHelper
{
/// Win32 constant for logon type in LogonUser API. Same as LOGON32_LOGON_INTERACTIVE
private const int Logon32LogonInteractive = 2;
/// Win32 constant for logon type in LogonUser API. Same as LOGON32_LOGON_NETWORK_CLEARTEXT
private const int Logon32LogonNetworkClearText = 8;
/// Win32 constant for logon provider in LogonUser API. Same as LOGON32_PROVIDER_DEFAULT
private const int Logon32ProviderDefault = 0;
/// Win32 constant of type SECURITY_IMPERSONATION_LEVEL
private const int SecurityImpersonation = 2;
///
/// Logs in a user using its credentials and returns the WindowsIdentity
///
/// User Name which needs to be logged in
/// Password of the user
/// Domain name for the user
/// WindosIdentity created after logging in the user
public static WindowsIdentity GetWindowsIdentity(string userName, string password, string domainName)
{
IntPtr tokenHandle = new IntPtr(0);
IntPtr dupeTokenHandle = new IntPtr(0);
try
{
tokenHandle = IntPtr.Zero;
dupeTokenHandle = IntPtr.Zero;
if (NativeMethods.LogonUser(userName, domainName, password, Logon32LogonNetworkClearText, Logon32ProviderDefault, ref tokenHandle) == false)
{
throw new ArgumentException("Error while trying to log user on");
}
if (NativeMethods.DuplicateToken(tokenHandle, SecurityImpersonation, ref dupeTokenHandle) == false)
{
throw new ArgumentException("Error while trying to duplicate token");
}
return new WindowsIdentity(dupeTokenHandle);
}
finally
{
if (tokenHandle != IntPtr.Zero)
{
NativeMethods.CloseHandle(tokenHandle);
}
if (dupeTokenHandle != IntPtr.Zero)
{
NativeMethods.CloseHandle(dupeTokenHandle);
}
}
}
///
/// Gets current WindowsIdentity
///
/// Current WindowsIdentity
public static WindowsIdentity GetCurrentWindowsIdentity()
{
return WindowsIdentity.GetCurrent();
}
}
}