jwt token expiration time (asp.net core)

2019-03-03 20:42发布

问题:

I'd like to increase the lifetime of JWT token but I can't.

I tried googling the matter and found references to JwtBearerOptions.TokenValidationParameters.ClockSkew.

I also tried providing 1 minute and 20 seconds timespans, but the changes aren't taken into account by the app.

Startup.cs:

services
  .AddAuthentication(options =>
  {
     options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
     options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
  })
  .AddJwtBearer(x =>
  {
     x.RequireHttpsMetadata = false;
     x.SaveToken = true;
     x.TokenValidationParameters = new TokenValidationParameters()
     {
        ClockSkew = TimeSpan.FromSeconds(20),
        RequireExpirationTime = true,
        RequireSignedTokens = true,

        ValidateIssuerSigningKey = true,
        ValidateLifetime = true,
        IssuerSigningKey = Configuration.GetSymmetricSecurityKey(),
        ValidAudience = Configuration.GetValidAudience(),
        ValidIssuer = Configuration.GetValidIssuer()
     };
  });

Here's the Authenticate action:

[AllowAnonymous]
[HttpPost]
public async Task<AuthenticateOutput> Authenticate([FromBody] AuthenticateInput input)
{
   string subdomain = Request.GetSubDomain();
   var user = await _userService.Authenticate(input.UserName, input.Password, subdomain);

   if (user == null)
   {
      throw new Exception("Unauthorised");
   }

   var tokenHandler = new JwtSecurityTokenHandler();

   var tokenDescriptor = new SecurityTokenDescriptor
   {
      Issuer = _config.GetValidIssuer(),
      Audience = _config.GetValidAudience(),
      SigningCredentials = new SigningCredentials(_config.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256),
      Subject = new ClaimsIdentity(new[]
      {
          new Claim(ClaimTypes.Name, user.UserName),
          new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
      })
   };

   var token = tokenHandler.CreateToken(tokenDescriptor);
   string tokenString = tokenHandler.WriteToken(token);

   return new AuthenticateOutput() { UserId = user.Id, Token = tokenString };
}

Have I missed anything?

回答1:

expiration value undefined in token descriptor.

var tokenDescriptor = new SecurityTokenDescriptor
{
   Issuer = _config.GetValidIssuer(),
   Audience = _config.GetValidAudience(),
   SigningCredentials = new SigningCredentials(_config.GetSymmetricSecurityKey(), SecurityAlgorithms.HmacSha256),
   Subject = new ClaimsIdentity(new[]
   {
      new Claim(ClaimTypes.Name, user.UserName),
      new Claim(ClaimTypes.NameIdentifier, user.Id.ToString())
   }),

   // expiration time here...
   Expiration = _config.GetExpiration() // etc
};


回答2:

There' a typo in Bayram's answer, so I think I should post mine.

The property Expiration doesn't exist in SecurityTokenDescriptor. It's DateTime? Expires.

DateTime expires = input.RememberMe ? DateTime.UtcNow.AddDays(5) : DateTime.UtcNow.AddMinutes(20);

var tokenDescriptor = new SecurityTokenDescriptor
{
    Expires = expires,
    ...

Works perfectly!