首页 文章

无法使用ASP.NET Core从JWT令牌获取声明

提问于
浏览
5

我正在尝试使用ASP.NET Core实现一个非常简单的JWT承载认证实现 . 我从控制器返回一个响应,如下所示:

var identity = new ClaimsIdentity();
    identity.AddClaim(new Claim(ClaimTypes.Name, applicationUser.UserName));
        var jwt = new JwtSecurityToken(
             _jwtOptions.Issuer,
             _jwtOptions.Audience,
             identity.Claims,
             _jwtOptions.NotBefore,
             _jwtOptions.Expiration,
             _jwtOptions.SigningCredentials);

       var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt);

       return new JObject(
           new JProperty("access_token", encodedJwt),
           new JProperty("token_type", "bearer"),
           new JProperty("expires_in", (int)_jwtOptions.ValidFor.TotalSeconds),
           new JProperty(".issued", DateTimeOffset.UtcNow.ToString())
       );

我有传入请求的Jwt中间件:

app.UseJwtBearerAuthentication(new JwtBearerOptions
{
     AutomaticAuthenticate = true,
     AutomaticChallenge = true,
     TokenValidationParameters = tokenValidationParameters
});

这似乎有助于使用authorize属性保护资源,但声明永远不会出现 .

[Authorize]
    public async Task<IActionResult> Get()
    {
        var user = ClaimsPrincipal.Current.Claims; // Nothing here

3 回答

  • 7

    您不能在ASP.NET Core应用程序中使用 ClaimsPricipal.Current ,因为它不是由运行时设置的 . 您可以阅读https://github.com/aspnet/Security/issues/322以获取更多信息 .

    相反,请考虑使用由 ControllerBase 公开的 User 属性 .

  • 11

    访问 User.Claims 而不是 ClaimsPrinciple.Current.Claims .

    From Introduction to Identity at docs.asp.net

    ...在HomeController.Index操作方法中,您可以查看User.Claims详细信息 .

    来自MVC存储库的Here is the relevant source code

    public ClaimsPrincipal User
    {
       get
       {
           return HttpContext?.User;
       }
    }
    
  • 1

    作为ASP.NET Core 2.0的一部分,您可以像上面描述的Shaun一样阅读JWT声明 . 如果您只是在寻找用户ID(请确保您已使用“Sub”声明名称将其添加为声明的一部分),那么您可以根据您的使用情况使用以下两个示例来阅读:

    Read User ID Claim:

    public class AccountController : Controller
        {
            [Authorize]
            [HttpGet]
            public async Task<IActionResult> MethodName()
            {
                var userId = _userManager.GetUserId(HttpContext.User);
                //...
                return Ok();
            }
        }
    

    Read Other Claims:

    public class AccountController : Controller
        {
            [Authorize]
            [HttpGet]
            public async Task<IActionResult> MethodName()
            {
                var rolesClaim = HttpContext.User.Claims.Where( c => c.Type == ClaimsIdentity.DefaultRoleClaimType).FirstOrDefault();
                //...
                return Ok();
            }
        }
    

相关问题