Can't get claims from JWT token with ASP.NET Core

前端 未结 4 1080
南笙
南笙 2021-02-12 22:49

I\'m trying to do a really simple implementation of JWT bearer authentication with ASP.NET Core. I return a response from a controller a bit like this:

    var i         


        
相关标签:
4条回答
  • 2021-02-12 23:12

    You can't use ClaimsPricipal.Current in an ASP.NET Core application, as it's not set by the runtime. You can read https://github.com/aspnet/Security/issues/322 for more information.

    Instead, consider using the User property, exposed by ControllerBase.

    0 讨论(0)
  • 2021-02-12 23:28

    Access User.Claims instead of ClaimsPrinciple.Current.Claims.

    From Introduction to Identity at docs.asp.net:

    ...inside the HomeController.Index action method, you can view the User.Claims details.

    Here is the relevant source code from the MVC repository:

    public ClaimsPrincipal User
    {
       get
       {
           return HttpContext?.User;
       }
    }
    
    0 讨论(0)
  • 2021-02-12 23:29

    As part of ASP.NET Core 2.0, you can read the JWT Claims like Shaun described above. If you are only looking for the User Id (make sure you already add it as part of the claim using the "Sub" claim name) then you can use the following to two examples to read depending on your use case:

    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();
            }
        }
    
    0 讨论(0)
  • 2021-02-12 23:30

    With this solution, you can access the User.Identity and its claims in controllers when you're using JWT tokens:

    Step 1: create a 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 ? 1 : 0) : 1) != 0)
                {
                    AuthenticateResult authenticateResult = await ctx.AuthenticateAsync(schema);
                    if (authenticateResult.Succeeded && authenticateResult.Principal != null)
                        ctx.User = authenticateResult.Principal;
                }
                await next();
            }));
        }
    }
    

    Step 2: use it in Startup.cs:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseAuthentication();
        app.UseJwtTokenMiddleware();
    }
    
    0 讨论(0)
提交回复
热议问题