【问题标题】:setting HttpContext.Current.User from JWT Token从 JWT 令牌设置 HttpContext.Current.User
【发布时间】:2017-05-20 12:35:26
【问题描述】:

我正在使用 Microsoft.Owin.Security.Jwt nuget 包来保护我的 webapi。当我将令牌作为请求头传递给 webapi 时,它会按预期设置 HttpContext.Current.User。

由于业务逻辑被封装,我找不到设置 HttpContext.Current.User 的那一刻。

我不想一直使用 identity.Claims 搜索正确的声明,而是想提取我需要的信息,并将自定义类设置为 HttpContext.Current.User。是否可以使用 Microsoft.Owin.Security.Jwt?

【问题讨论】:

    标签: asp.net-web-api oauth-2.0 asp.net-web-api2 owin jwt


    【解决方案1】:

    不太清楚你的意思。 HttpContext.Current.User 会在您的令牌有效时自动设置(匹配密钥且未过期)。 您可以做的是编写一些扩展方法来检索其他值。例如:

    public static class IdentityHelpers
    {
        public static string GetUserId(this IIdentity identity) 
        {
            ClaimsIdentity claimsIdentity = identity as ClaimsIdentity;
    
            if (claimsIdentity.Claims.FirstOrDefault(x => x.Type == "UserId") != null) {
                return claimsIdentity.Claims.FirstOrDefault(x => x.Type == "UserId").Value;
            }
    
            return "0";
        }
    
        public static string GetUserName(this IIdentity identity) 
        {
            return identity.Name;
        }
    }
    

    然后您就可以调用例如:

    HttpContext.Current.user.GetUserName(); 
    

    HttpContext.Current.User.GetUserId();
    

    无论您在哪里包含该类。

    【讨论】:

    • 现在我正在解决这个问题。我想截取 Owin 设置此 HttpContext.Current.User 的那一刻,并使用从声明中提取的值设置一个自定义类。
    • 对不起,那帮不了你了。我发现整个 Owin 概念非常模糊,我也有很多帮助方法来检索我的声明,就像我在回答中展示的那样来克服这个问题。我会关注这个问题,希望有一个好的答案
    猜你喜欢
    • 1970-01-01
    • 2016-02-17
    • 2016-02-07
    • 2017-04-21
    • 2018-09-23
    • 1970-01-01
    • 2017-04-17
    • 2021-11-28
    • 2017-02-07
    相关资源
    最近更新 更多