如何扮演另一个帐号(C#实现)
using directives#region Using directives
using System;
using SystemSecurityPrincipal;
using SystemRuntimeInteropServices;
using SystemTextRegularExpressions;
#endregion
namespace Impersonal
{
class Program
{
测试代码#region 测试代码
public static void Main(string[] args)
{
ConsoleWriteLine(当前用户是:
+ WindowsIdentityGetCurrent()Name);
ImpersonatedWork testDel = new ImpersonatedWork(Test);
ImpersonateAndDo(epro\\liping testDel);
ConsoleWriteLine(当前用户是:
+ WindowsIdentityGetCurrent()Name);
}
static void Test()
{
ConsoleWriteLine(当前用户是:
+ WindowsIdentityGetCurrent()Name);
}
#endregion
[DllImport(advapidll SetLastError = true)]
public extern static bool LogonUser(String lpszUsername String lpszDomain
String lpszPassword int dwLogonType
int dwLogonProvider ref IntPtr phToken);
[DllImport(kerneldll CharSet = CharSetAuto)]
public extern static bool CloseHandle(IntPtr handle);
[DllImport(advapidll CharSet = CharSetAuto SetLastError = true)]
public extern static bool DuplicateToken(IntPtr ExistingTokenHandle
int SECURITY_IMPERSONATION_LEVEL ref IntPtr DuplicateTokenHandle);
public delegate void ImpersonatedWork();
/**//// <summary>
/// 以指定用户的身份去做一件事情
/// </summary>
/// <param name=UserName></param>
/// <param name=PWD></param>
/// <param name=WhatToDo></param>
public static void ImpersonateAndDo(string UserName string PWD ImpersonatedWork WhatToDo)
{
扮演用户#region 扮演用户
string domainName = stringEmpty;
string userName = stringEmpty;
IntPtr tokenHandle = new IntPtr();
IntPtr dupeTokenHandle = new IntPtr();
const int LOGON_PROVIDER_DEFAULT = ;
const int LOGON_LOGON_INTERACTIVE = ;
const int SecurityImpersonation = ;
if (! RegexIsMatch(UserName @^\w+[\\]?\w+$))
{
throw new ApplicationException(非法的用户名);
}
string[] tmp = UserNameSplit(new char[] { \\ });
if (tmpLength > )
{
domainName = tmp[];
userName = tmp[];
}
else
{
userName = tmp[];
}
tokenHandle = IntPtrZero;
dupeTokenHandle = IntPtrZero;
bool returnValue = LogonUser(userNamedomainName PWD
LOGON_LOGON_INTERACTIVE LOGON_PROVIDER_DEFAULT
ref tokenHandle);
if (!returnValue)
{
throw new ApplicationException(取Handle出错了!);
}
//ConsoleWriteLine(当前用户是:
// + WindowsIdentityGetCurrent()Name);
bool retVal = DuplicateToken(tokenHandle SecurityImpersonation ref dupeTokenHandle);
if (!retVal)
{
CloseHandle(tokenHandle);
throw new ApplicationException(复制Handle出错了!);
}
WindowsIdentity newId = new WindowsIdentity(dupeTokenHandle);
WindowsImpersonationContext impersonatedUser = newIdImpersonate();
#endregion
以新用户身份调用#region 以新用户身份调用
WhatToDo();
#endregion
取消扮演#region 取消扮演
impersonatedUserUndo();
if (tokenHandle != IntPtrZero)
CloseHandle(tokenHandle);
if (dupeTokenHandle != IntPtrZero)
CloseHandle(dupeTokenHandle);
#endregion
}
}
}