寻找解决方案!
将 ClockSkew 设置为 TimeSpan.Zero
我想使用 ASP.NET Core Identity 框架并通过 JWT 进行身份验证。
我已注入身份:
builder.Services.AddIdentity<AppUser, IdentityRole>(options =>
{
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequireLowercase = false;
options.Password.RequireDigit = false;
options.Password.RequiredUniqueChars = 1;
options.Password.RequiredLength = 8;
options.Lockout.AllowedForNewUsers = true;
options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
})
.AddEntityFrameworkStores<ApplicationDbContext>();
和 JWT 中间件:
builder.Services
.AddAuthentication(options =>
{
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, config =>
{
var _configuration = builder.Configuration;
JwtSettings jwtSettings = _configuration.GetSection("Auth").Get<AuthSettings>()!.Jwt; // We already check null
var secretKey = jwtSettings.Key;
config.TokenValidationParameters = new TokenValidationParameters()
{
ValidIssuer = jwtSettings.Issuer,
ValidAudience = jwtSettings.Audience,
ValidateAudience = true,
ValidateIssuer = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey)),
ClockSkew = TimeSpan.Zero // since by default the token is valid for 5 minutes,
// you need to manually configure these properties,
// which is why you can make the token valid for less than 5 minutes
};
});
控制器有一个
Login
方法,其属性为 [Authorize]
:
[Authorize()]
[HttpGet()]
public IActionResult Secret()
{
return Ok();
}
世代代币
public string GenerateAccessToken(IEnumerable<Claim> claims)
{
var jwtSettings = _authSettings.Jwt;
var secretKey = jwtSettings.Key;
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
jwtSettings.Issuer,
jwtSettings.Audience,
claims,
expires: DateTime.Now.ToUniversalTime(),,
signingCredentials: signingCredentials
);
return new JwtSecurityTokenHandler().WriteToken(token);
}
但是当我发送带有已过期令牌的请求时,它会得到验证。在
TokenService
中,我生成了过期日期为“现在”的 JWT。
我使用
UserManager
和 SignInManager
来授权用户。
有什么问题吗?
我已经尝试过更改 Identity 和 JWT 实现的顺序。
TokenValidationParameters.ClockSkew
的默认值为 5 分钟。您可以将该值设置为较低的值。