跨多个进程使用WindowsIdentity令牌
本文关键字:WindowsIdentity 令牌 进程 | 更新日期: 2023-09-27 18:19:34
我概述了以下架构:
API网关(Web API),仅可通过intranet使用,因此该站点配置为使用Windows身份验证。此API允许用户与Dll(C++非托管)进行交互,并且由于Dll提供的函数尚未准备好进行多用户交互,而且由于必须维护使用Dll时的状态,因此有一个windows服务负责调用Dll。因此,从本质上讲,用户向网关发出请求,然后网关使用WCF(命名管道)调用windows服务中的方法。在处理给定用户的第一个请求时,WCF会创建一个AppDomain,从中运行Dll代码。现在,应用程序用户被映射到具有读/写权限的SQL Server数据库用户(…),因此,在创建AppDomain以运行Dll时,必须在发起请求的用户的上下文中完成。到目前为止,不幸的是,这就是我所想出的,但没有奏效。
我的网关中有以下代码:
[Route("sessions/{sessionId}")]
[HttpPut]
public HttpResponseMessage CreateBalanceSession (Guid sessionId)
{
return Request.CreateResponse(GatewayBalanceProvider.Proxy.CreateSession(sessionId, WindowsIdentity.GetCurrent().Token)
? HttpStatusCode.OK
: HttpStatusCode.NotAcceptable, "Balance session could not be created");
}
在windows服务端,我得到了这个:
public bool CreateSession(Guid sessionId, IntPtr windowsUserToken)
{
var windowsPrincipal = new WindowsPrincipal(new WindowsIdentity(windowsUserToken));
}
当服务中的代码运行时,我得到了一个例外:
mscorlib.dll中出现"System.ArgumentException"类型的异常,但未在用户代码中处理
附加信息:用于模拟的令牌无效-不能重复。
很明显,我在这里缺少了一些东西,但我找不到它是什么。据我所知,令牌是在IIS进程的上下文中创建的,既然此时所有内容都是同步的,那么令牌不应该仍然有效吗?
欢迎任何帮助。
感谢
更新1
根据这些评论,我开始研究如何复制我完成的令牌,只需一个简单的Api32调用,并在同一过程中完成所有操作:
using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.ServiceModel;
namespace ConsoleApplication1
{
class Program
{
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, int dwLogonType, int dwLogonProvider, out IntPtr phToken);
[DllImport("advapi32.dll", SetLastError = true)]
public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, out IntPtr DuplicateTokenHandle);
public enum SecurityImpersonationLevel : int
{
SecurityAnonymous = 0,
SecurityIdentification = 1,
SecurityImpersonation = 2,
SecurityDelegation = 3,
}
static void Main(string[] args)
{
IntPtr token;
IntPtr tokenDuplicate;
if (LogonUser("xxxxx", "xxxxx", "xxxxx", 2, 0, out token))
{
if (DuplicateToken(token, (int)SecurityImpersonationLevel.SecurityImpersonation, out tokenDuplicate))
{
//var channel = new ChannelFactory<IBalanceProvider>(new NetNamedPipeBinding(),
// new EndpointAddress("net.pipe://localhost/balance")).CreateChannel();
//Test it we can use the duplicated token
var windowsIdentity = new WindowsIdentity(tokenDuplicate);
//channel.CreateSession(Guid.Parse("88fb01c7-41b5-4460-9ce5-fc72f9b0aa33"), tokenDuplicate);
}
}
}
}
}
我可以使用重复的令牌创建WindowsIdentity的新实例,问题是当我使用WCF通过有线将此令牌发送到另一个进程时,我仍然会收到重复的异常,这让我抓狂。我还需要做什么来确保复制的令牌可以在创建它的范围之外使用吗?
感谢
您查看过此页面吗?https://msdn.microsoft.com/en-us/library/ms730088(v=vs.110).aspx
如果没有看到这个代理是如何工作的,我不确定,但我希望您需要在AD中配置应用程序池运行的任何上下文(如果是网络服务,则为服务帐户或计算机帐户),以将WCF服务委托给运行的上下文。如果这两个帐户还没有,则还需要在它们上定义Kerberos SPN。