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

前端 未结 4 1079
南笙
南笙 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: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 MethodName()
            {
                var userId = _userManager.GetUserId(HttpContext.User);
                //...
                return Ok();
            }
        }
    

    Read Other Claims:

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

提交回复
热议问题