【问题标题】:How do i access the value of a custom type that i have stored in a Claim from Webapi controllers?如何从 Webapi 控制器访问存储在声明中的自定义类型的值?
【发布时间】:2021-03-18 10:39:06
【问题描述】:

我在自定义令牌生成中向 JWT 令牌添加了一些声明信息“id”

    var tokenDescriptor = new SecurityTokenDescriptor
    {
        Subject = new ClaimsIdentity(new[] { new Claim("id", user.Id.ToString()), new Claim( ClaimTypes.Role, user.Role ) }),
        Expires = DateTime.UtcNow.AddDays(7),
        SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
    };

当我尝试从声明中访问声明类型“id”时,它给了我一个运行时错误

访问声明的代码

public async Task<IActionResult> GetAll()
        {
            //var identity = HttpContext.User.Identity as ClaimsIdentity;
            //if (identity != null)
            //{
            //    IEnumerable<Claim> claims = identity.Claims;
            //    // or


            //}


            var id = User.FindFirst("id").Value;

        //some code here to access servce 
}

我在var id = User.FindFirst("id").Value; 行遇到错误

更新 这是显示用户有效且其“id”已添加到声明中的屏幕截图

更新

这是我的自定义授权属性

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class AuthorizeAttribute : Attribute, IAuthorizationFilter
    {

        public AuthorizeAttribute()
        {
            
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var user = (User)context.HttpContext.Items["User"];
            if (user == null)
            {
                // not logged in
                context.Result = new JsonResult(new { message = "Unauthorized" }) { StatusCode = StatusCodes.Status401Unauthorized };
            }
        }
    }

为什么它会引发错误以及如何访问声明中的“id”?

【问题讨论】:

  • 可能需要首先检查 在您的用户中定义的声明。几个问题:您的SecurityTokenDescriptor 何时被调用,您当前的经过身份验证的用户是在添加此代码之前创建的吗?
  • @Tieson T 是的,它是在 tokenGenerator 中创建的,并且 id 是从经过身份验证的用户中提取的
  • 不完全确定我们是否相互理解,但如果此安全令牌是在您尝试读取它的同一请求中创建的,您可能会遇到错误,因为令牌可能尚未传播到请求上下文。
  • @TiesonT。我用屏幕截图更新了我的原始帖子,显示声明具有“id”的值
  • @TiesonT。你是说用户不在 HttpsContext 中?

标签: c# asp.net-core asp.net-core-webapi


【解决方案1】:

我能够通过将当前经过身份验证的用户附加到 HttpContext 来解决此问题

【讨论】:

    猜你喜欢
    • 2021-02-16
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    • 2020-02-10
    • 2014-04-10
    • 1970-01-01
    • 1970-01-01
    • 2018-09-27
    相关资源
    最近更新 更多