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
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();
}
}