C# .net JwtSecurityTokenHandler jwttoken claims to object
HttpContext.User.Identity.MethodName();
C# .net JwtSecurityTokenHandler jwttoken claims to object
HttpContext.User.Identity.MethodName();
C# .net JwtSecurityTokenHandler jwttoken claims to object
In any controller from net core 2 that has gone through the authorize with the JwtBearerDefaults scheme, you can use:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
public ActionResult Index()
{
var user = User.FindFirst("Name").Value;
//or if u want the list of claims
var claims = User.Claims;
return View();
}
C# .net JwtSecurityTokenHandler jwttoken claims to object
public static ClaimsPrincipal ValidateToken(string jwtToken)
{
IdentityModelEventSource.ShowPII = true;
SecurityToken validatedToken;
TokenValidationParameters validationParameters = new TokenValidationParameters();
validationParameters.ValidateLifetime = true;
validationParameters.ValidAudience = _audience.ToLower();
validationParameters.ValidIssuer = _issuer.ToLower();
validationParameters.IssuerSigningKey = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey(Encoding.UTF8.GetBytes(_appSettings.Secret));
ClaimsPrincipal principal = new JwtSecurityTokenHandler().ValidateToken(jwtToken, validationParameters, out validatedToken);
return principal;
}
C# .net JwtSecurityTokenHandler jwttoken claims to object
You should be able to retrieve a claims like this within your controller
var identity = HttpContext.User.Identity as ClaimsIdentity;
if (identity != null)
{
IEnumerable<Claim> claims = identity.Claims;
// or
identity.FindFirst("ClaimName").Value;
}
If you wanted, you could write extension methods for the IPrincipal interface and retrieve claims using the code above, then retrieve them using (for example)
HttpContext.User.Identity.MethodName();
C# .net JwtSecurityTokenHandler jwttoken claims to object
var identity = HttpContext.User.Identity as ClaimsIdentity;
if (identity != null)
{
IEnumerable<Claim> claims = identity.Claims;
// or
identity.FindFirst("ClaimName").Value;
}
C# .net JwtSecurityTokenHandler jwttoken claims to object
// Cast to ClaimsIdentity.
var identity = HttpContext.User.Identity as ClaimsIdentity;
// Gets list of claims.
IEnumerable<Claim> claim = identity.Claims;
// Gets name from claims. Generally it's an email address.
var usernameClaim = claim
.Where(x => x.Type == ClaimTypes.Name)
.FirstOrDefault();
// Finds user.
var userName = await _userManager
.FindByNameAsync(usernameClaim.Value);
if (userName == null)
{
return BadRequest();
}
// The rest of your code goes here...
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us