在Rails中,是否可以限制谁可以使用API​​登录谷歌?

是否可以仅允许某些Google帐户登录? 例如myname@mycompany.com是通过谷歌主机(他们实际上是谷歌帐户)。 我希望只有@mycompany用户才能登录这可能吗? 你用devise或google api做到这一点吗?

谢谢 :)

如果您使用的是omn​​iauth-google-oauth2 ,则可以通过在初始化期间为hd选项提供值来完成域限制。

 Rails.application.config.middleware.use OmniAuth::Builder do provider :google_oauth2, ENV['GOOGLE_CLIENT_ID'], ENV['GOOGLE_CLIENT_SECRET'], { scope: 'email, profile', hd: 'mycompany.com' } end 

也可以在处理回调的控制器中处理这个问题。 您可以根据request.env["omniauth.auth"]提供的值拒绝用户。

 class OmniauthCallbacksController < Devise::OmniauthCallbacksController def google_oauth2 auth_details = request.env["omniauth.auth"] if auth_details.info['email'].split("@")[1] == "yourdomain.com" # do all the bits that come naturally in the callback controller user = User.from_omniauth(request.env["omniauth.auth"]) if user.persisted? flash.notice = "Signed in Through Google!" sign_in_and_redirect user else session["devise.user_attributes"] = user.attributes flash.notice = "You are almost Done! Please provide a password to finish setting up your account" redirect_to new_user_registration_url end else # This is where you turn away the poor souls who do not match your domain render :text => "We're sorry, at this time we do not allow access to our app." end end end