Search code examples
authenticationnext.jsamazon-cognitonext-auth

how to completely destroy client side session with NextAuth.js & AWS Cognito


i am using Next.js with NextAuth.js with a amazon cognito setup and my issue is that when i click on signin link right after logging out, my user gets signed in directly without getting asked for credentials.

my [...nextauth].ts looks like this:

import NextAuth from 'next-auth';
import CognitoProvider from 'next-auth/providers/cognito';

export const authOptions = {
  providers: [
    CognitoProvider({
      clientId: process.env.COGNITO_CLIENT_ID || '',
      clientSecret: process.env.COGNITO_CLIENT_SECRET || '',
      issuer: process.env.COGNITO_ISSUER_URL,
    }),
  ],
  debug: process.env.NODE_ENV !== 'production' ? true : false,
};

export default NextAuth(authOptions);

For authentication i use the Next helper methods signIn and signOut:

interface HomeProps {
  appTitle: string;
}

const Home: NextPage<HomeProps> = ({ appTitle }) => {
  const { data: session, status } = useSession();

  if (status === 'authenticated') {
    return (
      <>
        <Head>
          <title>{appTitle}</title>
        </Head>
        <p>Signed in as {session.user?.email}</p>
        <Link href="/">
          <a
            onClick={() => {
              signOut();
            }}
          >
            Log out
          </a>
        </Link>
      </>
    );
  }

  return (
    <>
      <Head>
        <title>{appTitle}</title>
      </Head>
      <Link href="/">
        <a
          onClick={(event) => {
            event.preventDefault();
            signIn('cognito', {
              callbackUrl: 'http://localhost:3000',
            });
          }}
        >
          Sign In
        </a>
      </Link>
    </>
  );
};

export default Home;

I assume that the client keeps some information about the previous signed in user after logout but i don't know which data and where it is located.

I would like to completely delete all information after logout so that when clicking on signin the user always gets asked for credentials. Any help would be appreciated.


Solution

  • I have been facing this same issue and tracked back why thats happening. When the helper signIn method is invoked it redirects us to the hosted UI provided by cognito which is a different domain website from your own app. And that particular domain has its own local storage and session information. Cognito utilise that session credentials and logs you in without prompting for new username and password.

    For now, I couldn't find a proper solution for my use case as for security, you're not allowed to edit (or delete) a cookie on another site. So I am just providing these information for tracking back the how the client side storing that data.

    One solution is invoking the logout endpoint provided here. On logout you can make a callback for that url which will clear the credential from that cognito domain each time you signout