Passportjs认证使用谷歌应用程序的电子邮件id

passportjs authentication using google apps email id

本文关键字:电子邮件 id 应用程序 谷歌 认证 Passportjs      更新时间:2023-09-26

我正在尝试护照js与谷歌应用程序的电子邮件id。我可以使用gmail.com的电子邮件id进行身份验证。但是,如果电子邮件id是谷歌应用程序id (google.com/a/companyname.com),我如何进行身份验证?

这是我的代码

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);

你的代码缺少一些重要的部分:

...
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);
});
...

有了这些,我就可以用我的谷歌应用程序地址登录了。

EDIT:它只适用于Node 0.8,虽然Node 0.10给出了一个错误。我认为使用passport-google-oauth是一个更好的解决方案。为此,你必须在谷歌注册你的应用程序(在这里);注册后,您将获得可以使用的GOOGLE_CLIENT_ID和GOOGLE_CLIENT_SECRET代码。

我已经创建了一个方法来验证电子邮件域是否是我想要授权的:

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

这是我放入用户模型模型的方法,使用猫鼬模式模型

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

中的回调护照Google策略https://github.com/jaredhanson/passport-google-oauth

在您的passport.use回调中,您可以根据主电子邮件地址的域(或您正在检查的任何内容)执行额外的检查:

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