[google-api] Restrict Login Email with Google OAuth2.0 to Specific Domain Name


Answers

When defining your provider, pass in a hash at the end with the 'hd' parameter. You can read up on that here. https://developers.google.com/accounts/docs/OpenIDConnect#hd-param

E.g., for config/initializers/devise.rb

config.omniauth :google_oauth2, 'identifier', 'key', {hd: 'yourdomain.com'}
Question

I can't seem to find any documentation on how to restrict the login to my web application (which uses OAuth2.0 and Google APIs) to only accept authentication requests from users with an email on a specific domain name or set of domain names. I would like to whitelist as opposed to blacklist.

Does anyone have suggestions on how to do this, documentation on the officially accepted method of doing so, or an easy, secure work around?

For the record, I do not know any info about the user until they attempt to log in through Google's OAuth authentication. All I receive back is the basic user info and email.




Here's what I did using passport in node.js. profile is the user attempting to log in.

//passed, stringified email login
var emailString = String(profile.emails[0].value);
//the domain you want to whitelist
var yourDomain = '@google.com';
//check the x amount of characters including and after @ symbol of passed user login.
//This means '@google.com' must be the final set of characters in the attempted login 
var domain = emailString.substr(emailString.length - yourDomain.length);

//I send the user back to the login screen if domain does not match 
if (domain != yourDomain)
   return done(err);

Then just create logic to look for multiple domains instead of just one. I believe this method is secure because 1. the '@' symbol is not a valid character in the first or second part of an email address. I could not trick the function by creating an email address like mike@fake@google.com 2. In a traditional login system I could, but this email address could never exist in Google. If it's not a valid Google account, you can't login.




Related