jwt令牌到期时间(asp.net核心)

问题描述 投票:0回答:2

我想增加JWT令牌的生命周期,但我不能。

我试着用谷歌搜索这个问题,并找到了对JwtBearerOptions.TokenValidationParameters.ClockSkew的引用。

我也试过提供1分20秒的时间跨度,但应用程序没有考虑这些变化。

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()
     };
  });

这是Authenticate行动:

[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 };
}

我错过了什么吗?

angular authentication asp.net-core jwt
2个回答
1
投票

expiration值中的expiration值未定义。

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
};

0
投票

Bayram的答案中有一个错字,所以我想我应该发布我的。

Expiration中不存在SecurityTokenDescriptor属性。这是DateTime? Expires

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

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

完美的工作!

© www.soinside.com 2019 - 2024. All rights reserved.