我在使用 Google OAuth 2.0 进行身份验证后重定向用户时遇到设置 cookie 的问题。后端服务器使用 Node.js 和 Express.js,前端托管在与后端不同的域上。前端和 Nginx 都使用 HTTPS,但 Nginx 和服务器之间的连接是通过 HTTP 的。
我尝试在成功完成 Google OAuth 2.0 身份验证后设置 cookie,然后使用 res.redirect() 方法将用户重定向到前端域。
设置 cookie 的代码片段如下所示:
res.cookie("cookie", cookieValue, {
httpOnly: true,
sameSite: "none",
secure: true,
maxAge: 3 * 24 * 60 * 60 * 1000,
});
但是,浏览器中并未设置 cookie。仅当用户重定向到前端域时才会出现此问题。在本地主机环境中,一切都按预期运行。
后端服务器配置:
app.set("trust proxy", 1);
app.use(cors({
credentials: true,
origin: "https://frontend.com",
}));
app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(session({
secret: "session_secret",
resave: false,
saveUninitialized: false,
}));
Nginx 配置:
location /api/ {
proxy_pass http://ip.address:port;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
我的前端阻止了cookie,通过一些配置解决了它。
注意:还添加了一些 nginx 配置
proxy_set_header Cookie $http_cookie;
proxy_set_header SameSite SameSite=None;
proxy_set_header Secure Secure;