D.B*_*D.B 13 c# jwt asp.net-core
我已经构建了一个在ASP.NET Core中使用JWT承载认证的应用程序.在进行身份验证时,我定义了一些我需要在另一个WebAPI控制器中读取的自定义声明,以便执行某些操作.
任何想法我如何实现这一目标?
我的代码如下所示:(代码已经简化)
public async Task<IActionResult> AuthenticateAsync([FromBody] UserModel user)
{
..............
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim("userSecurityKey", userDeserialized.SecurityKey.ToString()),
new Claim("timeStamp",timeStamp),
new Claim("verificationKey",userDeserialized.VerificationKey.ToString())
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key),
SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
.................
}
Run Code Online (Sandbox Code Playgroud)
另一个控制器:(需要阅读"verificationKey"声明.)
[HttpGet]
[Route("getcandidate")]
public async Task<IActionResult> GetCandidateAsync()
{
try
{
............
var verificationKey = //TODO: GET VerificationKey FROM THE TOKEN
var verificationRecord = await service.GetVerificationRecordAsync(verificationKey);
.................
}
catch (Exception)
{
return NotFound();
}
}
Run Code Online (Sandbox Code Playgroud)
Adr*_*ni6 33
您应该能够在控制器中检索此类声明
var identity = HttpContext.User.Identity as ClaimsIdentity;
if (identity != null)
{
IEnumerable<Claim> claims = identity.Claims;
// or
identity.FindFirst("ClaimName").Value;
}
Run Code Online (Sandbox Code Playgroud)
如果您愿意,您可以为IPrincipal接口编写扩展方法并使用上面的代码检索声明,然后使用(例如)检索它们
HttpContext.User.Identity.MethodName();
Run Code Online (Sandbox Code Playgroud)
为了完整的答案.要解码JWT令牌,让我们编写一个方法来验证令牌并提取信息.
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;
}
Run Code Online (Sandbox Code Playgroud)
现在我们可以使用以下方法验证和提取声明:
ValidateToken(tokenString)?.FindFirst("ClaimName")?.Value
您应该注意,null如果验证失败,ValidateToken方法将返回值.
解码 JWT 并获取声明的一种方法是使用System.IdentityModel.Tokens
public string getJWTTokenClaim(string token, string claimName)
{
try
{
var tokenHandler = new JwtSecurityTokenHandler();
var securityToken = (JwtSecurityToken)tokenHandler.ReadToken(token);
var claimValue = securityToken.Claims.FirstOrDefault(c => c.Type == claimName)?.Value;
return claimValue;
}
catch (Exception)
{
//TODO: Logger.Error
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
// 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...
Run Code Online (Sandbox Code Playgroud)
小智 5
在通过 JwtBearerDefaults 方案授权的 net core 2 的任何控制器中,您可以使用:
[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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
26379 次 |
| 最近记录: |