using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;
public class Security
{
private IntPtr tokenHandle = new IntPtr(0);
private WindowsImpersonationContext impersonatedUser;
[DllImport("kernel32.dll")]
static extern bool CloseHandle(IntPtr handle);
// Test harness.
// If you incorporate this code into a DLL, be sure to demand FullTrust.
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public bool ImpersonateStart(string sDomainName, string userName, string Password)
{
bool returnValue;
WindowsIdentity newId = null;
try
{
tokenHandle = IntPtr.Zero;
// Call LogonUser to obtain a handle to an access token.
returnValue = false;
const int LOGON32_PROVIDER_DEFAULT = 0;
//This parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;
returnValue = LogonUser(userName, sDomainName, Password , LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle);
// check if logon successful
if ((returnValue == false))
{
int ret = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception(ret);
}
else
{
// Logon succeeded
// Use the token handle returned by LogonUser.
newId = new WindowsIdentity(tokenHandle);
impersonatedUser = newId.Impersonate();
}
}
catch (Exception ex)
{
ex = null;
returnValue = false;
}
finally
{
if (!(newId == null))
{
newId.Dispose();
newId = null;
}
}
return returnValue;
}
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public void ImpersonateStop()
{
try
{
// Stop impersonating the user.
impersonatedUser.Undo();
// Free the tokens.
if (tokenHandle != IntPtr.Zero)
{
CloseHandle(tokenHandle);
}
}
catch (System.Exception Return)
{
}
}
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
}
|