我试图Sytem.IntPtr
从服务调用中返回一个,以便客户端可以使用模拟来调用一些代码。如果不从 WCF 服务传回令牌,我的模拟代码可以正常工作。我不确定为什么这不起作用。我收到以下错误:
“用于模拟的令牌无效 - 无法复制。”
这是我的代码,除非我尝试将令牌从服务传递回 WinForm C# 客户端然后模拟。
[DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")]
public extern static bool DuplicateTokenEx(IntPtr ExistingTokenHandle, uint dwDesiredAccess, ref SECURITY_ATTRIBUTES lpThreadAttributes, int TokenType, int ImpersonationLevel, ref IntPtr DuplicateTokenHandle);
private IntPtr tokenHandle = new IntPtr(0);
private IntPtr dupeTokenHandle = new IntPtr(0);
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int Length;
public IntPtr lpSecurityDescriptor;
public bool bInheritHandle;
}
public enum SecurityImpersonationLevel
{
SecurityAnonymous = 0,
SecurityIdentification = 1,
SecurityImpersonation = 2,
SecurityDelegation = 3
}
public enum TokenType
{
TokenPrimary = 1,
TokenImpersonation = 2
}
private const int MAXIMUM_ALLOWED = 0x2000000;
[PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
public System.IntPtr GetWindowsUserToken(string UserName, string Password, string DomainName)
{
IntPtr tokenHandle = new IntPtr(0);
IntPtr dupTokenHandle = new IntPtr(0);
const int LOGON32_PROVIDER_DEFAULT = 0;
//This parameter causes LogonUser to create a primary token.
const int LOGON32_LOGON_INTERACTIVE = 2;
//Initialize the token handle
tokenHandle = IntPtr.Zero;
//Call LogonUser to obtain a handle to an access token for credentials supplied.
bool returnValue = LogonUser(UserName, DomainName, Password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle);
//Make sure a token was returned; if no populate the ResultCode and throw an exception:
int ResultCode = 0;
if (false == returnValue)
{
ResultCode = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception(ResultCode, "API call to LogonUser failed with error code : " + ResultCode);
}
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.bInheritHandle = true;
sa.Length = Marshal.SizeOf(sa);
sa.lpSecurityDescriptor = (IntPtr)0;
bool dupReturnValue = DuplicateTokenEx(tokenHandle, MAXIMUM_ALLOWED, ref sa, (int)SecurityImpersonationLevel.SecurityDelegation, (int)TokenType.TokenImpersonation, ref dupTokenHandle);
int ResultCodeDup = 0;
if (false == dupReturnValue)
{
ResultCodeDup = Marshal.GetLastWin32Error();
throw new System.ComponentModel.Win32Exception(ResultCode, "API call to DuplicateToken failed with error code : " + ResultCode);
}
//Return the user token
return dupTokenHandle;
}
知道我是否没有DuplicateTokenEx
正确使用调用吗?根据我在这里阅读的 MSDN 文档,我应该能够创建一个对委托有效的令牌,并在远程系统的上下文中使用。当使用“SecurityDelegation”时,服务器进程可以在远程系统上模拟客户端的安全上下文。
谢谢!