我期望在令牌过期后得到401错误,但它只会在很长一段时间后发生...我做错了什么?
我设置了ValidateLifetime: true
。
认证注册
public static class Registrar
{
public static IServiceCollection AddJWT(
this IServiceCollection services,
IConfiguration configuration)
{
var jwtOptionsSection = configuration.GetSection(nameof(JwtOptions));
var jwtOptions = jwtOptionsSection.Get<JwtOptions>();
services
.AddAuthorization(options =>
{
//options.FallbackPolicy = new AuthorizationPolicyBuilder()
// .RequireAuthenticatedUser()
// .Build();
})
.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 = jwtOptions.Issuer,
ValidAudience = jwtOptions.Audience,
IssuerSigningKey = new SymmetricSecurityKey(JwtSecrets.IssuerSigningKey),
};
});
services
.Configure<JwtOptions>(jwtOptionsSection)
.AddScoped<IAccessTokenService, AccessTokenService>()
.AddScoped<IRefreshTokenService, RefreshTokenService>()
.AddScoped<IGetAuthenticatedResultService, GetAuthenticatedResultService>();
return services;
}
}
当我创建一个令牌时,我在expires
参数中的当前日期时间上添加了几分钟。
创建访问令牌
internal class AccessTokenService : IAccessTokenService
{
private readonly JwtOptions _jwtOptions;
public AccessTokenService(IOptionsSnapshot<JwtOptions> options)
{
_jwtOptions = options.Value;
}
public string Get(IEnumerable<Claim> claims)
{
var securityKey = new SymmetricSecurityKey(JwtSecrets.IssuerSigningKey);
var signingCredentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
claims: claims,
signingCredentials: signingCredentials,
issuer: _jwtOptions.Issuer,
audience: _jwtOptions.Audience,
expires: DateTime.Now.AddMinutes(_jwtOptions.AccessTokenExpiryMinutes)); // !
var tokenString = new JwtSecurityTokenHandler().WriteToken(token);
return tokenString;
}
}
查询
[ExtendObjectType(typeof(Query))]
public class UserQuery
{
[Authorize] // <-- using HotChocolate.Authorization;
[UseOffsetPaging(IncludeTotalCount = true, DefaultPageSize = 20)]
[UseFiltering]
[UseSorting]
public IQueryable<User> GetUsers(IDbRepository<User> users) => users.Get();
}
GraphQL注册
public static class Registrar
{
public static IRequestExecutorBuilder AddGraphQL(this IServiceCollection services) => services
.AddGraphQLServer()
.AddAuthorization()
.AddFiltering()
.AddSorting()
.AddErrorFilter<ErrorFilter>()
.AddQueryType<Query>()
.AddMutationType<Mutation>().AddMutationConventions()
...
;
}
要发出具有[HotChocolate.Authorization.Authorize]
属性的请求,我在这里指定令牌。一旦令牌过期,不会发生401错误。
1条答案
按热度按时间dbf7pr2w1#
我设置了以下参数