【问题标题】:Different Claims in one Session一次会议中的不同索赔
【发布时间】:2015-02-10 22:15:36
【问题描述】:

以下三种检索索赔的方法有什么不同?

在 ApiController 中调用:

((ClaimsIdentity) HttpContext.Current.User.Identity).Claims
((ClaimsIdentity) Thread.CurrentPrincipal.Identity).Claims

((ClaimsIdentity) User.Identity).Claims

前两个属性存储了相同的数据,但最后一个属性存储了上一个会话的数据。

这是在注销方法中完成的:

UserCache.Instance.Clear();
FederatedAuthentication.SessionAuthenticationModule.SignOut();
HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(string.Empty), null);

更新

混合 WebForms、WebApi、MVC 应用程序

大部分应用程序都是使用 WebForms 构建的。

【问题讨论】:

    标签: asp.net asp.net-identity


    【解决方案1】:

    如果您正在使用 WebApi,那么 HttpContext.Current 不应该直接可用 (see this answer)。所以我猜你也在使用 MVC,你会在那里看到 MVC 上下文。

    Thread.CurrentPrincipal 使用起来很危险,因为它包含线程原理,这可能是您意想不到的,例如实际运行 IIS 的用户(AppPool 用户)。大多数时候它是你的想法,但有时不是。这将导致您无休止地追逐错误,您永远无法重新创建自己。

    User.Identity as ClaimsIdentity 是获取所需内容的正确方法,它在 VS 的默认模板中使用。但是,如果您看到“上一个会话”中的数据 - 意味着您的 cookie 未正确清除。而且您注销用户的方式看起来很可疑:

    1. 什么是UserCache.Instance
    2. SignOut 方法在请求完成之前不会真正注销用户。因此,如果您调用它,然后在同一请求中检查用户身份,您将看到相同的身份完好无损。
    3. 分配HttpContext.Current.User 不会在请求中给您太多。如果我们谈论的是纯 WebAPI,请参阅第一点。

    默认退出是通过IAuthenticationManager完成的

        private IAuthenticationManager Authentication
        {
            get { return Request.GetOwinContext().Authentication; }
        }
    
        [Route("Logout")]
        public IHttpActionResult Logout()
        {
            Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
            return Ok();
        }
    

    试试这个,然后根据您的需要进行调整。

    【讨论】:

    • UserCache.Instance 是我们创建的,用来保存一些数据。我无法在 ApiController 中注销,因为我想尽可能避免重写我们的遗留代码。是否可以在 Global.asax.cs 中注销?是否允许创建 ApiController 的实例并调用其方法之一?
    • 不,在 Global.Asax 中注销是不可能的。如果可能的话,不应该在那里做。恐怕您必须修改控制器以允许注销。
    猜你喜欢
    • 2018-09-22
    • 2021-10-10
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多