auth0 / nextjs-auth0

Next.js SDK for signing in with Auth0
MIT License
2.08k stars 392 forks source link

Can't sign out, automatically signs in immediately #1744

Open cutesweetpudding opened 6 months ago

cutesweetpudding commented 6 months ago

Checklist

Description

Everything works fine in local, I implement same way as example app. Just login/logout, however after deploy to azure static web, it fails to signout, always immediately signs back, which extremely annoying. I have tried all solutions online, and wasted 2 days on this issue, still can't figure it out. Attach a screenshot, logout v2 url is called, but session / cookie not cleaned, I even tried to manually clean it, but it adds back immedately.

Screenshot 2024-05-08 at 10 59 45 PM

Reproduction

Just deploy azure static website, I think this is common issue.

Additional context

n/a

nextjs-auth0 version

3.5.0

Next.js version

8.1.0

Node.js version

v20.8.0

JeroenMinnaert commented 6 months ago

Same issue over here, not sure what's going on. Tried changing to links as instructed here, but that didn't help. I'm running this on an AWS stack and Cloudfront.

Might be related to https://github.com/auth0/nextjs-auth0/issues/42?

zlatkopetrov commented 6 months ago

Same issue here. Using Azure static website.

JeroenMinnaert commented 6 months ago

From my part, it looks like this is related to the cache policy in my Cloudfront.

I've deployed using SST and the NextJs construct.

JeroenMinnaert commented 6 months ago

I found a fix for this issue in my stack. Since Auth0 uses Cookies for authentication, I had to explicitly set cookieBehavior: CacheCookieBehavior.all() (default it is set to none). Spent a long time looking for this solution, I hope this helps someone else.

Below is the full code:

  const nextJsSite = new NextjsSite(stack, "next-js-site", {
    path: "packages/web",
    cdk: {
      // By default, the cache policy is configured to cache all responses from
      // the server rendering Lambda based on the query-key only. If you're using
      // cookie or header based authentication, you need to override the
      // cache policy to cache based on those values as well.
      serverCachePolicy: new CachePolicy(stack, "ServerCache", {
        queryStringBehavior: CacheQueryStringBehavior.all(),
       // The headers below are set by the SST construct so adding this as well
        headerBehavior: CacheHeaderBehavior.allowList(
          "accept",
          "rsc",
          "next-router-prefetch",
          "next-router-state-tree",
          "next-url",
          "x-prerender-bypass",
          "x-prerender-revalidate",
        ),
        // The line below solved my problem
        cookieBehavior: CacheCookieBehavior.all(),
        defaultTtl: Duration.days(0),
        maxTtl: Duration.days(365),
        minTtl: Duration.days(0),
      }),
    },
  });
zlatkopetrov commented 6 months ago

Has anyone found a solution for this issue? The cookie is not removed after successful logout, so the users are still logged in.

altrim commented 6 months ago

I’m facing the same issue while deploying Next.js to Azure Static Web Apps. Logout works fine locally, but it doesn’t seem to work when deployed. Even though all requests in the network tab appear to be fine, it keeps signing in automatically.

kaayru commented 6 months ago

Same problem here.

larspietrowski commented 6 months ago

I have the same problem. Locally works fine, but on azure static web apps the user ist still logged in.

ktei commented 5 months ago

same issue here. can't believe this is still not fixed...

UPDATE: not nextjs-auth0's issue. It's like someone else mentioned, CloudFront is caching the cookie.

treckstar commented 4 months ago

So it looks like there are two things that could be happening:

  1. Make sure you are not using next/link component for Login / Logout links.

    <Link href="/api/auth/logout">Logout</Link>

    Being that next/link is for client side linking, it doesn't actually do a full page request to the href value.

    Changing it to a regular <a /> element should make Login / Logout work as expected as far as I know.

    <a href="/api/auth/logout">Logout</a>

    For app router, check example-app nav.tsx component for reference.

  2. If CloudFront is caching the cookie, try updating the cache policy using the cookieBehavior line of code from @JeroenMinnaert answer .

    cookieBehavior: CacheCookieBehavior.all()
withintheruins14 commented 4 months ago

@treckstar I've been going in circles with this library for at least a month - the next/link you mentioned fixed everything for me

micael-mbagira-parloa commented 2 months ago

I'm also affected by this issue with Azure Static Webapp (works well locally though). Was anyone able to fix it? I am not using the next/link and I am not using Cloudfront.

iDVB commented 2 months ago

I found a fix for this issue in my stack. Since Auth0 uses Cookies for authentication, I had to explicitly set cookieBehavior: CacheCookieBehavior.all() (default it is set to none). Spent a long time looking for this solution, I hope this helps someone else.

Below is the full code:

  const nextJsSite = new NextjsSite(stack, "next-js-site", {
    path: "packages/web",
    cdk: {
      // By default, the cache policy is configured to cache all responses from
      // the server rendering Lambda based on the query-key only. If you're using
      // cookie or header based authentication, you need to override the
      // cache policy to cache based on those values as well.
      serverCachePolicy: new CachePolicy(stack, "ServerCache", {
        queryStringBehavior: CacheQueryStringBehavior.all(),
       // The headers below are set by the SST construct so adding this as well
        headerBehavior: CacheHeaderBehavior.allowList(
          "accept",
          "rsc",
          "next-router-prefetch",
          "next-router-state-tree",
          "next-url",
          "x-prerender-bypass",
          "x-prerender-revalidate",
        ),
        // The line below solved my problem
        cookieBehavior: CacheCookieBehavior.all(),
        defaultTtl: Duration.days(0),
        maxTtl: Duration.days(365),
        minTtl: Duration.days(0),
      }),
    },
  });

This will most likely prevent any caching at all since there are many cookies for things like GA, or social libs etc that will add many cookies and some that change with each visit. You can also target only the ones you really care about which in our case is Auth0 and HubSpot session cookies...

cf.CacheCookieBehavior.allowList('appSession', 'hubspotutk'), // Added Auth0 and HubSpot sessions,
kinhdev24 commented 1 month ago

I have tried all the ways with this but they all don't seem to work. After a long period of research, I have found a way to fix this. I tried handling the oidc logout before logout on the client and this worked well for me. Although the logout time is a bit longer, I don't have the problem of automatically signing in when logging out.

I researched and tried following this doc

//pages/api/logout-oidc.ts

import { getSession, handleLogout } from '@auth0/nextjs-auth0'
import { NextApiRequest, NextApiResponse } from 'next'

const handler = async (req: NextApiRequest, res: NextApiResponse) => {
  if (req.method === 'GET') {
    const session = await getSession(req, res)
    console.log({ session })

    const logoutUrl = `${process.env.AUTH0_ISSUER_BASE_URL}/oidc/logout?clientId=${process.env.AUTH0_CLIENT_ID}&logout_hint=${session?.user.sid}`

    await fetch(logoutUrl, {
      method: 'GET'
    })

    return res.status(200).json({ message: 'Logged out successfully' })
  }
}

export default handler

Hope you can fix it this way. If you need more information please let me know

Fakher-Zaman commented 1 month ago

Problem Solved:

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

export const GET = handleAuth({
    login: handleLogin({
        returnTo: "/dashboard",
    }),
    logout: handleLogout({
        returnTo: "/",
    }),
});

The code provided handles authentication using @auth0/nextjs-auth0 for a Next.js project. The GET handler integrates both login and logout functionalities:

handleAuth is used to manage authentication flows. handleLogin redirects users to the /dashboard page after successful login. handleLogout ensures users are redirected to the homepage (/) after logging out.

This setup can resolve the issue where users are signed back in immediately after logging out, by correctly managing the redirection and logout flow through Auth0.