加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

模拟ASP.NET声明身份到Windows身份

发布时间:2020-12-16 07:39:44 所属栏目:asp.Net 来源:网络整理
导读:我有一个ASP.NET应用程序,它使用ADFS的声明基础身份验证.我还使用声明到 Windows身份服务将其映射到WindowsClaimsIdentity.这很好. 但现在我需要模拟当前的请求/线程,以便我可以访问不是声明感知的服务.我该怎么办? 我应该在Application_PostAuthenticate事
我有一个ASP.NET应用程序,它使用ADFS的声明基础身份验证.我还使用声明到 Windows身份服务将其映射到WindowsClaimsIdentity.这很好.

但现在我需要模拟当前的请求/线程,以便我可以访问不是声明感知的服务.我该怎么办?

我应该在Application_PostAuthenticate事件中获取一个WindowsImpersonationContext并将其保存在HttpContext.Items中,然后在Application_EndRequest中调用Undo方法吗?

或者还有其他首选方式吗?

更新:因为我没有得到任何关于模仿的首选方式的提示我尝试了自己的建议.我在global.asax.cs中创建了这段代码:

private static readonly string WICKey = typeof(System.Security.Principal.WindowsImpersonationContext).AssemblyQualifiedName;

    protected void Application_PostAuthenticateRequest()
    {
        var wid = User.Identity as System.Security.Principal.WindowsIdentity;
        if (wid != null)
        {
            HttpContext.Current.Trace.Write("PostAuthenticateRequest PreImpersonate: " + System.Security.Principal.WindowsIdentity.GetCurrent().Name);
            HttpContext.Current.Items[WICKey] = wid.Impersonate();
            HttpContext.Current.Trace.Write("PostAuthenticateRequest PostImpersonate: " + System.Security.Principal.WindowsIdentity.GetCurrent().Name);
        }
    }

    protected void Application_EndRequest()
    {
        var wic = HttpContext.Current.Items[WICKey] as System.Security.Principal.WindowsImpersonationContext;
        if (wic != null)
        {
            HttpContext.Current.Trace.Write("EndRequest PreUndoImpersonate: " + System.Security.Principal.WindowsIdentity.GetCurrent().Name);
            wic.Undo();
            HttpContext.Current.Trace.Write("EndRequest PostUndoImpersonate: " + System.Security.Principal.WindowsIdentity.GetCurrent().Name);
        }
    }

当我查看跟踪日志时,我看到了这一点

PostAuthenticateRequest PreImpersonate: NT AUTHORITYNETWORK SERVICE   
PostAuthenticateRequest PostImpersonate: MyDomainCorrectUser
Home: NT AUTHORITYNETWORK SERVICE
EndRequest PreUndoImpersonate: NT AUTHORITYNETWORK SERVICE
EndRequest PostUndoImpersonate: NT AUTHORITYNETWORK SERVICE

因此,在第二行中,您可以看到线程被正确模拟.但是在下一行中你会看到模仿已经丢失. (第三行来自控制器).

当我使用以下代码在本地模拟时,它工作正常:

var wid = User.Identity as System.Security.Principal.WindowsIdentity;
        if (wid != null)
        {
            using (var ctx = wid.Impersonate())
            {
                //Do something
            }
        }

但我想模仿整个请求的生命周期.
我该怎么办?

解决方法

你说后端服务不是声明.你能详细说明一下吗?你的意思是编译的代码不是声明的,但你有能力修改web.config文件?如果是这样,那么您可以尝试配置后端服务以通过在WSFederationAuthenticationModule,SessionAuthenticationModule和自定义ClaimsAuthorizationManager中使用WIF管道来进行authN,如果您还需要执行authZ.然后,当ASP.NET应用程序调用后端服务时,您可以使用WIF的ActAs或OnBehalfOf功能.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读