简体   繁体   中英

passportjs authentication using google apps email id

I am trying passport js with google app email id. I am able to authenticate using gmail.com email id. But how can I authenticate if the email id is a google app id (google.com/a/companyname.com).

This is my code

var express = require('express');
var app = express();
var passport = require('passport');
var GoogleStrategy = require('passport-google').Strategy;

passport.use(new GoogleStrategy({
    returnURL: 'http://10.3.0.52:3000/auth/google/return',
    realm: 'http://10.3.0.52:3000/'
},
function(identifier, profile, done) {
    User.findOrCreate({
        openId: identifier
    }, function(err, user) {
        done(err, user);
    });
}
));

app.get('/auth/google', passport.authenticate('google'));

app.get('/auth/google/return', 
    passport.authenticate('google', {
        successRedirect: '/',
        failureRedirect: '/login'
    }));

app.get('/', function(req, res){
    res.writeHead(200);

    res.end("connected");

});

app.listen(process.env.PORT || 3000);

Your code is missing some vital parts:

...
passport.use(...); // this you have

// these are required as well.
app.use(passport.initialize());
app.use(passport.session());

// please read docs for the following two calls
passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(obj, done) {
  done(null, obj);
});
...

With those in place, I can log in using my Google App address just fine.

EDIT: it only works with Node 0.8 though, Node 0.10 gives an error. I think using passport-google-oauth is a better solution anyway. For that, you have to register your application with Google ( here ); after registration, you'll be supplied both the GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET codes which you can use.

I have created a method that verifies if the email domain is the one i want to authorize:

UserSchema.method('checkFordomain', function(value) {
    var parts = value.split('@');
    return (parts[1] == 'companyname.com');
});

this is method I put in the model of the user model, using mongoose schema models

if (!user.checkForMMdomain(profile.emails[0].value)) {
    return done();
}

in the callback of the passport google strategy https://github.com/jaredhanson/passport-google-oauth

In your passport.use callback you can perform additional checking based on the domain of the primary email address (or whatever you are checking):

if (profile.emails[0].split('@')[1] !== authorizedDomain) {
    return done(null, false);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM