模仿另外一个用户身份
日期: 2010-08-09 类别: C#, asp.net 发表评论最近有个需求,要获取远程服务器上的windows services的状态,不过我的账号没有权限,需要用其他的账户,这就需要模仿另外一个用户的身份。在msdn上找到了个例子,记录下来。
首先,要引入几个win32的api:
[DllImport("advapi32.dll", SetLastError = true)] public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)] public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL,ref IntPtr DuplicateTokenHandle); [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public extern static bool CloseHandle(IntPtr handle);
LogonUser尝试用一个用户名来登录本机,但不能登录远程机器,如果登录成功的话,将会返回一个句柄。
DuplicateToken复制一个已经存在的Token来创建一个新的access token
CloseHandle关闭一个对象句柄
然后声明如下几个变量/常量
WindowsImpersonationContext impersonationContext; IntPtr tokenHandle = new IntPtr(0); IntPtr dupeTokenHandle = new IntPtr(0); const int LOGON32_PROVIDER_DEFAULT = 0; //This parameter causes LogonUser to create a primary token. const int LOGON32_LOGON_INTERACTIVE = 2; const int SECURITY_IMPERSONATION_LEVEL = 2; tokenHandle = IntPtr.Zero; dupeTokenHandle = IntPtr.Zero;
之后调用LogonUser来登陆本机并获取句柄
bool returnValue = LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle);
// 如果调用失败,则抛出异常 if (false == returnValue) { int ret = Marshal.GetLastWin32Error(); throw new System.ComponentModel.Win32Exception(ret); }
复制句柄,其实这步是可以不需要的
bool retVal = DuplicateToken(tokenHandle, SECURITY_IMPERSONATION_LEVEL, ref dupeTokenHandle); if (false == retVal) { CloseHandle(tokenHandle); return; }
模拟用户
// 此处可以用LogonUser返回的tokenHandle, 也可以使用复制的dupeTokenHandle WindowsIdentity id = new WindowsIdentity(tokenHandle); WindowsImpersonationContext impersonatedUser = id.Impersonate(); // do someting
回复用户,并关闭句柄
// Stop impersonating the user. impersonatedUser.Undo(); // Free the tokens. if (tokenHandle != IntPtr.Zero) CloseHandle(tokenHandle);
参考资料
- LogonUser Function: http://msdn.microsoft.com/en-us/library/aa378184(VS.85).aspx
- DuplicateToken Function: http://msdn.microsoft.com/en-us/library/aa446616(VS.85).aspx
- CloseHandle Function: http://msdn.microsoft.com/en-us/library/ms724211(VS.85).aspx
- WindowsImpersonationContext: http://msdn.microsoft.com/en-us/library/system.security.principal.windowsimpersonationcontext.aspx
Stat.