【发布时间】:2018-08-19 20:28:47
【问题描述】:
我正在处理 JWT 及其刷新令牌,但找不到一个可以同时提供性能和安全性的良好工作示例。
性能:: 每次刷新令牌时都不能访问数据库。
安全性:: 由于生命周期长,刷新令牌应该是超级机密而不是访问令牌。
所以我尝试结合使用内存缓存和过期令牌声明来实现我自己的:
第 1 步。
a) 成功登录后,生成具有 JwtRegisteredClaimNames.Jti 声明类型中唯一 GUID 的访问令牌..
b) 然后生成refresh-token,并以关联的jti access-token值(唯一GUID)作为key保存在memoryCache中
c) 两者都发送到客户端应用程序并存储在 localStorage 中。
第 2 步。
a)access-token 过期后,access-token 和 refresh-token 都会发送到刷新控制器。
b) 然后 jti 在过期令牌中声明作为缓存键发送到 memoryCache 以从内存中获取刷新令牌。
c) 检查 -send refresh-token 和 -in-memory refresh-token 的相等性后,如果相等,则生成 access-token 和 refresh-token 的新实例并将其发送回客户端应用程序。
AuthService.cs
private readonly IConfiguration _configuration;
private readonly IMemoryCache _memoryCache;
private readonly Claim _jtiClaim;
public AuthService(IConfiguration configuration, IMemoryCache memoryCache)
{
_configuration = configuration;
_memoryCache = memoryCache;
_jtiClaim = new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString());
}
public string GenerateAccessToken(IList<Claim> claims)
{
claims.Add(_jtiClaim);
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtConfiguration:JwtKey"]));
var jwtToken = new JwtSecurityToken(
issuer: _configuration["JwtConfiguration:JwtIssuer"],
audience: _configuration["JwtConfiguration:JwtIssuer"],
claims: claims,
notBefore: DateTime.UtcNow,
expires: DateTime.UtcNow.AddMinutes(int.Parse(_configuration["JwtConfiguration:JwtExpireMins"])),
signingCredentials: new SigningCredentials(key, SecurityAlgorithms.HmacSha256)
);
return new JwtSecurityTokenHandler().WriteToken(jwtToken);
}
public string GenerateRefreshToken(ClientType clientType)
{
var randomNumber = new byte[32];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(randomNumber);
var token = Convert.ToBase64String(randomNumber);
var refreshToken = JsonConvert.SerializeObject(new RefreshToken(token, _jtiClaim.Value, clientType));
_memoryCache.Set(_jtiClaim.Value, refreshToken, new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromDays(7)));
return token;
}
}
public RefreshToken GetRefreshToken(string jtiKey)
{
if (!_memoryCache.TryGetValue(jtiKey, out string refreshToken)) return null;
_memoryCache.Remove(jtiKey);
return JsonConvert.DeserializeObject<RefreshToken>(refreshToken);
}
public ClaimsPrincipal GetPrincipalFromExpiredToken(string accessToken)
{
var tokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtConfiguration:JwtKey"])),
ValidateLifetime = false //here we are saying that we don't care about the token's expiration date
};
var tokenHandler = new JwtSecurityTokenHandler();
var principal = tokenHandler.ValidateToken(accessToken, tokenValidationParameters, out var securityToken);
if (!(securityToken is JwtSecurityToken jwtSecurityToken) || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
throw new SecurityTokenException("Invalid token");
return principal;
}
AuthController.cs
private readonly SignInManager<User> _signInManager;
private readonly UserManager<User> _userManager;
private readonly AuthService _authService;
private readonly IMemoryCache _memoryCache;
private readonly DataContext _context;
public AuthController(UserManager<User> userManager, AuthService authService,
SignInManager<User> signInManager, DataContext context)
{
_userManager = userManager;
_authService = authService;
_signInManager = signInManager;
_context = context;
}
[HttpPost]
public async Task<ActionResult> Login([FromBody] LoginDto model)
{
var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false);
if (!result.Succeeded) return BadRequest(new { isSucceeded = result.Succeeded, errors= "INVALID_LOGIN_ATTEMPT" });
var appUser = _userManager.Users.Single(r => r.Email == model.Email);
return Ok(new
{
isSucceeded = result.Succeeded,
accessToken = _authService.GenerateAccessToken(GetClaims(appUser)),
refreshToken = _authService.GenerateRefreshToken(model.ClientType)
});
}
[HttpPost]
public ActionResult RefreshToken([FromBody] RefreshTokenDto model)
{
var principal = _authService.GetPrincipalFromExpiredToken(model.AccessToken);
var jtiKey = principal.Claims.Single(a => a.Type == JwtRegisteredClaimNames.Jti).Value;
var refreshToken = _authService.GetRefreshToken(jtiKey);
if (refreshToken == null)
return BadRequest("Expired Refresh Token");
if (refreshToken.Token != model.RefreshToken)
return BadRequest("Invalid Refresh Token");
return Ok(new
{
isSucceeded = true,
accessToken = _authService.GenerateAccessToken(principal.Claims.SkipLast(1).ToList()),
refreshToken = _authService.GenerateRefreshToken(model.ClientType)
});
}
我不确定这是刷新令牌的良好实现,因为刷新令牌可能在客户端应用程序中受到损害。
你能建议我一个更好的解决方案吗?
【问题讨论】:
标签: asp.net-web-api .net-core jwt memorycache refresh-token