被模拟时调用异步WCF服务

TGlicker

我在服务器上运行了WCF服务,该服务器被配置为接受Kerberos身份验证。

Kerberos可以正常工作,因此WCF服务可以知道哪个用户正在与其连接。该服务将所有内容作为异步方法提供。这里是这样的(只是为了清楚起见)。

public ExampleService : IExampleService {
    public Task<string> GetUsernameAsync() {
       return await Task.Run(() => System.Threading.Thread.CurrentPrincipal.Name);
    }
}

在客户端,我有一个控制器(这是一个MVC页面,但这并不重要),该控制器异步地调用方法。

public ExampleController {
    public async Task<ActionResult> Index() {
        using(var serviceClient = ServiceFactory.GetServiceClient())
        using(Security.Impersonation.Impersonate())
        {
            var data = await serviceClient.GetUsernameAsync();
            return View(data);
        }
    }
}

只要我不使用waiting,模拟就可以正常工作。

由于Task<>不会传递模拟的身份,因此我想知道是否存在某种可能性,可以更改的执行用户Task或进行任何其他操作以使模拟在此用例中正常工作。

我尝试了一个自定义的等待者(在这种情况下可以使用Culture来完成),但这根本不起作用(嗯,它也不能冒充他人)。

TGlicker

好的-经过更深入的研究,我终于找到了解决方案,该方案如何在异步任务之间传递模拟的Windows身份。

该解决方案在整个计算机范围内,并且将为所有(在这种情况下)64位ASP.NET 4.5应用程序设置。

在中找到aspnet.config文件C:\Windows\Microsoft.Net\Framework64\v4.0.30319(可能也适用于更高版本),然后将其值更改legacyImpersonationPolicy为false

<legacyImpersonationPolicy enabled="false"/>

确保重新启动IIS(或重新启动计算机)。
只要您使用托管方法进行模拟,这就会使模拟流动在我的情况下,我冒充了类似的东西,效果很好:

class Impersonation : IDisposable
    {
        public static Impersonation Impersonate()
        {
            return new Impersonation();
        }

        private WindowsImpersonationContext ImpersonationContext { get; set; }

        private Impersonation()
        {
            var currentIdentity = System.Threading.Thread.CurrentPrincipal.Identity as WindowsIdentity;
            if (currentIdentity != null && currentIdentity.IsAuthenticated)
            {
                ImpersonationContext = currentIdentity.Impersonate();
                return;
            }

            throw new SecurityException("Could not impersonate user identity");
        }

        public void Dispose()
        {
            if(ImpersonationContext != null)
                ImpersonationContext.Dispose();
        }
    }
}

此处说明了aspnet.config设置(顺便说一下,它无法在web.config文件中进行设置):http : //msdn.microsoft.com/zh-cn/library/ms229296 (v=vs.110 ) .aspx(它基本上说,如果这是真的,那么我们将以.NET 1.1的方式进行操作)

您可以使用以下方法检查Windows身份是否流通:

System.Security.SecurityContext.IsWindowsIdentityFlowSuppressed()

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章