【问题标题】:ASP.NET Core and JWT token lifetimeASP.NET Core 和 JWT 令牌生命周期
【发布时间】:2018-12-23 01:11:43
【问题描述】:

我使用ASP.NET Core 2.1.1

有趣的是,只有在 both ClockSkew - 在 Startup.cs and 中才考虑过期时间JwtSecurityTokenHandler.TokenLifetimeInMinutes - 在控制器中

例如:

services
  .AddJwtBearer(x =>
  {
      ...
      x.TokenValidationParameters = new TokenValidationParameters()
      {
         ClockSkew = TimeSpan.FromMinutes(90),
         ...

...
public async Task<AuthenticateOutput> Authenticate([FromBody] AuthenticateInput input)
{
   var tokenHandler = new JwtSecurityTokenHandler();
   tokenHandler.TokenLifetimeInMinutes = (int)TimeSpan.FromMinutes(90).TotalMinutes;
   ...

如果我删除 tokenHandler.TokenLifetimeInMinutes = (int)TimeSpan.FromMinutes(90).TotalMinutes; 部分 - 使用默认过期时间。

在我看来tokenHandler.TokenLifetimeInMinutes仍然是多余的,我只是误解了如何正确设置过期时间的概念。

我也尝试添加过期声明 - new Claim(ClaimTypes.Expiration, ...) - 但效果不大。

【问题讨论】:

标签: c# authentication asp.net-core jwt token


【解决方案1】:

ClockSkew 属性与过期本身无关,它补偿了clock skew

要设置令牌过期,您必须在创建令牌时指定它:

new JwtSecurityToken(
                ...
                expires: DateTime.UtcNow.AddMinutes(90),
                ....);

以下代码将为您提供带有令牌的字符串:

var token = new JwtSecurityToken() { /* setup your token setting here*/ }
var tokenString = new JwtSecurityTokenHandler().WriteToken(token);

【讨论】:

  • 谢谢亚历克斯,玩得很好!测试了几次尝试不同的时间间隔 - 工作。
  • 如何避免过期?我已经尝试删除过期属性,但它仍然会在 1 小时左右过期
  • ((JwtSecurityTokenHandler)tokenHandler).SetDefaultTimesOnTokenCreation = false; 让它永不过期。
【解决方案2】:
//reading the key from config
//reading the issuer from config
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:Key"]));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(configuration["Jwt:Issuer"], configuration["Jwt:Issuer"], 
                            null, expires: DateTime.Now.AddMinutes(60),
                            signingCredentials: credentials); //60mins expiration 

            string newToken = new JwtSecurityTokenHandler().WriteToken(token);

【讨论】:

    猜你喜欢
    • 2021-06-04
    • 2020-11-06
    • 2019-12-01
    • 2019-06-17
    • 2017-10-13
    • 2019-06-26
    • 2020-08-22
    • 2015-01-08
    • 2017-07-25
    相关资源
    最近更新 更多