fix: resolve OAuth state cookie error - Add proper Cookie configuration with domain settings - Add domain extraction function for production environment - Update environment variables example

This commit is contained in:
theshy
2025-08-01 20:20:03 +08:00
parent da41306918
commit 2cd0ebda65
5 changed files with 162 additions and 13 deletions

View File

@ -33,6 +33,17 @@ function getValidatedNextAuthUrl(): string {
return cleanUrl;
}
// 获取域名用于 Cookie 配置
function getDomain(): string {
const url = getValidatedNextAuthUrl();
try {
const urlObj = new URL(url);
return urlObj.hostname;
} catch {
return "recorder.zyj.best"; // 默认域名
}
}
export const authOptions: AuthOptions = {
adapter: PrismaAdapter(prisma),
@ -121,6 +132,68 @@ export const authOptions: AuthOptions = {
debug: process.env.NODE_ENV === "development",
// 使用验证后的 URL
url: getValidatedNextAuthUrl(),
// 添加 Cookie 配置
cookies: {
sessionToken: {
name: `next-auth.session-token`,
options: {
httpOnly: true,
sameSite: "lax",
path: "/",
secure: process.env.NODE_ENV === "production",
domain: process.env.NODE_ENV === "production" ? getDomain() : undefined,
},
},
callbackUrl: {
name: `next-auth.callback-url`,
options: {
sameSite: "lax",
path: "/",
secure: process.env.NODE_ENV === "production",
domain: process.env.NODE_ENV === "production" ? getDomain() : undefined,
},
},
csrfToken: {
name: `next-auth.csrf-token`,
options: {
httpOnly: true,
sameSite: "lax",
path: "/",
secure: process.env.NODE_ENV === "production",
domain: process.env.NODE_ENV === "production" ? getDomain() : undefined,
},
},
pkceCodeVerifier: {
name: `next-auth.pkce.code_verifier`,
options: {
httpOnly: true,
sameSite: "lax",
path: "/",
maxAge: 900,
secure: process.env.NODE_ENV === "production",
domain: process.env.NODE_ENV === "production" ? getDomain() : undefined,
},
},
state: {
name: `next-auth.state`,
options: {
httpOnly: true,
sameSite: "lax",
path: "/",
maxAge: 900,
secure: process.env.NODE_ENV === "production",
domain: process.env.NODE_ENV === "production" ? getDomain() : undefined,
},
},
nonce: {
name: `next-auth.nonce`,
options: {
httpOnly: true,
sameSite: "lax",
path: "/",
secure: process.env.NODE_ENV === "production",
domain: process.env.NODE_ENV === "production" ? getDomain() : undefined,
},
},
},
};