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:
77
lib/auth.ts
77
lib/auth.ts
@ -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,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user