Next Auth 登录成功后子域名重定向异常问题求助
Next Auth多子域名登录重定向问题解决方案
1. 动态生成NEXTAUTH_URL
固定的NEXTAUTH_URL没法适配多子域名场景,必须在Next Auth配置里根据请求动态生成,而非依赖.env中的固定值:
// pages/api/auth/[...nextauth].js import NextAuth from "next-auth"; import YourCustomProvider from "./path-to-your-provider"; export default NextAuth({ providers: [YourCustomProvider], session: { strategy: "jwt" }, callbacks: { async redirect({ url, req }) { // 从请求头获取当前访问的子域名 const currentProtocol = req.headers["x-forwarded-proto"] || "http"; const currentHost = req.headers.host; const dynamicBaseUrl = `${currentProtocol}://${currentHost}`; // 处理相对路径重定向 if (url.startsWith("/")) { return `${dynamicBaseUrl}${url}`; } // 验证目标URL是否属于当前域名体系,防止恶意跳转 const targetHost = new URL(url).hostname; const rootDomain = currentHost.split(".").slice(-2).join("."); if (targetHost.endsWith(rootDomain)) { return url; } // 默认重定向到当前子域名首页 return dynamicBaseUrl; }, }, // 配置Cookie跨子域名共享 cookies: { sessionToken: { name: `__Secure-next-auth.session-token`, domain: ".example.com", // 替换为你的根域名,比如".yourdomain.com" path: "/", secure: true, httpOnly: true, sameSite: "lax", }, callbackUrl: { name: `__Secure-next-auth.callback-url`, domain: ".example.com", path: "/", secure: true, }, // 其他Next Auth相关Cookie同理添加domain配置 }, });
2. 动态配置OAuth Provider的redirect_uri
每个子域名对应的OAuth应用,必须在提供商后台配置对应的回调地址(比如https://subdomain.example.com/api/auth/callback/your-provider)。同时在自定义Provider里动态生成redirect_uri:
// 自定义OAuth Provider配置 const YourCustomProvider = { id: "your-provider-id", name: "Your Provider", type: "oauth", version: "2.0", wellKnown: "https://your-provider-domain/.well-known/openid-configuration", async profile(profile) { return { id: profile.sub, name: profile.name, email: profile.email, // 其他需要的字段 }; }, authorization: { url: "https://your-provider-domain/oauth/authorize", params: { scope: "openid email profile" }, }, token: "https://your-provider-domain/oauth/token", userinfo: "https://your-provider-domain/oauth/userinfo", // 动态生成当前子域名的回调地址 async redirectUri({ req }) { const protocol = req.headers["x-forwarded-proto"] || "http"; const host = req.headers.host; return `${protocol}://${host}/api/auth/callback/${this.id}`; }, };
3. 登录时显式传递callbackUrl
调用signIn方法时,把当前页面的URL作为callbackUrl传递,确保登录后回到当前子域名:
// 登录组件示例 import { signIn } from "next-auth/react"; export default function LoginBtn() { const currentCallbackUrl = typeof window !== "undefined" ? window.location.href : ""; return ( <button onClick={() => signIn("your-provider-id", { callbackUrl: currentCallbackUrl })} > 登录 </button> ); }
核心要点
- Cookie域名必须设为根域名:如果不配置Cookie的
domain为.example.com,子域名无法读取主域名下的Cookie,会导致登录状态丢失。 - 绝对不能用固定NEXTAUTH_URL:Next Auth的很多内部逻辑依赖
NEXTAUTH_URL,固定值会强制所有重定向指向主域名,动态生成才能适配子域名。 - OAuth回调地址必须匹配:每个子域名的OAuth应用都要在提供商后台单独配置回调地址,否则会触发“回调地址不匹配”的错误。
内容的提问来源于stack exchange,提问作者Cam
相关产品推荐
相关产品推荐

