生产环境下NextAuth无法重定向至Google登录的问题及解决
问题:NextAuth Google认证无法跳转至Google登录页(生产环境IIS部署)
环境信息
- 部署环境:Windows服务器(Node.js 22.2.0)
- 应用框架:Next.js
- 认证方案:NextAuth + Google Provider(外部模式)
- 数据库:Prisma连接MSSQL
问题现象
本地连接远程数据库时功能正常,部署到生产环境后:
- 点击「Sign in with Google」后,停留在NextAuth默认提供商选择页,URL有变化但不会跳转至Google登录页
- NextAuth调试日志显示已生成正确的Google授权URL,但实际未完成跳转
关键调试日志片段
Redirect Callback: { url: '/', baseUrl: 'https://XXX.XXX.XXX' } [next-auth][debug][GET_AUTHORIZATION_URL] { url: 'https://accounts.google.com/o/oauth2/v2/auth?client_id=193456009801-t513geo4qhwt190v38226opnjjo47e15.apps.googleusercontent.com&scope=openid%20email%20profile&response_type=code&redirect_uri=https%3A%2F%2Fpenman.shadow-me.de%2Fapi%2Fauth%2Fcallback%2Fgoogle&access_type=offline&prompt=consent&state=4T9SHczCWABapR57lRH7GxIdt1wthBowRz5eHz3194o&code_challenge=dAOFHP2nLVlJ3Bie1iSpqrvTWwthtf0LO7XKDoY65t0&code_challenge_method=S256', ... } Redirect Callback: { url: '/o/oauth2/v2/auth?client_id=193456009801-t513geo4qrgraev38226opnjjo47e15.apps.googleusercontent.com&scope=openid+email+profile&response_type=code&redirect_uri=https%3A%2F%2FXXX.XXX.XXX%2Fapi%2Fauth%2Fcallback%2Fgoogle&access_type=offline&prompt=consent&state=4T9SHczCWABapR57lRH7GwthrwtZBowRz5eHz3194o&code_challenge=dAOFHP2nLVlJ3Bie1iSpqrvTWv9hZf0LO7XKDoY65t0&code_challenge_method=S256', baseUrl: 'https://XXX.XXX.XXX' } Redirect Callback: { url: '/o/oauth2/v2/auth?client_id=193456009801-t513geo4qr441rtsh226opnjjo47e15.apps.googleusercontent.com', baseUrl: 'https://XXX.XXX.XXX' }
NextAuth配置代码
import NextAuth from "next-auth"; import GoogleProvider from "next-auth/providers/google"; import { PrismaAdapter } from "@next-auth/prisma-adapter"; import prisma from "@/prisma/client"; const handler = NextAuth({ adapter: PrismaAdapter(prisma), providers: [ GoogleProvider({ clientId: process.env.GOOGLE_CLIENT_ID!, clientSecret: process.env.GOOGLE_CLIENT_SECRET!, authorization: { params: { scope: "openid email profile", access_type: "offline", prompt: "consent", }, }, }), ], session: { strategy: "jwt", }, debug: true, callbacks: { async signIn({ user, account, profile, email, credentials }) { console.log("SignIn Callback:", { user, account, profile, email, credentials, }); return true; }, async redirect({ url, baseUrl }) { console.log("Redirect Callback:", { url, baseUrl }); return url.startsWith(baseUrl) ? url : baseUrl; }, async session({ session, user, token }) { console.log("Session Callback:", { session, user, token }); return session; }, async jwt({ token, user, account, profile, isNewUser }) { console.log("JWT Callback:", { token, user, account, profile, isNewUser, }); return token; }, }, }); export { handler as GET, handler as POST };
排查过程
- 确认Google Cloud控制台中重定向URI、Client ID、Client Secret配置正确,请求体参数无误
- 应用与认证服务同子域名,排除跨域问题
- 最终定位:IIS反向代理的URL重写规则修改了响应头中的跳转链接,导致Google授权URL被截断
解决方案
在IIS设置中取消勾选**「reverse rewrite host in response headers」**选项,禁止IIS重写外部跳转链接(如Google授权URL),确保NextAuth生成的完整跳转地址能正常生效。
内容的提问来源于stack exchange,提问作者beanCounter
相关产品推荐
相关产品推荐

