nextauthjs / next-auth

Authentication for the Web.
https://authjs.dev
ISC License
24.18k stars 3.35k forks source link

Apple provider callback not working Next-auth v4 (App Router) #10338

Closed mycvlnn closed 6 months ago

mycvlnn commented 6 months ago

Environment

System: OS: macOS 14.3.1 CPU: (10) arm64 Apple M2 Pro Memory: 273.83 MB / 32.00 GB Shell: 5.9 - /bin/zsh Binaries: Node: 18.18.1 - /usr/local/bin/node npm: 9.8.1 - /usr/local/bin/npm Browsers: Chrome: 122.0.6261.128 Safari: 17.3.1 npmPackages: next: 14.0.2 => 14.0.2 next-auth: ^4.24.5 => 4.24.7 react: ^18 => 18.2.0

Reproduction URL

https://github.com/nextauthjs/next-auth-example

Describe the issue

I integrated Apple Sign-in into my website but I constantly get this error:

[next-auth][error][OAUTH_CALLBACK_ERROR] 
https://next-auth.js.org/errors#oauth_callback_error invalid_client {
  error: i: invalid_client
      at e.exports (/var/task/.next/server/chunks/674.js:39:35799)
      at q.grant (/var/task/.next/server/chunks/674.js:39:15085)
      at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
      at async q.callback (/var/task/.next/server/chunks/674.js:39:2818)
      at async l (/var/task/.next/server/chunks/674.js:6:32639)
      at async Object.c (/var/task/.next/server/chunks/674.js:30:781)
      at async m (/var/task/.next/server/chunks/674.js:6:16179)
      at async a (/var/task/.next/server/chunks/674.js:30:18364)
      at async e.length.t (/var/task/.next/server/chunks/674.js:30:19780)
      at async /var/task/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:41304 {
    name: 'OAuthCallbackError',
    code: undefined
  },
  providerId: 'apple',
  message: 'invalid_client'
}

I already have Google sign-in and it is working. When I try to sign-in via Apple, callback does not work and this is the URL I get as a result: https://www.pinify.co/signin?callbackUrl=https%3A%2F%2Fwww.pinify.co%2Fdashboard&error=OAuthCallback

I have used this script to generate the client secret.

I am aware that some people faced this issue in the past and I tried numerous solutions like https://github.com/nextauthjs/next-auth/discussions/3503, https://github.com/nextauthjs/next-auth/discussions/5879, https://github.com/nextauthjs/next-auth/issues/5810, https://github.com/nextauthjs/next-auth/issues/6788 but none of them could make it work. Any ideas? image

How to reproduce

Navigate to https://www.pinify.co/signin and click "Continue with Apple". See error.

This is the current code I am using.

import { NextAuthOptions, User, getServerSession } from "next-auth";
import prismadb from "@/lib/prismadb";

import GoogleProvider from "next-auth/providers/google";
import AppleProvider from "next-auth/providers/apple";
import type { DefaultSession } from 'next-auth';

declare module 'next-auth' {
  interface Session {
    user: DefaultSession['user'] & {
      id: string; // Custom Session property
    };
  }
}

export const authConfig: NextAuthOptions = {
    debug: true,
    pages: {
      signIn: "/signin"
    },
    providers: [
        GoogleProvider({
          clientId: process.env.GOOGLE_CLIENT_ID as string,
          clientSecret: process.env.GOOGLE_CLIENT_SECRET as string,
          allowDangerousEmailAccountLinking: true,
        }),
        AppleProvider({
          authorization: {
            params: {
              scope: "name email",
              response_mode: "form_post",
              response_type: "code",
            },
          },
          clientId: process.env.APPLE_CLIENT_ID as string,
          clientSecret: process.env.APPLE_CLIENT_SECRET as string,
          allowDangerousEmailAccountLinking: true,

        }),
    ],
    cookies: {
      csrfToken: {
        name: 'next-auth.csrf-token',
        options: {
          httpOnly: false,
          sameSite: 'none',
          path: '/',
          secure: true
        }
      },
      pkceCodeVerifier: {
        name: "next-auth.pkce.code_verifier",
        options: {
          httpOnly: false,
          sameSite: "none",
          path: "/",
          secure: true,
        },
      },
      callbackUrl: {
        name: `__Secure-next-auth.callback-url`,
        options: {
          httpOnly: false,
          sameSite: 'none',
          path: '/',
          secure: true,
        },
      },
    },  
    callbacks: {
      async signIn({ user, account, profile }) {
          const email = user.email;
          if (email) {
            let existingUser = await prismadb.user.findUnique({
              where: { emailAddress: email },
            });

            // If user doesn't exist, we create one. 
            if (!existingUser) {
              existingUser = await prismadb.user.create({
                data: {
                  name: user.name || email,
                  emailAddress: email,
                },
              });
            }
          }
          return true; // Returning true allows the sign-in to proceed
      },
      async session({ session, user }) {
          // Optionally customize the session object
          // e.g., add user ID or roles from the database to the session
          if (session.user){        
              const dbUser = await prismadb.user.findUnique({
                  where: { emailAddress: session.user.email || undefined }
              });

              if (dbUser) {
                  return { ...session,
                      user: { ...session.user,
                        id: dbUser.id
                      }
                  }
              }
          }
          return session;
      },
      async redirect({ url, baseUrl }) {
        if (url.startsWith("/")) return `${baseUrl}${url}`
        else if (new URL(url).origin === baseUrl) return url
        return baseUrl
      }
    }
};

Expected behavior

Google, Kakao, Line, Facebook is working flawlessly. I expect the Apple Provider to work the same way.

github-actions[bot] commented 6 months ago

We could not detect a valid reproduction link. Make sure to follow the bug report template carefully.

Why was this issue closed?

To be able to investigate, we need access to a reproduction to identify what triggered the issue. We need a link to a public GitHub repository. Example: (NextAuth.js example repository).

The bug template that you filled out has a section called "Reproduction URL", which is where you should provide the link to the reproduction.

What should I do?

Depending on the reason the issue was closed, you can do the following:

In general, assume that we should not go through a lengthy onboarding process at your company code only to be able to verify an issue.

My repository is private and cannot make it public

In most cases, a private repo will not be a sufficient minimal reproduction, as this codebase might contain a lot of unrelated parts that would make our investigation take longer. Please do not make it public. Instead, create a new repository using the templates above, adding the relevant code to reproduce the issue. Common things to look out for:

I did not open this issue, but it is relevant to me, what can I do to help?

Anyone experiencing the same issue is welcome to provide a minimal reproduction following the above steps by opening a new issue.

I think my reproduction is good enough, why aren't you looking into it quickly?

We look into every issue and monitor open issues for new comments.

However, sometimes we might miss a few due to the popularity/high traffic of the repository. We apologize, and kindly ask you to refrain from tagging core maintainers, as that will usually not result in increased priority.

Upvoting issues to show your interest will help us prioritize and address them as quickly as possible. That said, every issue is important to us, and if an issue gets closed by accident, we encourage you to open a new one linking to the old issue and we will look into it.

Useful Resources