Search code examples
node.jsexpressoauth-2.0passport.js

passport google oauth on localhost


I am quite new at using passport for authentication over node, hence the lot of code snippets

my server is configured as :

var router = require('./app/config/routes');
var googleStrategy = require('./app/config/passport');
var session = require("express-session");

var passport = require('passport');
app.use(session({secret : '<secret-key>'}));
app.use(passport.initialize());
app.use(passport.session());
googleStrategy(passport); 

my routes are configured as

module.exports = function(app, passport) {

    app.get('/auth/google', function() {
        passport.authenticate('google', {scope: ['profile', 'email']});
    });

    app.get('/auth/google/callback', function() {
        passport.authenticate('google', {
            successRedirect: '/profile',
            failureRedirect: '/fail'
        });
    });

    .... ALSO configured /profile and /fail
};

my passport is configured as

passport.serializeUser(function(user, callback){
        console.log('serializing user.');
        callback(null, user);
    });

    passport.deserializeUser(function(user, callback){
       console.log('deserialize user.');
       callback(null, user);
    });

    var processRequest = function(token, refreshToken, profile, callback){
        process.nextTick(function(){
           console.log('id : '+ profile.id);
           console.log('name :'+ profile.displayName);
           console.log('email :' + profile.emails);
           console.log('token : '+ token);
        });
    };

    passport.use(new GoogleStrategy({
        clientID: 'client ID',
        clientSecret : 'client SECRET',
        callbackURL : 'http://127.0.0.1:8080/auth/google/callback',
        realm : 'http://127.0.0.1:8080'
    }, processRequest));

Problem : on going to /auth/google , I never get a confirmation screen. What should be I looking at?

Update :

changing the routes to the configuration shown below made it work.

    app.get('/auth/google', 
        passport.authenticate('google', {scope: ['profile', 'email']})
    );

    app.get('/auth/google/callback', 
        passport.authenticate('google', {
            successRedirect: '/profile',
            failureRedirect: '/fail'
        })
    );

Solution

  • Currently OAUTH2 protocol for authentication and autherization is well supported by google.So Its better to use the same . Here is google's documentation on it .Use 'passport-google-oauth' module . Here is the implementation.This should be the app objects configuration , also see that oauth2strategy object is used from passport-google-oauth module , also check out the scopes in the app.get route registration .

    var googleStrategy = require('passport-google-oauth').OAuth2Strategy;
      app.configure(function() {
    
        app.set('views',  './views');
        app.set('view engine', 'jade');
        app.use(express.favicon());
        app.use(express.logger('dev'));
        app.use(express.cookieParser());
        app.use(express.bodyParser());
        app.use(express.session({secret:'MySecret'}));
        app.use(passport.initialize());
        app.use(passport.session());
        app.use(express.methodOverride());
        app.use(app.router);
        app.use(express.static('./public'));
    });
    
    app.get('/auth/google', select.passport.authenticate('google',{scope: 'https://www.googleapis.com/auth/plus.me https://www.google.com/m8/feeds https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile'}));
    
    app.get('/auth/google/callback', function() {
        passport.authenticate('google', {
            successRedirect: '/profile',
            failureRedirect: '/fail'
        });
    });
    app.get('/logout', function (req, res) {
            req.logOut();
            res.redirect('/');
        });
    

    But before creating a new strategy go to googles developer console and get clientID and secret . Here are the steps

    1. go this link and create project , here is the snapshot of the same enter image description here
    2. give a new project name and ID , here is the snapshot enter image description here
    3. It'll roughly take a minute to create your new project , once your new project is created it'll redirect you to the application configuration of your app . In the redirected page select APIS AND AUTH -> API's , In the API's page enable the GOogle+ API , here is the snapshot of it enter image description here
    4. then go to credentials(below APIs), then click on Create New Client Id , and register the domains and callback for your app(configure the domain to be localhost ) , here is its snapshot !enter image description here 5.Then u'll get your new ID and secret . Use them to create the new Strategy

      passport.use(new googleStrategy({
          clientID: '<TheNewclientID>',
          clientSecret: '<The New Secret>',
      
          callbackURL: "http://locahost:8080/auth/google/callback"
      },
      function (accessToken, refreshToken, profile, done) {
          console.log(profile); //profile contains all the personal data returned 
          done(null, profile)
      }
      ));
      

    6.now serialize and deserialize

    passport.serializeUser(function(user, callback){
            console.log('serializing user.');
            callback(null, user.id);
        });
    
    passport.deserializeUser(function(user, callback){
           console.log('deserialize user.');
           callback(null, user.id);
        });
    

    run the server and go to localhost:8080/auth/google (dont use 127.0.0.1:8080 instead of locahost ) .This should be getting it working :)

    [Other useful links: Check out the first comment by kvcrawford on the repo of the module in this page Passport-google is another popular module which is use to provide login using google , its kind of outdated now , here is the link with respect to its recent issues ]