Reputation: 31
I'm learning Authentication using passport-google-oauth20. When I try registering a user using Google+, I keep on getting this error message after failing to submit the request (InternalOAuthError: failed to fetch user profile).
I tried this solution:
2.Deprecated scopes
//jshint esversion:6
require('dotenv').config()
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = require('passport-local-mongoose');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const findOrCreate = require('mongoose-findorcreate');
const app = express();
app.use(express.static("public"));
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({
extended: true
}));
// save user sessionusing cookies
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
}));
//initializa passport and use it to manage sessions
app.use(passport.initialize());
app.use(passport.session());
mongoose.connect('mongodb://localhost:27017/userDB', {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true
});
mongoose.set("useCreateIndex", true);
const userSchema = new mongoose.Schema({
email: String,
password: String
});
userSchema.plugin(passportLocalMongoose);
userSchema.plugin(findOrCreate);
const user = mongoose.model("User", userSchema);
// use static authenticate method of model in LocalStrategy
passport.use(user.createStrategy());
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use(new GoogleStrategy({
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/secrets",
userProfileURL: "https: //www.googleapis.com/oauth2/v3/userinfo"
},
function(accessToken, refreshToken, profile, cb) {
console.log(profile);
user.findOrCreate({ googleId: profile.id }, function(err, user) {
return cb(err, user);
});
}
));
app.get("/", function(req, res) {
res.render("home");
});
app.get('/auth/google',
passport.authenticate('google', { scope: ['profile'] }));
app.get('/auth/google/secrets',
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
// Successful authentication, redirect secrets.
res.redirect('/secrets');
});
app.get("/login", function(req, res) {
res.render("login");
});
app.get("/register", function(req, res) {
res.render("register");
});
app.get("/secrets", function(req, res) {
if (req.isAuthenticated) {
res.render("secrets");
} else {
res.redirect("/login");
}
});
app.get("/logout", function(req, res) {
req.logout();
res.redirect("/");
});
app.post("/register", function(req, res) {
user.register({
username: req.body.username
}, req.body.password, function(err, user) {
if (err) {
console.log(err);
res.redirect("/register");
} else {
passport.authenticate("local")(req, res, function() {
res.redirect("/secrets");
});
}
});
});
app.post("/login", function(req, res) {
const user = new user({
name: req.body.username,
password: req.body.passwword
});
req.login(user, function(err) {
if (err) {
console.log(err);
} else {
passport.authenticate("local")(req, res, function() {
res.redirect("/secrets");
});
}
});
});
app.listen(3000, function() {
console.log("Server started on port 3000");
});ode here
Upvotes: 3
Views: 9010
Reputation: 1
You no longer need to use "userProfileURL" because the most recent version (v2.0.0) of the npm package resolves the Google+ account issue that existed a few years ago.
Upvotes: 0
Reputation: 185
In my case, the error "Failed to fetch user profile"
was caused by a bug in the grand-parent library node-oauth
. Specifically, it was a double callback handling.
https://github.com/jaredhanson/passport-google-oauth2/issues/87
These libraries passport-google-oauth2
, node-oauth
are very old and not maintained well. And I didn't want to play with my own forks on GitHub. I quickly fixed it with a package patch
approach.
https://dev.to/zhnedyalkow/the-easiest-way-to-patch-your-npm-package-4ece
How I applied a patch for the node-oauth
library with patch-package
:
Install patch-package
library.
Patch node_modules/oauth/lib/oauth2.js
with the code:
request.on('error', function(e) {
// `www.googleapis.com` does `ECONNRESET` just after data is received in `passBackControl`
// this prevents the callback from being called twice, first in passBackControl and second time in here
// see also NodeJS Stream documentation: "The 'error' event may be emitted by a Readable implementation at any time"
if(!callbackCalled) {
callbackCalled= true;
callback(e);
}
});
npx patch-package node-oauth
.Thanks @patil's answer for the tip about the bug.
Upvotes: 1
Reputation: 41
After breaking my head for 2 days found that , the issue is with node-auth package but node-oauth appears to be a dead project (the last commit was in 2017), and this bug is going to impact users of passport-google-oauth2 on fast connections. Please find issue explained below:
https://github.com/jaredhanson/passport-google-oauth2/issues/87
I feel its better to implement google-Oauth without passport js.
Upvotes: 2
Reputation: 11
The solution was just a typo in userProfileURL, I had it with a '0auth2', change it to 'oauth2' to "https://www.googleapis.com/oauth2/v3/userinfo" it worked!
Upvotes: 1
Reputation: 55
With couple of changes, it worked for me.
In the passport.deserializeUser() method, you should be using 'user' not 'User'.
In the passport.use(new GoogleStrategy....) you have a typo in the userProfileURL value.
userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo"
Please try these changes. Hope that helps. Note: also the default value for saveUninitialized is true. In your scenario, the value should be false, but true doesn't hurt either.
Upvotes: 1