0

I'm working on .net core api 2.1, I have implemented JWT token authentication, I want jwt token to expire after given time, but it is not expiring. Token still validation even after expiry time.

Startup.cs code:

// configure jwt authentication
var jwtSettings = jwtSettingsSection.Get<JWTSettings>();
var key = Encoding.ASCII.GetBytes(jwtSettings.SECRET);
services.AddAuthentication(x =>
{
    x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(x =>
{
    x.RequireHttpsMetadata = false;
    x.SaveToken = true;
    x.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuer = false,
        ValidateAudience = false,
        ValidateLifetime = false,
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(key),
        ClockSkew = TimeSpan.Zero
    };
});

services.Configure<IISOptions>(options =>
{
    options.AutomaticAuthentication = true;
    //options.ForwardClientCertificate = true;
});

SignIn api code to create token on sign in:

var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_jwtSettings.SECRET);
var currentTime = DateTime.Now;

var tokenDescriptor = new SecurityTokenDescriptor
{
     Expires = DateTime.Now.AddMinutes(2),
     SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(tokenDescriptor);
var tokenString = tokenHandler.WriteToken(token);
rs.Token = tokenString;

Auth filter to validate token:

public void OnAuthorization(AuthorizationFilterContext filterContext)
{
    if (!ValidateToken(filterContext.HttpContext.Request.Headers["TOKEN"]))
    {
    filterContext.Result = new UnauthorizedResult();
    }
}

private bool ValidateToken(string authToken)
{
    try
    {
    var tokenHandler = new JwtSecurityTokenHandler();
    var validationParameters = GetValidationParameters();

    SecurityToken validatedToken;
    IPrincipal principal = tokenHandler.ValidateToken(authToken, validationParameters, out validatedToken);
    return true;
    }
    catch(Exception ex)
    {
    return false;
    }
}

private TokenValidationParameters GetValidationParameters()
{
    return new TokenValidationParameters()
    {
    ValidateLifetime = false, // Because there is expiration in the generated token
    ValidateAudience = false, // Because there is no audiance in the generated token
    ValidateIssuer = false,   // Because there is no issuer in the generated token
    //ValidIssuer = _appSettings.ValidIssuer,
    //ValidAudience = _appSettings.ValidAudience,
    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretkey)) // The same key as the one that generate the token
    };
}

What can be the issue?

Shreyas Pednekar
  • 157
  • 1
  • 11
  • 1
    Why do you set `ValidateLifetime = false`? Isn't this just the opposite of the behaviour you want? Also read the answer here: https://stackoverflow.com/questions/44252043/netcore-jwtbearerauthentication-not-rejecting-expired-tokens – jps Jun 04 '19 at 05:56
  • 1
    @jps Token is not expiring even after setting `ValidateLifetime = true` – Shreyas Pednekar Jun 04 '19 at 05:59
  • did you read the linked answer? Also, pls show your token. Is the `exp`set correctly? – jps Jun 04 '19 at 07:03
  • Yes, I have already read it. I have posted my code, you can check I have set `Expires = DateTime.Now.AddMinutes(2)` – Shreyas Pednekar Jun 04 '19 at 09:47
  • So `ClockSkew = TimeSpan.Zero`, as shown in the other answer doesn't help?! I saw your code, but I want to see the token, or at least the actual value of exp. – jps Jun 04 '19 at 10:00
  • See this is one of my token `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYmYiOjE1NTk2NTA2NTYsImV4cCI6MTU1OTY1MDY2MSwiaWF0IjoxNTU5NjUwNjU2fQ.x3_r82FxynQ10rwHJEuQ33J8PEWx4i2EWGO_1sacPAg` – Shreyas Pednekar Jun 04 '19 at 12:41
  • 1
    `ClockSkew = TimeSpan.Zero` is not helping me, you can check my code of token creation and `exp` which I have set – Shreyas Pednekar Jun 04 '19 at 12:42
  • 1
    your token is only valid for 5 seconds! (difference between exp and nbf (not before) claims). You can paste the token to the jwt.io debugger and see the values on the right side. There you can also see if the time is what you expect. That's still no answer, but another thing that is probably not right in your code. – jps Jun 04 '19 at 12:58
  • If my token is valid for only 5 seconds then why it is not expiring? what can be the issue? – Shreyas Pednekar Jun 05 '19 at 04:30
  • 1
    I notice that you have created two `TokenValidationParameters` in your code. The first is used to generate token , and the second is used to validate token. However, **the two token parameters are different from each other**. I could reproduce the same issue if I keep the second `TokenValidationParameters` the same as yours. But if I add **ClockSkew = TimeSpan.Zero for both two token parameters**, it expires. – itminus Jun 05 '19 at 06:46
  • 1
    Thanks, It resolved my issue – Shreyas Pednekar Jun 05 '19 at 06:49

0 Answers0