Using DotNet Core 2.2, I'm using JWT auth in my app, while storing the token in cookies. All is fine apart from when the token expires.

I have the following options for my authentication in 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;
                });

And here is my SimpleTokenProvider.cs file:

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");
            }

My problem is the line handler.ValidateToken(protectedText, this.validationParameters, out validToken) keeps throwing a timeout exception:

Microsoft.IdentityModel.Tokens.SecurityTokenExpiredException: 'IDX10223: Lifetime validation failed. The token is expired. ValidTo: '[PII is hidden]', Current time: '[PII is hidden]'.'

What I'd like to do in this instance is automatically generate a new token, or delete the current auth cookie.

How can I do this/what is the best way to go?

0 Answers