[英]Get information from bearer token
登錄成功后我有一個 jwt 並想從該令牌中獲取數據(令牌已編碼,包含使用 Claims 保存的信息)。 有沒有辦法使用 HttpContext.AuthenticateAsync(JwtBearerDefaults.AuthenticationScheme) 從承載令牌獲取數據? 我不知道如何從收到的令牌中獲取數據。 這是我的代碼。
public async Task<TokenResponse> Login(string username, string password)
{
var user = await dataContext.Users
.FirstOrDefaultAsync(x => x.Username == username && x.Password == password.Encrypt())
?? throw new BadRequestExceptions("Wrong username or password");
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
new Claim(ClaimTypes.Role, user.Role.ToString()),
new Claim(ClaimTypes.GivenName,user.Name),
new Claim(ClaimTypes.Upn, user.Username)
};
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(tokenConfig.Key));
var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
var tokenString = new JwtSecurityToken(tokenConfig.Issuer, tokenConfig.Audience, claims: claims, signingCredentials: signingCredentials);
tokenResponse = new TokenResponse()
{
Token = new JwtSecurityTokenHandler().WriteToken(tokenString)
};
return tokenResponse;
}
從令牌中獲取數據的最佳方法(假設您有多個數據要檢索)是擴展(擴展方法)ClaimsPrincipal,然后您可以從程序集中的任何位置調用您在該類中擴展的任何方法。 在下面找到一個示例:
public static class ClaimsPrincipalExtensions
{
public static string GetUsername(this ClaimsPrincipal user)
{
return user.FindFirst(ClaimTypes.Name)?.Value;
}
public static int GetUserId(this ClaimsPrincipal user)
{
return int.Parse(user.FindFirst(ClaimTypes.NameIdentifier)?.Value);
}
}
然后在您的控制器操作中的某處,您可以調用User.GetUsername()和User.GetUserId()
但是,如果您只需要檢索一兩條記錄,那么這就足夠了:
int userId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value)
快樂編碼!!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.