0

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.

enter image description here

Neomaster
  • 166
  • 1
  • 7
  • 1
    Does this answer your question? [JwtSecurityToken doesn't expire when it should](https://stackoverflow.com/questions/39728519/jwtsecuritytoken-doesnt-expire-when-it-should) – Eugene May 14 '23 at 04:54

1 Answers1

0

I set the following parameter

ClockSkew = TimeSpan.Zero

enter image description here

Neomaster
  • 166
  • 1
  • 7