Search code examples
next.jsnext-auth

NextAuth login attempt failure always directs to fail error page


I'm using the example at https://next-auth.js.org/configuration/callbacks#sign-in-callback to redirect to a page if the login is failed.

The redirect to the "403" page is successful but when attempting to login in again, the user is brought directly to the "403" page without a new prompt for authentication.

User actions:

  1. Click on button
  2. Google Auth page
  3. User is not authorized to access so is directed to 403 page
  4. User clicks on button 2nd time
  5. Redirected to 403 page

I'd like to redirect back to the Google Auth page instead of directly to the 403. The only way I can get this to work is to clear the Next Auth cookies.

I've tried using the pages: field in the authOptions to specify the return of signIn() to a path and the return "/403" but both have the same result of redirecting straight to the 403.

export const authOptions: NextAuthOptions = {
  secret: process.env.NEXTAUTH_SECRET,
  providers: [
    GoogleProvider({
      profile(profile: GoogleProfile) {
        return {
          id: profile.sub,
          name: profile.name,
          firstname: profile.given_name,
          lastname: profile.family_name,
          email: profile.email,
          image: profile.picture,
        }
      },
      clientId: process.env.GOOGLE_CLIENT_ID as string,
      clientSecret: process.env.GOOGLE_SECRET as string,
    }),
  ],
  callbacks: {
    async signIn({ user, account, profile, email, credentials }) {
      const allowed = false  // Force a failure to login  
      if (allowed) {  
        return true
      }

      return false

    },
  },
  pages: { error: "/403" },
}

Solution

  • I found a solution at Unable to change account when I fail a login rule with NextAuth Google provider.

    signIn("google", undefined, { prompt: "select_account" })
    

    prompt: "select_account" will ask the user to log in again.