我想增加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 };
}
我错过了什么吗?
expiration值中的expiration值未定义。
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
};
Bayram的答案中有一个错字,所以我想我应该发布我的。
Expiration
中不存在SecurityTokenDescriptor
属性。这是DateTime? Expires
。
DateTime expires = input.RememberMe ? DateTime.UtcNow.AddDays(5) : DateTime.UtcNow.AddMinutes(20);
var tokenDescriptor = new SecurityTokenDescriptor
{
Expires = expires,
...
完美的工作!