具有Cookie的JWT身份验证-如何处理过期的令牌?

时间:2019-05-01 10:46:01

标签: cookies .net-core jwt jwt-auth

使用DotNet Core 2.2,我在应用程序中使用JWT auth,同时将令牌存储在cookie中。除了令牌过期时,其他一切都很好。

在Startup.cs中,我具有以下身份验证选项:

services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                })
                .AddCookie(options =>
                {
                    options.SlidingExpiration = true;
                    options.Cookie.Name = "access_token";
                    options.TicketDataFormat = new SimpleTokenProvider.CustomJwtDataFormat(
                        SecurityAlgorithms.HmacSha256,
                        tokenValidationParameters);
                    options.Cookie.SameSite = SameSiteMode.None;
                });

这是我的SimpleTokenProvider.cs文件:

public AuthenticationTicket Unprotect(string protectedText, string purpose)
            {
                var handler = new JwtSecurityTokenHandler();
                ClaimsPrincipal principal = null;
                SecurityToken validToken = null;

                try
                {
                    principal = handler.ValidateToken(protectedText, this.validationParameters, out validToken);

                    var validJwt = validToken as JwtSecurityToken;

                    if (validJwt == null)
                    {
                        throw new ArgumentException("Invalid JWT");
                    }

                    if (!validJwt.Header.Alg.Equals(algorithm, StringComparison.Ordinal))
                    {
                        throw new ArgumentException($"Algorithm must be '{algorithm}'");
                    }
                }
                catch (SecurityTokenValidationException e)
                {
                    return null;
                }
                catch (ArgumentException e)
                {
                    return null;
                }

                return new AuthenticationTicket(principal, new AuthenticationProperties(), "Cookie");
            }

我的问题是,handler.ValidateToken(protectedText, this.validationParameters, out validToken)行不断抛出超时异常:

  

Microsoft.IdentityModel.Tokens.SecurityTokenExpiredException:   'IDX10223:生命周期验证失败。令牌已过期。有效:   “ [[PII隐藏]]”,当前时间:“ [[PII隐藏]”。”

在这种情况下,我想自动生成一个新令牌或删除当前的身份验证cookie。

我该怎么做/最好的方法是什么?

0 个答案:

没有答案
相关问题