nextjs-auth0: Logout handler does not call the auth0 logout endpoint if the user is unauthorized

Description

When a user enters a valid username/password through on the universal login sign-in page, but when an auth0 rule returns an UnauthorizedError (like when forcing email verification), the user is stuck in an unauthorized state, and redirecting them to /api/auth/logout or /api/auth/login doesn’t let them sign out and try again. The most likely reason is because sessionCache.isAuthenticated fails in the logout handler, so the logout handler never executes client.endSessionUrl, keeping the SSO cookie of that user on the auth0 domain.

Reproduction

App configuration:

  • Create a new auth0 app of type “Regular web application” and using the “Classic” universal login
  • Go to login page customization, turn on “Customize login page”, add the loginAfterSignUp: false option in var lock = new Auth0Lock(..., and save it
  • Create a new auth0 rule
  • Select the “Force email verification” rule, save it as is, and make sure the rule is activated
  • On the nextJS app, use all the default handlers in /api/auth/[...auth0].js

User actions:

  • Go to /api/auth/login
  • Sign up a new user with a valid email/password
  • You should see a message about a verification email being sent, do not verify the email address after signing up
  • Go to /api/auth/login, log in with the previously entered username and password
  • You should see a page with an error message saying “unauthorized (Please verify your email before logging in.)”
  • Go to /api/auth/logout, then to /api/auth/login, you should see the same “unauthorized” error message instead of the universal login page

Environment

  • Version of this library used: 1.2.0
  • Version of the platform or framework used, if applicable: node v12.18.3, nextJS v10.0.6
  • Other relevant versions (language, server software, OS, browser): Auth0 Classic universal login with forced email verification

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 7
  • Comments: 19 (4 by maintainers)

Commits related to this issue

Most upvoted comments

In some scenarios calling directly auth0 to logout is not working and redirecting me back to my app being authenticated.

Honestly, I feel this case should be handle by the library. Call the logout method should work and clear auth0 cookies no matter the situation otherwise it will put more users of this lib in this situation and having bugs using it.

+1 for using native <a> tag instead of next/link component. Solved my issue.

It took me way too much time to figure out how to this. Here is the custom code I had to add to the callback handler:

res
        .redirect(
          `${AUTH0_ISSUER_BASE_URL}/v2/logout?${new URLSearchParams({
            client_id: AUTH0_CLIENT_ID as string,
            returnTo: BASE_URL,
          })}`
        )
        .end();

Hi @THEhEROLocker @Romainpaulus - I’ve chatted with my team and we think that if you want to log out of Auth0 when you’re already logged out of the application you should use the Auth0 api directly (see https://github.com/auth0/nextjs-auth0/issues/362#issuecomment-816595953)

@THEhEROLocker - yes, you should be able to handle the error from handleCallback and perform an Auth0 logout if necessary

I had a similar issue like @tr3ysmith and using a native browser <a> solved the problem.

Hi, in my case there’s a different behavior in staging tenant vs prod tenant.

This is my handleAuth

import { handleAuth } from "@auth0/nextjs-auth0";

export const GET = handleAuth({
  onError(req: Request, error: Error) {
    console.error(error);
  }
});

In staging tenant domain/api/auth/logout takes me to the auth0 login page (working as intended). but in prod tenant I get redirected to the app logged in.

Hi @Romainpaulus - thanks for raising this

This is expected behaviour - let me have a chat with my team about what changes, if any, we should make to this.

In the meantime, you can call the logout endpoint directly: https://{AUTH0_DOMAIN}/v2/logout?returnTo={LOGOUT_URL}&client_id={CLIENT_ID}

Ok so for anyone still experiencing this, this worked for me. I’m using NextJs with App Router:

import { useRouter } from 'next/navigation';

export default function LogoutButton() {

   const router = useRouter();

   return <button onClick={() => router.push("/api/auth/logout")}>Logout</button>

}

I was using href on both <Link /> from NextJs and <a> and it wasn’t working and just going around in a loop.

In the meantime, you can call the logout endpoint directly: https://{AUTH0_DOMAIN}/v2/logout?returnTo={LOGOUT_URL}&client_id={CLIENT_ID}

@adamjmcgrath I have a question which may be related to https://github.com/auth0/nextjs-auth0/issues/362#issuecomment-871193585

I have the following auth0 handleAuth in a Next project

// src/pages/api/auth/[...auth0].ts

export default auth0.handleAuth({
  async logout(request: NextApiRequest, response: NextApiResponse) {
    try {
      const user = auth0.getSession(request, response)?.user;
      const logoutUrl = `${auth0IssuerBaseURL}/v2/logout?returnTo=${baseURL}&client_id=${clientID}`;
      await auth0.handleLogout(request, response, {
        // explicitly set returnTo if user is unauthorized:
        returnTo: user == null ? logoutUrl : undefined,
      });
    } catch (error) {
      console.error(error);
      response.status(error.status ?? 500).end(error.message);
    }
  },
  ...
})

I am seeing the behaviour described by the comment

In some scenarios calling directly auth0 to logout is not working and redirecting me back to my app being authenticated.

From the auth0 docs I found a note:

the returnTo URL must be listed in the Allowed Logout URLs set at the application level

Does this mean both baseURL and auth0IssuerBaseURL need to be added to the whitelist?