Cannot get claims from JWT token using ASP.NET Core

I am trying to make a very simple JWT bearer authentication implementation using ASP.NET Core. I am returning a response from the controller 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 claims never appear.

  [Authorize] public async Task<IActionResult> Get() { var user = ClaimsPrincipal.Current.Claims; // Nothing here 
+9
source share
4 answers

You cannot use ClaimsPricipal.Current in an ASP.NET Core application because it is not installed by the runtime. You can read https://github.com/aspnet/Security/issues/322 for more information.

Instead, consider using the User property provided by ControllerBase .

+14
source

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

From an introduction to Identity at docs.asp.net :

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

Here is the corresponding source code from the MVC repository:

 public ClaimsPrincipal User { get { return HttpContext?.User; } } 
+8
source

As part of ASP.NET Core 2.0, you can read the JWT claims, such as Shaun, described above. If you are looking for a user ID (make sure you have already added it as part of the claim using the claim name “Sub”), you can use the following two examples to read, depending on your use case:

Read user id request:

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

Thanks to this solution, you can access User.Identiy and its statements in controllers using Jwt tokens:

Step 1: create 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(); } 
+1
source

Source: https://habr.com/ru/post/1258906/


All Articles