【问题标题】:Asp.Net Core & JWT authentication: How to know authentication failed because token expired?Asp.Net Core & JWT 身份验证:如何知道身份验证失败,因为令牌过期?
【发布时间】:2019-04-16 20:13:31
【问题描述】:

下面是我使用的 JWT 认证:

.AddJwtBearer(options =>
{
    // options.SaveToken = false;
    // options.RequireHttpsMetadata = false;

    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(AuthConfig.GetSecretKey(Configuration)),

        ValidateIssuer = false,
        ValidateAudience = false,

        ValidateLifetime = true,
        ClockSkew = TimeSpan.Zero,
    };

    options.Events = new JwtBearerEvents()
    {
        OnChallenge = c =>
        {
            c.HandleResponse();

            // TODO: How to know if the token was expired?

            return AspNetUtils.WriteJsonAsync(c.Response, new Result<string> 
            { 
                Message = "Unauthenticated.", 
                IsError = true 
            }, 401);
        },
    };
});

身份验证工作正常。对于新的需求,我需要知道身份验证是否因为 JWT 令牌过期而失败。

请注意,由于多种原因,身份验证失败。令牌可能丢失、被篡改或过期。

有什么想法吗?谢谢!

【问题讨论】:

    标签: asp.net-core jwt asp.net-core-2.1 jwt-auth


    【解决方案1】:
    .AddJwtBearer(options =>
    {
        options.Events = new JwtBearerEvents()
        {
            OnAuthenticationFailed = context =>
            {
                if(context.Exception is SecurityTokenExpiredException)
                {
                    // if you end up here, you know that the token is expired
                }
            }
        };
    })
    

    【讨论】:

      【解决方案2】:

      使用OnChallenge 属性:

      .AddJwtBearer(options =>
      {
          options.Events = new JwtBearerEvents
          {
              OnChallenge = context =>
              {
                  if (context?.AuthenticateFailure is SecurityTokenExpiredException)
                  {
                      var error = context.Error; // "invalid_token"
                      var errorDescription = context.ErrorDescription; // "The token is expired"
                  }
      
                  return Task.CompletedTask;
              }
          };
      });
      

      【讨论】:

        猜你喜欢
        • 2021-12-17
        • 2016-09-27
        • 2019-02-22
        • 2019-09-06
        • 2021-04-20
        • 2018-07-23
        • 2016-07-21
        • 2019-03-10
        • 1970-01-01
        相关资源
        最近更新 更多