'Failing to fetch a user profile with Google OAuth20 and Passport
I'm getting some weird behavior when working with the Google OAuth20 strategy from Passport
Upon first login and no user in the DB, I'm able to create a new user profile and store it in the DB. However, when I logout and attempt to log back in, I'm never shown the consent screen for google. Could this be an issue with cookies?
Moreover, when there's no user in the DB and I attempt to log in for the first time. I don't get a consent screen, I simply get the following error:
InternalOAuthError: Failed to fetch user profile
There were some instances where I got an error regarding a missing access token.
Below is my configuration and routes:
passport.js
require("dotenv").config();
const passport = require("passport");
const User = require("../models/User");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
// Passport config:
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "http://localhost:8000/auth/google/redirect",
passReqToCallback: true,
},
async (request, accessToken, refreshToken, profile, done) => {
try {
const currentUser = await User.findOne({ googleId: profile.id });
if (!currentUser) {
const newUser = await new User({
googleId: profile.id,
username: profile.displayName,
}).save();
return done(null, newUser);
} else {
return done(null, currentUser);
}
} catch (error) {
console.log("Error found", error);
}
}
)
);
passport.serializeUser((user, done) => {
done(null, user);
});
passport.deserializeUser((user, done) => {
done(null, user);
});
routes/auth.js
// auth logout
router.get("/logout", (req, res) => {
// handle with passport
console.log("Current user:", req.user);
req.logout();
console.log("Current user after logout:", req.user);
res.redirect("/");
});
// auth with google
router.get(
"/google",
passport.authenticate("google", {
scope: ["email", "profile"],
})
);
// callback route for google to redirect to
router.get(
"/google/redirect",
passport.authenticate("google", { failureRedirect: "/login" }),
(req, res) => res.redirect("/")
);
module.exports = router;
server.js
app.use(session({ secret: "1fng4v", resave: false, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
const authRoutes = require("./routes/auth");
app.use("/auth", authRoutes);
app.get("/", (req, res) => {
res.send("Home!");
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|