使用Passport.js+Express实现Google登录时遇Redirect URI Mismatch错误
解决Passport.js+Express Google登录的Redirect URI Mismatch错误
我尝试用Passport.js和Express实现Google登录功能,但反复遇到Redirect URI Mismatch错误。多次核对代码中的callbackURL与Google开发者控制台内的授权重定向URI,确认二者一致,但问题仍未解决。
Passport.js配置代码
import passport from "passport"; import { Strategy } from "passport-google-oauth20"; import db from "../../lib/database.js"; export default function (passport: passport.PassportStatic) { passport.use( new Strategy( { clientID: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, callbackURL: "http://127.0.0.1:3000/auth/google/callback", }, async (accessToken, refreshToken, profile, done) => { const user = db.user.findFirst({ where: { authProvider: "google", authProviderId: profile.id, }, }); if (!user) { const newUser = db.user.create({ data: { authProvider: "google", authProviderId: profile.id, name: profile.displayName, email: profile.emails[0].value, }, }); return done(null, newUser); } return done(null, user); } ) ); }
认证路由代码
import passport from "passport"; import express from "express"; import passportConfig from "../configs/passportConfig.js"; passportConfig(passport); const router = express.Router(); router.get( "/auth/google", passport.authenticate("google", { scope: ["profile"] }) ); router.get( "/auth/google/callback", passport.authenticate("google", { failureRedirect: "/login" }), function (req, res) { // Successful authentication, redirect home. res.redirect("/"); } ); export default router;
Google开发者控制台授权重定向URI

错误界面截图

排查与解决方法
- 严格匹配URI细节:确认代码中的callbackURL和Google控制台的URI完全一致,包括是否有末尾斜杠、大小写(Google OAuth对URI匹配要求严格,
localhost和127.0.0.1视为不同地址),检查是否存在复制时的空格或隐藏字符。 - 核对OAuth客户端ID:确保代码中使用的
GOOGLE_CLIENT_ID与控制台配置重定向URI的OAuth客户端ID完全对应,避免混用多个客户端的ID。 - 修正异步操作问题:代码中查询和创建用户的数据库操作未加
await,会导致逻辑错误,需修改:// 查询用户 const user = await db.user.findFirst({ where: { authProvider: "google", authProviderId: profile.id, }, }); // 创建新用户 const newUser = await db.user.create({ data: { authProvider: "google", authProviderId: profile.id, name: profile.displayName, email: profile.emails[0].value, }, }); - 添加Passport序列化配置:缺少序列化/反序列化用户的逻辑会导致认证流程异常,需补充:
passport.serializeUser((user, done) => { done(null, user.id); }); passport.deserializeUser(async (id, done) => { const user = await db.user.findUnique({ where: { id } }); done(null, user); }); - 更新权限Scope:当前仅请求
profile权限,若需获取邮箱需添加emailscope,修改路由配置:router.get( "/auth/google", passport.authenticate("google", { scope: ["profile", "email"] }) ); - 清除浏览器缓存:浏览器可能缓存旧的OAuth请求信息,清除Cookie和缓存后重新测试。
内容的提问来源于stack exchange,提问作者bearthum
相关产品推荐
相关产品推荐

