jwt令牌到期时间(asp.net核心) [英] jwt token expiration time (asp.net core)

查看:1182
本文介绍了jwt令牌到期时间(asp.net核心)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想延长JWT令牌的有效期,但不能.

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

我尝试谷歌搜索此事,并找到了对JwtBearerOptions.TokenValidationParameters.ClockSkew的引用.

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

我还尝试提供1分钟20秒的时间跨度,但应用程序未考虑更改.

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

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

我错过了什么吗?

推荐答案

Bayram的答案有错别字,所以我认为我应该发布我的答案.

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

属性ExpirationSecurityTokenDescriptor中不存在. DateTime? Expires.

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

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

完美工作!

这篇关于jwt令牌到期时间(asp.net核心)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆