使用带有Google身份validation的节点护照来限制login到特定的域

我正在实施Google Auth上的一项内部服务。 这是一个带有Node后端的JS客户端应用程序。 我select使用Passport.js和Passport-google-oauth策略的Node模块。

我已经成功地工作,但有一件事仍然让我困惑。 我想确保我的应用程序只允许公司员工login。 据了解, 根据官方文档 ,您可以使用名为“hd”的参数来限制域的login。

首先,您在Passport.js的上下文中发送该参数的位置? 我只是不明白在哪里放在代码中。 如果有帮助,我一直以来都是按照passport-google-oauth提供的例子 。

其次,从理论上讲,这一切是如何工作的? 它在Google方面,他们拒绝任何人试图访问我们公司以外的域名的应用程序。 还是在我身边,我需要检查用户login的域名是什么?

这是一个例子:

// first make sure you have access to the proper scope on your login route app.get("/login", passport.authenticate("google", { scope: ["profile", "email"] }); // set up your Google OAuth strategy elsewhere... passport.use(new GoogleStrategy({ clientID: "something", clientSecret: "something", callbackURL: "/something" }, function(token, refreshToken, profile, done){ if(profile._json.hd === "yourdomain.com"){ // find or create user in database, etc User.find({ id: profile.id }).done(done); }else{ // fail done(new Error("Invalid host domain")); } }); 

对于这个好的方法,这里是一个完整的“profile”variables的variables。

 { provider: 'google', id: '12345678987654321', displayName: 'Don Draper', name: { familyName: 'Whitman', givenName: 'Richard' }, emails: [ { value: 'don@scdp.com' } ], _raw: 'a bunch of stringified json', _json: { id: '123456789', email: 'something@something.com', verified_email: true, name: 'Don Draper', given_name: 'Don', family_name: 'Draper', link: 'https://plus.google.com/123456789', picture: 'https://lh3.googleusercontent.com/XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/123456789/photo.jpg', gender: 'male', locale: 'en', hd: 'yourdomain.com' } } 

这里有一些详细的教程,应该回答你所有这些背后的理论问题。 你会想要两者的一些组合。

  1. 本地authentication和基本设置
  2. Google身份validation

我build议一个2步的方法来做到这一点。 如果这是过度复杂的话,会很乐意听到反馈。

1)帮助您的用户select正确的帐户

 passport.authenticate('google', { // Only show accounts that match the hosted domain. hd: 'example.com', // Ensure the user can always select an account when sent to Google. prompt: 'select_account', scope: [ 'https://www.googleapis.com/auth/plus.login', 'https://www.googleapis.com/auth/plus.profile.emails.read' ] })(req, res, next); 

2)validation他们的个人资料

当用户被发送到accounts.google.com进行身份validation时,URL中有一个简单的hd=example.com查询参数。 您可以删除这个账户并且用任何账户进行身份validation(Passport将成功validationOauth代码,而不pipe所选账户的域名是什么),所以它只能被视为最终用户的糖,而不是服务器的安全。

当Passportparsingauthentication时,只需按照aembke的回答检查托pipe域:

 passport.use(new google_strategy({ clientID: ... clientSecret: ... callbackURL: ... }, function(token, tokenSecret, profile, done) { if (profile._json.domain !== 'example.com') { done(new Error("Wrong domain!")); } else { done(null, profile); } }));