可以覆盖 sign_in url 中的approval_prompt,因此您可以将其设置为“强制”,从而使用户脱离catch-22,即使google_oauth2 设计配置已将其设置为“自动”(默认)。
诀窍是在 OmniauthCallbacksController 中传达这是所需要的。一种简单且不显眼的方法是简单地设置一个临时 cookie:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def google_oauth2
if user = User.find_for_google_oauth2(request.env["omniauth.auth"])
cookies.delete :google_oauth2_approval_prompt
flash[:notice] = I18n.t( "devise.omniauth_callbacks.success", kind: "Google")
sign_in_and_redirect user, event: :authentication
else
# we are not supporting self-service registration, so although
# user has authenticated at Google and given consent to the app,
# we are not going to allow the user in
cookies[:google_oauth2_approval_prompt] = "force"
flash[:error] = I18n.t( "devise.omniauth_callbacks.failure", kind: "Google", reason: "account not provisioned")
redirect_to root_url
end
end
end
然后在呈现谷歌登录的视图中,有条件地附加approval_prompt:
:ruby
extra_params = if approval_prompt = cookies[:google_oauth2_approval_prompt]
{approval_prompt: approval_prompt}
else
{}
end
= link_to "Sign-in with Google",
user_omniauth_authorize_path(:google_oauth2,extra_params)
因此,如果用户首先尝试使用应用程序决定不接受的 Google 帐户,则用户将有机会在尝试再次登录时切换帐户(因为它们将通过强制批准工作流程)。