js-cookie设置token过期时间_详解ASP.NET Core Web Api之JWT刷新Token_实用技巧
时间: 2024-02-27 08:54:18 浏览: 262
好的,我了解您的问题。关于js-cookie设置token过期时间,我们可以通过设置cookie的expires属性来实现。示例代码如下:
```
// 设置cookie过期时间为1小时
Cookies.set('token', 'your_token', { expires: 1/24 });
// 获取cookie过期时间
var expires = new Date(Cookies.get('token')).toUTCString();
console.log('token过期时间:' + expires);
```
另外,关于ASP.NET Core Web Api之JWT刷新Token,我们可以通过设置Token过期时间,并在Token过期前刷新Token来实现。示例代码如下:
```
// 在Startup.cs中设置Token认证
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["Jwt:Issuer"],
ValidAudience = Configuration["Jwt:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
}
};
});
// 在Token过期前刷新Token
[HttpPost("refresh-token")]
public async Task<IActionResult> RefreshToken([FromBody] TokenRequestModel model)
{
var principal = GetPrincipalFromExpiredToken(model.Token);
var username = principal.Identity.Name; //retrieve the username of the person we are refreshing
var user = await _userManager.FindByNameAsync(username);
if (user == null || user.RefreshToken != model.RefreshToken || user.RefreshTokenExpiryTime <= DateTime.UtcNow)
{
return BadRequest("Invalid client request");
}
var newJwtToken = GenerateJwtToken(user);
var newRefreshToken = GenerateRefreshToken();
user.RefreshToken = newRefreshToken;
await _userManager.UpdateAsync(user);
return new ObjectResult(new TokenResponseModel
{
Token = newJwtToken,
RefreshToken = newRefreshToken
});
}
// 获取Token中的Principal
private ClaimsPrincipal GetPrincipalFromExpiredToken(string token)
{
var tokenValidationParameters = new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"])),
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(token, tokenValidationParameters, out var securityToken);
var jwtSecurityToken = securityToken as JwtSecurityToken;
if (jwtSecurityToken == null || !jwtSecurityToken.Header.Alg.Equals(SecurityAlgorithms.HmacSha256, StringComparison.InvariantCultureIgnoreCase))
throw new SecurityTokenException("Invalid token");
return principal;
}
// 生成新的JWT Token
private string GenerateJwtToken(User user)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim("userId", user.Id.ToString())
};
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var expires = DateTime.UtcNow.AddMinutes(Convert.ToDouble(Configuration["Jwt:ExpireMinutes"]));
var token = new JwtSecurityToken(
Configuration["Jwt:Issuer"],
Configuration["Jwt:Issuer"],
claims,
expires: expires,
signingCredentials: creds
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
// 生成新的Refresh Token
private string GenerateRefreshToken()
{
var randomNumber = new byte[32];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(randomNumber);
return Convert.ToBase64String(randomNumber);
}
}
```
希望这些代码对您有所帮助!
阅读全文