0

In order to generate JWT token I am using the following code:

  var tokenHandler = new JwtSecurityTokenHandler();

            var key = Encoding.ASCII.GetBytes(_consumerConfiguration.SecretKey);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, "ConsumerId")
                }),
                Expires = DateTime.Now.AddMinutes(1),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);

This is my code in RegisterServices

  var appSettingsSection = configuration.GetSection("ConsumerConfiguration");
            services.Configure<ConsumerConfiguration>(appSettingsSection);

            var appSettings = appSettingsSection.Get<ConsumerConfiguration>();

            var key = Encoding.ASCII.GetBytes(appSettings.SecretKey);
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });
            services.AddScoped<Microsoft.AspNetCore.Authorization.IAuthorizationHandler, ConsumerAuthorizationHandler>();

I using this as a filter to register the custom authorization handler globally in the application:

 var policy = new AuthorizationPolicyBuilder().RequireCustomClaim(ClaimTypes.Name).
                AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme).Build();

options.Filters.Add(new AuthorizeFilter(policy));
            })

and this is my custom authorization handler

    #region constructor
    public ConsumerAuthorizationHandler(IOptions<ConsumerConfiguration> consumerConfiguration)
    {
        _consumerConfiguration = consumerConfiguration.Value;
    }
    #endregion
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CustomRequireClaim requirement)
    {
        if (!_consumerConfiguration.EnableAuthorizationFilter)
            context.Succeed(requirement);

        var hasClaim = context.User.Claims.Any(x => x.Type == requirement.ClaimType);

        if (hasClaim)
        {
            context.Succeed(requirement);
        }

        return Task.CompletedTask;
    }
}

public static class AuthorizationPolicyBuilderExtensions
{
    public static AuthorizationPolicyBuilder RequireCustomClaim(this AuthorizationPolicyBuilder builder, string claimType)
    {
       return builder.AddRequirements(new CustomRequireClaim(claimType));
    }
}

The problem is: How can I check if the JWT is expired? The token seems not to expire. What code do I have to add that it will check if the token is expired?

jps
  • 20,041
  • 15
  • 75
  • 79
Aamir
  • 95
  • 1
  • 10
  • Please share your `ConsumerConfiguration` and `CustomRequireClaim`.For how to check the jwt token is expired,you could use the following code:`User.FindFirstValue("exp")`. – Rena Jun 10 '20 at 06:14

1 Answers1

0

The authentication flow handles this for you by default. It happens even before you hit your authorization layers.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • I don't know but that's not happening right now, its still authenticate if token is expired. Is there anything wrong, I am doing in the code? @Danial A. White – Aamir Jun 09 '20 at 19:02
  • Note that if the token is expired, your authorization handler is still called, but ```context.User``` will not have any claims, can you confirm that you indeed see claims? Also, do you see the 'exp' claim type? If yes, what is the value? – Michael Shterenberg Jun 10 '20 at 05:44
  • By default it expires tokken in 5 mins, I had to add this in code ClockSkew = TimeSpan.Zero – Aamir Jun 10 '20 at 09:58