如何解决生产中 next-auth 的 api/auth/error 问题?

Fua*_*ad9 15 next.js next-auth

我在 Vercel 中设置了以下环境变量:

NEXTAUTH_URL=https://example.vercel.app (production) 
NEXTAUTH_URL=http://localhost:3000 (development)
Run Code Online (Sandbox Code Playgroud)

然后在 Google 提供商 GCP 控制台 ( https://console.cloud.google.com )中授权以下两个重定向 URL :

https://example.vercel.app/api/auth/callback/google
http://localhost:3000/api/auth/callback/google
Run Code Online (Sandbox Code Playgroud)

当我单击登录按钮时,它会重定向到此错误 URL:https://example.vercel.app/api/auth/error并显示“找不到此页面”。我还尝试为环境变量设置这些值:

NEXTAUTH_URL=https://example.vercel.app/api/auth 
NEXTAUTH_URL=https://example.vercel.app/api/auth/signin
Run Code Online (Sandbox Code Playgroud)

错误仍然存​​在。在开发 ( https://localhost:3000) 中,我能够成功登录:单击登录按钮时,它会正确地将我重定向到以下 URL:

http://localhost:3000/api/auth/signin?callbackUrl=http%3A%2F%2Flocalhost%3A3000%2F
Run Code Online (Sandbox Code Playgroud)

并显示 NextAuth 默认页面:

浏览器img

我的身份验证API pages/api/auth/[...nextauth].js

NEXTAUTH_URL=https://example.vercel.app (production) 
NEXTAUTH_URL=http://localhost:3000 (development)
Run Code Online (Sandbox Code Playgroud)

如何解决这个问题?我错过了什么吗?

Oxf*_*ist 14

当库的文档使用类似的内容https://example.com而不指出它实际上是一个示例时,我总是发现有些误导。幸运的是,这很容易解决!

1. 正确域名NEXTAUTH_URL

由于https://example.vercel.app它实际上是一个示例,因此NEXTAUTH_URL您应该将其设置为您自己的应用程序域,而不是设置它。您可以从Vercel 中的“概述”页面的“域”下获取您的应用程序域。在以下示例中,应用程序域为https://my-simple-app.vercel.app

Vercel 中的概述页面的屏幕截图,显示应用程序域

NEXTAUTH_URL=https://my-simple-app.vercel.app (production) 
Run Code Online (Sandbox Code Playgroud)

2. GCP控制台上的正确域名

应该在 GCP 控制台中执行相同的操作,而不是放置https://example.vercel.app/api/auth/callback/google,您应该放置您自己的应用程序域,在上面的示例中,这将是https://my-simple-app.vercel.app/api/auth/callback/google

显示授权 URI 的 Google Cloud Platform 控制台的屏幕截图

应该这样做!

额外资源

如果您需要更多信息,我可以推荐这篇文章。它从头开始,帮助我澄清了在 Vercel 部署中进行身份验证所需的内容。


gep*_*epe 5

import NextAuth from "next-auth"\nimport RedditProvider from "next-auth/providers/reddit"\nimport GoogleProvider from "next-auth/providers/google";\n    \nexport default NextAuth({\n  // Configure one or more authentication providers\n  providers: [\n    RedditProvider({\n      clientId: process.env.REDDIT_CLIENT_ID,\n      clientSecret: process.env.REDDIT_CLIENT_SECRET\n    }),\n    // ...add more providers here\n    GoogleProvider({\n      clientId: process.env.GOOGLE_CLIENT_ID,\n      clientSecret: process.env.GOOGLE_CLIENT_SECRET\n    })\n  ],\n  secret: \'IamVeryHandsome\' \n})\n
Run Code Online (Sandbox Code Playgroud)\n

它对我有用,秘密是: \'anystring\'。谢谢 \xd7\x99\xd7\x90\xd7\x99\xd7\xa8 \xd7\x90\xd7\x9c\xd7\x9e\xd7\x9c\xd7\x99\xd7\x97\ni 使用\n"下一步": "12.1.6",\n"next-auth": "^4.5.0",

\n

赞赏

\n