【发布时间】:2020-06-12 03:49:51
【问题描述】:
我使用 .Net Core 作为我的 API,所以没有意见或任何意见。我还使用 ASP.net Core Identity 框架来授权我的数据库中的用户。 对于登录用户,我使用以下代码:
private string GenerateAuthenticationResult(ApplicationUser user)
{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_jwtSettings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
// Things to be included and encoded in the token
Subject = new ClaimsIdentity(new[]
{
new Claim(JwtRegisteredClaimNames.Sub, user.Email),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Email, user.Email),
new Claim("id", user.Id)
}),
// Token will expire 2 hours from which it was created
Expires = DateTime.UtcNow.AddHours(2),
//
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
这就像验证用户操作的魅力,但如果用户使用我之前提供的令牌登录他的请求标头(Bearer),我怎么知道我的服务器正在与谁交谈。
TL;博士
我想从请求标头中提供的令牌中提取用户 ID 或用户电子邮件。
谢谢。
【问题讨论】:
标签: rest api asp.net-core .net-core jwt