auth0 / nextjs-auth0

Next.js SDK for signing in with Auth0

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

withMiddlewareAuthRequired does not check token expiration

mogzol opened this issue · comments

Checklist

Description

I am using withMiddlewareAuthRequired in my next.js 14 app (using app router). I have noticed that users with expired tokens in their session can still access the app as if they are logged in. Looking at the code, it seems that withMiddlewareAuthRequired only checks that the session exists and can be read, and does not check if the token is expired or not.

I'm not sure if this is intentional behaviour, but I definitely did not expect it to behave this way. I expected withMiddlewareAuthRequired to redirect users with expired tokens to the login.

Reproduction

  1. Set up an app with the withMiddlewareAuthRequired middleware.
  2. Log in
  3. Wait for the token to expire (but not long enough for the session cookie to expire)
  4. Try using the app, observe that you can, and withMiddlewareAuthRequired does not redirect you to login
  5. Additionally, calling getSession still works and returns the session with the expired token

Additional context

I found that I can work around this by either using an absolute session with a duration <= the token expiry time (so the cookie expires before the token), or by calling getAccessToken in the middleware, which will throw an error if the token is expired, which I can then catch and redirect the user to the login.

nextjs-auth0 version

3.5.0

Next.js version

14.0.4

Node.js version

20.10.0

+1, we are encountering the same issue. Thanks for opening @mogzol.

Based on my understanding, withPageAuthRequired also faces a similar issue. It safeguards pages and redirects users lacking a session to the login page. However, it permits users with expired tokens to access the protected pages.

Hi @mogzol - this is by design - the duration of the session is not tied to the ID Token, or Access Token's expiration

See #538 (comment) and #833 (comment) for more info

@mogzol Any idea how to proceed? The comments @adamjmcgrath linked to don't really provide any direction.

@mrhaddad, in my middleware, I call the getAccessToken() function, which throws an error if the access token is invalid

try {
  // The nextjs-auth0 library does not check token expiry in withMiddlewareAuthRequired, so do it
  // here by calling getAccessToken, which will throw an error if the token is expired.
  await auth0.getAccessToken();
} catch (e) {
  if (e instanceof AccessTokenError && e.code === "ERR_EXPIRED_ACCESS_TOKEN") {
    // Token is expired, do whatever here
  }
  throw e;
}