I expect to get a 401 error after token expiration, but it only happens after a long time... What am I doing wrong?
I set ValidateLifetime: true
.
Auth registration
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;
}
}
When I create a token, I add a few minutes to the current date-time in expires
parameter.
Creating access token
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;
}
}
Query
[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 registration
public static class Registrar
{
public static IRequestExecutorBuilder AddGraphQL(this IServiceCollection services) => services
.AddGraphQLServer()
.AddAuthorization()
.AddFiltering()
.AddSorting()
.AddErrorFilter<ErrorFilter>()
.AddQueryType<Query>()
.AddMutationType<Mutation>().AddMutationConventions()
...
;
}
To make a request with attribute [HotChocolate.Authorization.Authorize]
, I specify the token here. Once the token expires, no 401 error occurs.