nextauthjs / next-auth

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

Apple Provider callback error.. #8837

Closed SungbeenPark closed 11 months ago

SungbeenPark commented 11 months ago

Provider type

Apple

Environment

System: OS: macOS 14.0 CPU: (10) arm64 Apple M1 Pro Memory: 560.66 MB / 32.00 GB Shell: 5.9 - /bin/zsh Binaries: Node: 18.18.0 - /opt/homebrew/bin/node Yarn: 1.22.19 - /opt/homebrew/bin/yarn npm: 9.8.1 - /opt/homebrew/bin/npm Browsers: Chrome: 117.0.5938.149 Edge: 117.0.2045.55 Safari: 17.0

Reproduction URL

https://app-test.daeryunlaw.co.kr/auth/signin?callbackUrl=https%3A%2F%2Fapp-test.daeryunlaw.co.kr

Describe the issue

authLogger error OAUTH_CALLBACK_ERROR

` import type {NextAuthOptions} from "next-auth" import NextAuth, {Theme} from "next-auth" import NaverProvider from "next-auth/providers/naver"; import Kakao from "next-auth/providers/kakao"; import Google from "next-auth/providers/google"; import Apple from "next-auth/providers/apple"; import DaeryunAdapter from "@/pages/api/auth/DaeryunAdapter"; import EmailProvider from "next-auth/providers/email"; import {createTransport} from "nodemailer";

export const authOptions: NextAuthOptions = { adapter: DaeryunAdapter(), // adapter: TypeORMAdapter(connection), logger: { warn: (message) => console.warn("authLogger warn ", message), debug: (message) => console.debug("authLogger debug ", message), error: (message) => console.error("authLogger error ", message), }, secret: process.env.SECRET ?? "", jwt: { // The maximum age of the NextAuth.js issued JWT in seconds. // Defaults to session.maxAge. maxAge: 60 60 24 * 7, // 1 week }, pages: { signIn: '/auth/signin', signOut: '/auth/signout', error: '/error', // Error code passed in query string as ?error= verifyRequest: '/auth/verify-request', // (used for check email message) newUser: '/user/agree' // New users will be directed here on first sign in (leave the property out if not of interest) }, callbacks: { async jwt({token, user, account, profile, isNewUser}) { console.log("callbacks-jwt",token,user,account,profile,isNewUser) return token }, async signIn({user, account, profile, email, credentials}) { console.log("callbacks-signIn",user.id,user,account,profile,email,credentials)

        // //@ts-ignore
        // if (user && profile)
        //  //네이버는 폰번호 와서 처리함. 구글 번호없음, 카카오는 번호줄텐데 상용 버전에서 확인 해야함.
        //  if (account?.provider === "naver") {
        //      const newPfofile = {...profile}
        //      //@ts-ignore
        //      if (newPfofile.resultcode && newPfofile.resultcode === "00") {
        //          //@ts-ignore
        //          const res = newPfofile.response
        //          const phoneNumber = res.mobile ?? ""
        //          if (phoneNumber !== "") {
        //              // eslint-disable-next-line react-hooks/rules-of-hooks
        //              await useUsersActions().updateUserPhoneNumber(user.id, phoneNumber.replace(/-/g, ""))
        //          }
        //      }
        //  }
        return true
    },
    async redirect({url, baseUrl}) {
        console.log("redirect",url,baseUrl)
        return baseUrl
    },
    async session({session, token, user}): Promise<any> {
        console.log("session",session,token,"user:",user)
        // const user_id = user.id.toString();
        // sessionStorage.setItem( "test" , user_id)
        return {...session, userId: user.id}
    }
},
/**
 * 애플 로그인 시 쿠키옵션 적용해 주어야 callbackUrl이 정상 작동
 */
cookies: {
    callbackUrl: {
        name: `__Secure-next-auth.callback-url`,
        options: {
            httpOnly: false,
            sameSite: "none",
            path: "/",
            secure: true,
        },
    },
},
providers: [
    NaverProvider({
        clientId: process.env.NAVER_ID ?? "",
        clientSecret: process.env.NAVER_SECRET ?? ""

    }),
    Kakao({
        clientId: process.env.KAKAO_ID ?? "",
        clientSecret: process.env.KAKAO_SECRET ?? ""
    }),
    Google({
        clientId: process.env.GOOGLE_ID ?? "",
        clientSecret: process.env.GOOGLE_SECRET ?? ""
    }),
    Apple({
        clientId: process.env.APPLE_ID ?? "",
        clientSecret: process.env.APPLE_SECRET ?? "",
    }),
    EmailProvider({
        server: {
            secure: true,
            host: process.env.EMAIL_SERVER_HOST ?? "",
            port: Number(process.env.EMAIL_SERVER_PORT) ?? 4444,
            auth: {
                user: process.env.EMAIL_SERVER_USER ?? "",
                pass: process.env.EMAIL_SERVER_PASSWORD ?? "",
            }
        },
        from: process.env.EMAIL_FROM,
        sendVerificationRequest: async (params) => {
            const {identifier, url, provider, theme} = params
            const {host} = new URL(url)
            // NOTE: You are not required to use `nodemailer`, use whatever you want.
            const transport = createTransport(provider.server)
            const result = await transport.sendMail({
                to: identifier,
                from: provider.from,
                subject: `[LawFirm.com] 이메일 인증 로그인`,
                text: text({url, host}),
                html: html({url, host, theme}),
            })
            const failed = result.rejected.concat(result.pending).filter(Boolean)
            if (failed.length) {
                throw new Error(`Email(s) (${failed.join(", ")}) could not be sent`)
            }
        },
        normalizeIdentifier(identifier: string): string {
            // Get the first two elements only,
            // separated by `@` from user input.
            let [local, domain] = identifier.toLowerCase().trim().split("@")
            // The part before "@" can contain a ","
            // but we remove it on the domain part
            domain = domain.split(",")[0]
            return `${local}@${domain}`

        }
    })
],

}

const authHandler = NextAuth(authOptions)

export default async function handler(...params: any[]) { // if(req.query.nextauth.includes("callback") && req.method === "POST") { // console.log( // "Handling callback request from my Identity Provider", // req.body // ) // } await authHandler(...params) }

/**

/* Email Text body (fallback for email clients that don't render HTML, e.g. feature phones) / function text({ url, host }: { url: string; host: string }) { return 로그인 하기 ${host}\n${url}\n\n } `

How to reproduce

try. apple oauth login

Expected behavior

log - "authLogger error OAUTH_CALLBACK_ERROR"

websiate - login page-> apple login page-> login page

github-actions[bot] commented 11 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