Google登录生产环境异常:redirect_uri不匹配及重定向错误
解决Google社交登录生产环境redirect_uri不匹配问题
你的问题核心确实是后端向Google发送请求时使用了localhost:8000作为回调地址,根源在于硬编码的配置和反向代理未传递真实请求头,以下是具体解决步骤:
1. 动态配置Passport Google策略的回调URL
不要硬编码回调地址,根据环境区分开发/生产环境,或者通过反向代理传递的请求头动态生成:
const GoogleStrategy = require('passport-google-oauth20').Strategy; passport.use(new GoogleStrategy({ clientID: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, // 按环境切换回调地址 callbackURL: process.env.NODE_ENV === 'production' ? 'https://www.example.com/api/auth/google/callback' : 'http://localhost:8000/auth/google/callback', // 开启代理信任,让Passport识别反向代理传递的请求头 proxy: true }, (accessToken, refreshToken, profile, done) => { // 你的用户逻辑处理 }));
同时修正successRedirect的硬编码问题:
export const googleAuth = passport.authenticate("google", { scope: ["email", "profile"], successRedirect: process.env.NODE_ENV === 'production' ? 'https://www.example.com' // 替换为你的生产前端域名 : 'http://localhost:3000' });
2. 修正Nginx配置,传递真实请求头
后端在反向代理下默认会认为请求来自localhost,需要让Nginx传递真实的主机名和协议:
location /api/ { proxy_pass http://localhost:8000/; # 传递真实主机名 proxy_set_header Host $host; # 传递真实协议(HTTPS) proxy_set_header X-Forwarded-Proto $scheme; # 传递真实客户端IP(可选) proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; }
同时在Node.js后端(如Express)开启信任代理:
// Express应用实例 app.set('trust proxy', true);
3. 清理Google Cloud Console的重定向URI
删除之前添加的http://localhost:8000/auth/google/callback,只保留生产环境的https://www.example.com/api/auth/google/callback,避免配置混淆。
完成以上修改后,重启后端和Nginx服务,登录流程即可正确重定向到生产环境URL,不会再出现redirect_uri_mismatch错误。
内容的提问来源于stack exchange,提问作者plutownium
相关产品推荐
相关产品推荐

