Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict Login with Google OAuth2.0 to Specific Whitelisted Domain Name on Ruby

EDIT: I changed how I'd like to do this I think I will use a MySQL table to whitelist the devise logins using google. The changed question is posted here: Restrict Login with Google OAuth2.0 and Devise to Specific Whitelist Table using Ruby

Alright so I am trying to get restricted authentication for my ruby on rails website using Devise and Omni-Auth2 and only google. Everything is working so far, but I only want emails coming from a certain domain to be accepted. I am open to anyway to do this.

I have done some googling but it seems some PHP users have a bit more local files than I do, maybe because of using the google API client locally? I'm not exactly sure, as I am quite new to coding in general and surprised I made it this far.

Here is an example: Google Oauth2.0 with Python: How do I limit access to a specific domain?

And here: Restrict Login Email with Google OAuth2.0 to Specific Domain Name

Both seem to use the "hd:domain" or something similar, but there seems to be issues with that plus I'm not sure how I would impliment it in my app.

Now for some more info, I am only using the gem devise and omniauth-google-oauth2 (https://github.com/zquestz/omniauth-google-oauth2) I feel like theres a way to do it with that gem but still not entirely sure. Any help would be appreciated if I can post any more info let me know.

My omniauth_callbacks_controller:

class User::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def google_oauth2
    # You need to implement the method below in your model (e.g. app/models/user.rb)
    @user = User.find_for_google_oauth2(request.env["omniauth.auth"], current_user)

    if @user.persisted?
      flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Google"
      sign_in_and_redirect @user, :event => :authentication
    else
      session["devise.google_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end
end
like image 788
Preston M Avatar asked Apr 25 '14 13:04

Preston M


1 Answers

I know this question is old but answering it just for reference. You need to change config/initializer/omniauth.rb and add "hd" to provider.

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :google_oauth2, ENV["google_client_id"], ENV["google_client_secret"],
           {
               hd: 'domain.com'
           }
end
like image 143
sadaf Avatar answered Oct 29 '22 15:10

sadaf