在 Rails 中,是否可以限制谁可以使用 api 使用 google 登录? [英] In Rails, is it possible to limit who can log in with google using the api?
问题描述
是否可以只允许某些谷歌账户登录?例如 myname@mycompany.com
是通过 google 托管的(它们实际上是 google 帐户).我只希望具有 @mycompany
的用户能够登录,这可能吗?你是用devise还是google api来做这个的?
Is it possible to only allow certain google accounts to log on? for example myname@mycompany.com
is host through google (they are actually google account). I want only user with the @mycompany
to be able log on is this possible?
do you do this with devise or google api?
谢谢:)
推荐答案
如果您使用的是 omniauth-google-oauth2,您可以通过在初始化期间为 hd
选项提供值来实现域限制.
If you are using omniauth-google-oauth2, you can accomplish domain restrictions using by providing a value for hd
option during initialization.
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"]
.
It's also possible to handle this in your controller which is handling the callback. You can deny users depending on values provided in 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
这篇关于在 Rails 中,是否可以限制谁可以使用 api 使用 google 登录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!