从 WebAPI 控制器获取声明 - JWT 令牌, [英] Get claims from a WebAPI Controller - JWT Token,
问题描述
我已经构建了一个在 ASP.NET Core 中使用 JWT 承载身份验证的应用程序.身份验证时,我定义了一些自定义声明,我需要在另一个 WebAPI 控制器中读取这些声明以执行某些操作.
I have built an application which uses JWT bearer authentication in ASP.NET Core. When authenticating I define some custom claims which i need to read in another WebAPI controller in order to execute some actions.
有什么想法我怎样才能做到这一点?
Any ideas How Can I achieve this?
我的代码是这样的:(代码已经简化)
This how my code looks like:(Code has been simplified)
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);
.................
}
另一个控制器:(它需要阅读verificationKey"声明.)
Another controller: (It Needs to read "verificationKey" claim.)
[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();
}
}
推荐答案
你应该能够在你的控制器中检索这样的声明
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;
}
如果需要,您可以为 IPrincipal 接口编写扩展方法并使用上面的代码检索声明,然后使用(例如)检索它们
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();
<小时>
为了答案的完整性.为了解码 JWT 令牌,让我们编写一个方法来验证令牌并提取信息.
For completeness of the answer. To Decode the JWT token let's write a method to validate the token and extract the information.
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;
}
现在我们可以使用以下方法验证和提取声明:
Now we can validate and extract the Claims by using:
ValidateToken(tokenString)?.FindFirst("ClaimName")?.Value
您应该注意,如果验证失败,ValidateToken 方法将返回 null
值.
You should note that the ValidateToken method will return null
value if the validation fails.
这篇关于从 WebAPI 控制器获取声明 - JWT 令牌,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!