我想延长JWT令牌的寿命,但我不能。
我尝试谷歌搜索此事,并发现了对JwtBearerOptions.TokenValidationParameters.ClockSkew
的引用。
我还尝试提供1分钟20秒的时间跨度,但应用程序未考虑更改。
Startup.cs
:
services
.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters()
{
ClockSkew = TimeSpan.FromSeconds(20),
RequireExpirationTime = true,
RequireSignedTokens = true,
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
IssuerSigningKey = Configuration.GetSymmetricSecurityKey(),
ValidAudience = Configuration.GetValidAudience(),
ValidIssuer = Configuration.GetValidIssuer()
};
});
这是Authenticate
动作:
[AllowAnonymous]
[HttpPost]
public async Task<AuthenticateOutput> Authenticate([FromBody] AuthenticateInput input)
{
string subdomain = Request.GetSubDomain();
var user = await _userService.Authenticate(input.UserName, input.Password, subdomain);
if (user == null)
{
throw new Exception("Unauthorised");
}
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor
{
Issuer = _config.GetValidIssuer(),
Audience = _config.GetValidAudience(),
SigningCredentials = new SigningCredentials(_config.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256),
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
})
};
var token = tokenHandler.CreateToken(tokenDescriptor);
string tokenString = tokenHandler.WriteToken(token);
return new AuthenticateOutput() { UserId = user.Id, Token = tokenString };
}
我错过了什么吗?
答案 0 :(得分:1)
在令牌描述符中未定义的到期值。
var tokenDescriptor = new SecurityTokenDescriptor
{
Issuer = _config.GetValidIssuer(),
Audience = _config.GetValidAudience(),
SigningCredentials = new SigningCredentials(_config.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256),
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, user.UserName),
new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
}),
// expiration time here...
Expiration = _config.GetExpiration() // etc
};
答案 1 :(得分:0)
Bayram的答案有错别字,所以我认为我应该发表我的看法。
Expiration
中不存在属性SecurityTokenDescriptor
。是DateTime? Expires
。
DateTime expires = input.RememberMe ? DateTime.UtcNow.AddDays(5) : DateTime.UtcNow.AddMinutes(20);
var tokenDescriptor = new SecurityTokenDescriptor
{
Expires = expires,
...
完美工作!
答案 2 :(得分:0)
var token = new JwtSecurityToken(_config["Jwt:Issuer"], _config["Jwt:Issuer"],
claims, expires: DateTime.Now.AddMinutes(120)