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

use*_*734 13 c# claims-based-identity jwt asp.net-core

我正在尝试使用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())
       );
Run Code Online (Sandbox Code Playgroud)

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

app.UseJwtBearerAuthentication(new JwtBearerOptions
{
     AutomaticAuthenticate = true,
     AutomaticChallenge = true,
     TokenValidationParameters = tokenValidationParameters
});
Run Code Online (Sandbox Code Playgroud)

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

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

Kév*_*let 17

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

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


Sha*_*tin 9

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

从docs.asp.net上的介绍到身份:

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

以下是 MVC存储库的相关源代码:

public ClaimsPrincipal User
{
   get
   {
       return HttpContext?.User;
   }
}
Run Code Online (Sandbox Code Playgroud)


Ton*_*ony 6

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

读取用户 ID 声明:

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

阅读其他声明:

    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();
        }
    }
Run Code Online (Sandbox Code Playgroud)


小智 5

通过此解决方案,您可以User.Identity在使用 JWT 令牌时访问控制器中的 及其声明:

第1步:创建JwtTokenMiddleware:

public static class JwtTokenMiddleware
{
    public static IApplicationBuilder UseJwtTokenMiddleware(
      this IApplicationBuilder app,
      string schema = "Bearer")
    {
        return app.Use((async (ctx, next) =>
        {
            IIdentity identity = ctx.User.Identity;
            if (identity != null && !identity.IsAuthenticated)
            {
                AuthenticateResult authenticateResult = await ctx.AuthenticateAsync(schema);
                if (authenticateResult.Succeeded && authenticateResult.Principal != null)
                    ctx.User = authenticateResult.Principal;
            }
            await next();
        }));
    }
}
Run Code Online (Sandbox Code Playgroud)

步骤2:在Startup.cs中使用它:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseAuthentication();
    app.UseJwtTokenMiddleware();
}
Run Code Online (Sandbox Code Playgroud)