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: falseoption invar 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
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}
What is the correct way to go around this issue? Do I trigger a logout from the api/auth/callback?
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
Sounds good, thanks for looking into it @adamjmcgrath !
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();
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.
Hi @matthieuh,
As mentioned https://github.com/auth0/nextjs-auth0/issues/362#issuecomment-821202378 - we're not going to support logging out of auth0.com if you're not logged in to your application.
In some scenarios calling directly auth0 to logout is not working and redirecting me back to my app being authenticated.
This sounds like a different issue - If you raise a bug with a small reproducable example, I'd be happy to debug it for you
@iddan
res.redirect(
`${AUTH0_ISSUER_BASE_URL}/v2/logout?${new URLSearchParams({
client_id: AUTH0_CLIENT_ID as string,
returnTo: BASE_URL,
})}`
)
I get CORS error.
~So far, what I've found the best is, catching the error in frontend and run window.location.reload(). Then nextjs/auth0 will trigger /auth/me themself and that will redirect user to the relogin. And plus you don't lose the current location.~
response with 401 on api routes -> catch it on frontend -> run window.location.href = "/api/auth/logout";
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?
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.
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.
I had a similar issue like @tr3ysmith and using a native browser <a> solved the problem.
+1 for using native <a> tag instead of next/link component. Solved my issue.
what about programmatically logging out? Right now i am doing router.push('/api/auth/logout') and it works, but i see this error in the console:
Access to fetch at 'https://mytenant.us.auth0.com/v2/logout?client_id=[REDACTED]&returnTo=http%3A%2F%2Flocalhost%3A3000' (redirected from 'http://localhost:3000/api/auth/logout?_rsc=w8pat') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Hello, I keep encountering this problem in Next.js v14.x. Logout works, but it doesn't clear the session or access token and automatically logs in. How can I logout completely clearing the session and token?
I'm facing the same issue as @RafalKostecki is describing. Would love some help!
We're in a circle when using logout. Im now using /api/auth/login?prompt=login to force a login. But I'm unable to properly logout my users.
Hey @noudadrichem can you please provide complete solution i'm facing same issue
I've seemed to run into this issue and, if I'm following it correctly, if some error occurs upon login (in my case, the user was not part of an organization, which is a requirement), there is no built-in way to get the user back to a proper logged out state?
So, there is no reason to ever rely on the built-in logout functionality and the only choice when using this package is to override the handler with something similar to https://github.com/auth0/nextjs-auth0/issues/362#issuecomment-860711901.
This seems half-baked if the provided package doesn't perform basic duties.
I'm also seeing this issue. We're forcing a user to be email verified but if a user logs in without verifying their email, I'm unable to force a log out by going to /api/auth/logout, it just logs back in automatically. The only way I'm able to clear the state is manually verify the email in the management console....