【问题标题】:how to set lifetime of jwt token in asp.net core如何在 asp.net core 中设置 jwt 令牌的生命周期
【发布时间】:2021-06-04 04:14:55
【问题描述】:

我已经在asp.net core 3.1中创建了项目,并且可以成功授权。

问题是我想增加 JWT 令牌的生命周期,我尝试了所有可能的方法,但仍然无法获得适当的帮助或回答我正在寻找的内容。

下面是startup.cs

中的代码
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
   {
    options.TokenValidationParameters = new TokenValidationParameters
    {
        RequireExpirationTime = true,
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        //ClockSkew = TimeSpan.Zero,
        ValidIssuer = _configuration.GetSection("BaseUrl").Value,
        ValidAudience = _configuration.GetSection("BaseUrl").Value,
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetSection("IssuerSigningKey").Value)),
    };

    options.Events = new JwtBearerEvents
    {
         OnAuthenticationFailed = context =>
         {
             context.Response.OnStarting(() =>
             {
                  context.Response.StatusCode = 499;
                  return Task.CompletedTask;
             });

             if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
             {
                  context.Response.Headers.Add("Token-Expired", "true");
             }
         return Task.CompletedTask;
    }
  };
});

以下是生成 JWT 令牌的代码,

string GeneratJwtToken()
{
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration.GetSection("IssuerSigningKey").Value));
            var signinCredentials = new SigningCredentials(secretKey, SecurityAlgorithms.HmacSha256);

            var claims = new[] { new Claim("Source", "PmpMobileApp") };

            var tokeOptions = new JwtSecurityToken(
                issuer: _configuration.GetSection("BaseUrl").Value,
                audience: _configuration.GetSection("BaseUrl").Value,
                claims,
                expires: DateTime.Now.AddSeconds(20),
                signingCredentials: signinCredentials
            );
            return new JwtSecurityTokenHandler().WriteToken(tokeOptions);
}

我见过刷新令牌的概念,但是对于刷新令牌,它应该从中间件返回 401 未经授权的错误,然后我可以调用刷新令牌 api。但在此它会返回 200 登录页面成功。

另外注意到,令牌在本地开发环境中不会过期,但在生产环境中会在几分钟内过期。

注意:- 在网络和移动设备上使用相同的项目。

【问题讨论】:

  • 由于令牌内容是可读的,因为它只是 base64url 编码,您应该使用例如调试令牌jwt.io,并检查 exp 属性的值。如果将鼠标悬停在它上面,它会显示人类可读的日期时间。 ValidateLifetime 选项基本上只是检查这个给定的日期时间是否已经过去;因此,如果 exp 日期时间包含预期值,则令牌不应在几分钟后被视为过期(问题可能是其他问题)。

标签: asp.net-core authentication asp.net-web-api jwt authorization


【解决方案1】:

您已在 GeneratJwtToken() 方法中将其设置为 20 秒后过期:

 expires: DateTime.Now.AddSeconds(20)

【讨论】:

  • 我用同样的方法做了,但它不起作用。
  • 同理是什么意思?我写的就是你发的。您将其设置为 20 秒后过期。你说你想增加寿命。例如,如果您希望它持续 1 天,则必须编写 DateTime.Now.AddDays(1)。
  • 如果我将它更改为 DateTime.Now.AddYears(1),那么它也会在几分钟后过期。
【解决方案2】:

使用 cookieOption 中的 Expires 属性。

var cookieOptions = new CookieOptions
            {
                HttpOnly = true,
                Expires = DateTime.UtcNow.AddDays(7) 
            };

完美运行!

【讨论】:

    猜你喜欢
    • 2018-12-23
    • 2020-11-06
    • 2019-12-01
    • 1970-01-01
    • 2017-10-17
    • 2019-10-31
    • 2017-10-13
    • 2019-06-17
    • 1970-01-01
    相关资源
    最近更新 更多