Lakshan Umesh
Lakshan Umesh

Reputation: 111

ClaimsPrincipal does not work in ASP .Net core MVC web app

I need to get tenant id from claims when user log into my application. This is totally works fine with ASP .Net 4.7 Mvc app. But it didn't works inside asp .net core mvc app (3.1).

var tenantId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value; 

Its keep getting "Object reference not set to an instance of an object" this error.

Upvotes: 0

Views: 3791

Answers (2)

Varun Sood
Varun Sood

Reputation: 11

For .Net Core 3.1 put, using System.IdentityModel.Tokens.Jwt;

For Controller:

var token = HttpContext.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
var tokenClaims = new JwtSecurityToken(token.Replace("Bearer ", string.Empty));
var oid = tokenClaims.Payload["oid"].ToString();

For SignalRHub OnConnectedAsync():

var token = new JwtSecurityToken(Context.User.Identities.FirstOrDefault(x => x.IsAuthenticated).BootstrapContext.ToString());
var oid = token.Claims.FirstOrDefault(m => m.Type == "oid").Value;

Upvotes: 1

kristofke
kristofke

Reputation: 295

ClaimsPrincipal.Current isn't set in ASP.NET Core. Instead, it uses dependency injection to provide dependencies such as the current user's identity.

There are several options for retrieving the current authenticated user's ClaimsPrincipal:

  • ControllerBase.User (MVC controller)
  • HttpContext.User (middleware)
  • Passed in from caller (libraries without access to HttpContext)
  • IHttpContextAccessor (when passing around the user's identity too much)

You can find more information about this topic on the documentation page.

Upvotes: 0

Related Questions