Konrad Viltersten
Konrad Viltersten

Reputation: 39250

Can't restrict the lifetime of a JWT token in .NET Core

My colleague produced a token using the code below.

byte[] secret = Encoding.UTF8.GetBytes("hakunana_matata_kurva_garbata");
SecurityKey key = new SymmetricSecurityKey(secret);
SigningCredentials credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
JwtSecurityToken jwt = new JwtSecurityToken(
  "https://localhost:44385",
  "https://localhost:44385",
  new Claim[] { },
  DateTime.Now,
  DateTime.Now.AddMinutes(1),
  credentials);
string token = new JwtSecurityTokenHandler().WriteToken(jwt);

The way I expected it to perform was to be allow access for 6o seconds and then stop working. This doesn't seem to happen and the secured method keeps getting invoked regardless (it doesn't for wrong tokens and for requests without a token). After a while (not sure how long) the token stops working (and I guess it's expired then).

I also checked the token in the JWT page. What stroke me as odd was the two lines for not before and expiry. It seems that the difference between them is 60 seconds, as expected.

{
  "nbf": 1563895482,
  "exp": 1563895542,
  "iss": "https://localhost:44385",
  "aud": "https://localhost:44385"
}

I made sure that the configuration for the security demands validation of expiry date.

TokenValidationParameters parameters = new TokenValidationParameters
{
  ValidateIssuerSigningKey = true,
  ValidateLifetime = true,
  ValidateAudience = false,
  ValidateIssuer = false,
  IssuerSigningKey = new SymmetricSecurityKey(hakuna_whatever)
};

What am I missing here?

Upvotes: 1

Views: 1140

Answers (1)

i regular
i regular

Reputation: 583

The problem is ClockSkew which default to 5 minutes (see for instance this post). Set it to TimeSpan.Zero when specifying the TokenValidationParameters

TokenValidationParameters parameters = new TokenValidationParameters
{
    // [...]
    ClockSkew = TimeSpan.Zero
};

Upvotes: 3

Related Questions