Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 641
user888734 Avatar asked Oct 27 '16 17:10

user888734


People also ask

How do I get current user in .NET core Web API from JWT token?

It is a general requirement that, once the user is validated and received token and redirected to actual API to fetch or post the data. Here, if we want to fetch any information about a logged In user from API, we need to send userid/username to the API.

What is claim in JWT C#?

In a JWT, a claim appears as a name/value pair where the name is always a string and the value can be any JSON value. Generally, when we talk about a claim in the context of a JWT, we are referring to the name (or key). For example, the following JSON object contains three claims ( sub , name , admin ):

Is it possible to implement JWT with ASP NET Core?

3 I working on an ASP Net Core 2.1 Web API. I've implemented successfully JWT within my project. Everything with the Authorization works fine. Normally, when I need user claims, I know I can get them like this (E.g. Email claim):

Is it possible to retrieve JWT from httpcontext gettokenasync?

JWT cannot be retrieved by HttpContext.GetTokenAsync in .NET Core 2.1 0 Jwt Role authentication in controller ASP.net core 2.1 0 ASP .NET CORE 2.2 JWT & Claims identity Authentication for Website 1 Can't get asp .net core 2.2 to validate my JWT 0

What is the use of claims in JWT?

Claims in JWT Token are used to store key data (e.g. username, timezone, or roles) in the Token payload, besides the IssuedAt (i.e. iat), which is added by default. In.NET Core, Claims can be used without installing any additional package, it comes from the System.Security.Claims package.

Is there a good way to configure JWT token?

The current iteration of JWT Token setup in ASP.NET Core actually works very well, as long as you get the right incantations of config settings strung together. Part of the problem with Auth configuration is that most of settings have nothing to do with the problem at hand and deal with protocol ceremony.


2 Answers

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.

like image 182
Kévin Chalet Avatar answered Sep 21 '22 13:09

Kévin Chalet


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;
   }
}
like image 44
Shaun Luttin Avatar answered Sep 22 '22 13:09

Shaun Luttin