Reputation: 111
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
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
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:
You can find more information about this topic on the documentation page.
Upvotes: 0