首页 > 解决方案 > 如何在 asp.net core 中设置 jwt 令牌的生命周期

问题描述

我在 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 登录页面成功。

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

注意:- 对 Web 和移动设备使用相同的项目。

标签: asp.net-coreauthenticationasp.net-web-apijwtauthorization

解决方案


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

 expires: DateTime.Now.AddSeconds(20)

推荐阅读