【发布时间】:2020-02-09 01:56:21
【问题描述】:
这就是我为我的.NET Core API 创建 JWT 令牌的方式,它工作得非常好,但我想实现在 HTTP 请求来请求它时撤销、禁用或无效 JWT 令牌的可能性,使用令牌在标题中。
我可以想到一种方法,将令牌存储在我的数据库中,并有一个 boolean 列指示令牌是否处于活动状态,但是有没有办法在不将令牌存储在数据库中的情况下做到这一点全部?
public UserAuthenticationResponse CreateToken(UserAuthenticationRequest userAuth)
{
var user = // try to find user in database...
if (user == null)
{
return null;
}
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim("user_id", userAuth.Id),
}),
Expires = DateTime.UtcNow.AddMinutes(5),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var authenticatedUser = new UserAuthenticationResponse();
authenticatedUser.Id = user.Id;
authenticatedUser.Token = tokenHandler.WriteToken(token);
return authenticatedUser;
}
【问题讨论】:
-
首先考虑jwt是否是最适合您的授权形式,然后阅读stackoverflow.com/questions/21978658/…
标签: .net-core jwt asp.net-core-webapi