Reputation: 24671
I'm trying to embed google authentication in Node.js using passport and google passport-google-oauth20. The problem is that when the google callback route opens up I get:
Error
at Strategy.OAuth2Strategy.parseErrorResponse (E:\Programowanie\NodeJS\Hydronide\node_modules\passport-oauth2\lib\strategy.js:329:12)
at Strategy.OAuth2Strategy._createOAuthError (E:\Programowanie\NodeJS\Hydronide\node_modules\passport-oauth2\lib\strategy.js:376:16)
at E:\Programowanie\NodeJS\Hydronide\node_modules\passport-oauth2\lib\strategy.js:166:45
at E:\Programowanie\NodeJS\Hydronide\node_modules\oauth\lib\oauth2.js:191:18
at passBackControl (E:\Programowanie\NodeJS\Hydronide\node_modules\oauth\lib\oauth2.js:132:9)
at IncomingMessage.<anonymous> (E:\Programowanie\NodeJS\Hydronide\node_modules\oauth\lib\oauth2.js:157:7)
at emitNone (events.js:110:20)
at IncomingMessage.emit (events.js:207:7)
at endReadableNT (_stream_readable.js:1059:12)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickCallback (internal/process/next_tick.js:180:9)
I (more or less) follow this tutorial. Here is my code: Routes (starting with '/auth')
'use strict'
const passport = require('passport')
const router = require('express').Router()
router.get(
'/google',
(req, res, next) => {
if (req.query.return) {
req.session.oauth2return = req.query.return
}
next()
},
passport.authenticate('google', { scope: ['email', 'profile'] })
)
router.get(
'/google/callback',
passport.authenticate('google'),
(req, res) => {
const redirect = req.session.oauth2return || '/';
delete req.session.oauth2return;
res.redirect(redirect);
}
);
module.exports = router
There is a passport configuration:
'use strict'
const passport = require('passport')
const keys = require('./keys')
const GoogleStrategy = require('passport-google-oauth20').Strategy
const userController = require('../controllers/user-controller')
const passportConfig = {
clientID: keys.google.clientId,
clientSecret: keys.google.clientSecret,
callbackURL: 'auth/google/callback',
accessType: 'offline'
}
passport.use(new GoogleStrategy(passportConfig,
(accessToken, refreshToken, profile, done) => {
console.log(accessToken, refreshToken, profile, done)
userController.getUserByExternalId('google', profile.id)
.then(user => {
if (!user) {
userController.createUser(profile, 'google')
.then(user => {
return done(null, user)
})
.catch(err => {
return done(err)
})
}
return done(null, user)
})
.catch(err => {
return done(err)
})
}))
passport.serializeUser((user, cb) => {
cb(null, user)
})
passport.deserializeUser((obj, cb) => {
cb(null, obj)
})
As you can see I've added console.log in the new GoogleStrategy second parameter function, but it never fires.
//EDIT
I noticed that instead of assign require('passport-google-oauth20').Strategy
I used require('passport-google-oauth20')
. But fixing it doesn't chang anything, still the same error.
What I can add to a question is that in my main fail I call
// sets passport config
require('./config/jwt-auth')
require('./config/google-auth')
// initialize passport
app.use(passport.initialize())
So I don't expect anything wrong in there.
Upvotes: 7
Views: 12557
Reputation: 1
passport.use(new GoogleStrategy({
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/home"
},
function(accessToken, refreshToken, profile, cb) {
console.log(profile);
User.findOrCreate({ username: profile.displayName, googleId: profile.id },
function (err, user) {
return cb(err, user);
});
}));
Upvotes: 0
Reputation: 1
In passport.js you need to change callbackURL from 'auth/google/callback' to '/auth/google/callback'. Do not forget to add '/' before auth.
passport.use(new googleStrategy({
clientID:keys.clientID,
clientSecret:keys.clientSecret,
callbackURL:'/auth/google/callback'
},(accessToken,refreshToken, profile,done)=>{
console.log(accessToken);
console.log(refreshToken);
console.log(profile);
}
));
Upvotes: 0
Reputation: 275
const express = require('express');
const router = express.Router();
const { User } = require('../models/user.model');
const jwt = require('jsonwebtoken');
const config = require('../config/config.json');
const role = require('../lib/role');
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
router.use(passport.initialize());
passport.serializeUser((user, cb) => {
cb(null, user);
});
passport.deserializeUser((obj, cb) => {
cb(null, obj);
});
passport.use(new GoogleStrategy({
clientID: "sssssssssssssssssssssssssss",
clientSecret: "Vsssssssssssssss",
callbackURL: "http://localhost:4000/api/auth/google/callback"
},
(request, accessToken, refreshToken, profile, cb) => {
User.findOne({ email: profile.emails[0].value }, (err, user) => {
if (err) {
cb(err); // handle errors!
}
if (!err && user !== null) {
cb(err, user);
}
else {
user = new User({
googleId: profile.id,
email: profile.emails[0].value,
firstname: profile.name.givenName,
lastname: profile.name.familyName,
role: role.Client,
isActive: true,
isGain: false,
});
user.save((err) => {
if (err) {
cb(err); // handle errors!
} else {
cb(null, user);
}
});
}
});
}
));
router.get('/', passport.authenticate('google', { session: false, scope: ['profile', 'email'] }));
// callback
router.get('/callback', passport.authenticate('google', { failureRedirect: '/failed' }),
(req, res) => {
const token = jwt.sign({ userId: req.user._id, email: req.user.email, role: req.user.role }, config.secret_key, { expiresIn: '10 h' })
res.status(200).json({ success: true, token, expireIn: `${new Date().getTime() + 120000}` })
}
);
//failed auth google
router.get('/failed', async (req, res) => { res.status(404).send('erreur authentification') })
module.exports = router;
Upvotes: 0
Reputation: 653
I solved the issue by checking this route
app.get('/auth',passport.authenticate('google',{
scope:['profile','email']
}));
I was trying to do something to new users and for that I was trying to get the users from the database if I get that I will do that work otherwise simply redirect to somewhere but the problem I faced is you can check this route by consoling the log
Upvotes: 0
Reputation: 118
You have to specify the full url in the callbackURL section of the strategy:
for example: when if running the code locally on localhost:3000
with code like this:
passport.use(new googleStrategy({
clientID:keys.clientID,
clientSecret:keys.clientSecret,
callbackURL:'auth/google/callback'
},(accessToken,refreshToken, profile,done)=>{
console.log(accessToken);
console.log(refreshToken);
console.log(profile);
}
));
app.get('/auth',passport.authenticate('google',{
scope:['profile','email']
}));
app.get('/auth/google/callback',
passport.authenticate('google'));
The above code will surely throw a TokenError: Bad request. You have to pass the complete URl to have a final code like shown below:
passport.use(new googleStrategy({
clientID:keys.clientID,
clientSecret:keys.clientSecret,
callbackURL:'http://localhost:3000/auth/google/callback'
},(accessToken,refreshToken, profile,done)=>{
console.log(accessToken);
console.log(refreshToken);
console.log(profile);
}
));
app.get('/auth',passport.authenticate('google',{
scope:['profile','email']
}));
app.get('/auth/google/callback',
passport.authenticate('google'));
Upvotes: 9
Reputation: 1868
You can get help by putting some console.log inside your Oauth and Strategy under node modules, Specifically around the line on which you are getting error in logs.
E:\Programowanie\NodeJS\Hydronide\node_modules\passport-oauth2\lib\strategy.js
E:\Programowanie\NodeJS\Hydronide\node_modules\oauth\lib\oauth2.js
This will help you to get the root cause of parsing error . Seems like there is some problem with request/response data.
Upvotes: 2