Can't get claims from JWT token with ASP.NET Core
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 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())
);
I have Jwt middleware for incoming requests:
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = tokenValidationParameters
});
This seems to work to protect resources with the authorize attribute, but the claims never show up.
[Authorize]
public async Task<IActionResult> Get()
{
var user = ClaimsPrincipal.Current.Claims; // Nothing here
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
.
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 theUser.Claims
details.
Here is the relevant source code from the MVC repository:
public ClaimsPrincipal User
{
get
{
return HttpContext?.User;
}
}