Devise + Omniauth:当用户启用 SSO 时禁用电子邮件登录

问题描述 投票:0回答:2

我有一个使用电子邮件和密码进行正常 Devise 登录的网站。

然后我完成了添加 Omniauth / SSO 的教程:

https://github.com/heartcombo/devise/wiki/OmniAuth:-概述

现在 当某些用户选择使用“使用 Google 登录”时,我想禁用这些用户使用电子邮件和密码进行正常登录(以增强安全性)。

我怎样才能实现这一目标?

ruby-on-rails devise omniauth omniauth-google-oauth2
2个回答
2
投票

我面临着类似的情况,我不确定是否有一种干净的方法可以做到这一点。

我正在按照

krsyoung
在此线程上的建议进行操作 https://github.com/heartcombo/devise/issues/5502#issuecomment-1445633830

# user.rb

  def valid_password?(password)
    return false if sso_enabled?

    super
  end

额外:由于我必须禁止

unlock
-ing 帐户和
resetting passwords
,而且还必须通过显示默认设计消息来混淆验证消息,所以我必须覆盖更多设计方法

# also in user.rb

  def send_reset_password_instructions?
    email_login_enabled? # your logic can go here
  end

  def send_reset_password_instructions
    # still show the `send_paranoid_instructions` message
    # "If your email address exists in our database, 
    # you will receive a password recovery link at your email 
    # address in a few minutes."
    return unless send_reset_password_instructions?

    super
  end

  def send_unlock_instructions?
    email_login_enabled?  # your logic can go here
  end

  def send_unlock_instructions
    # Still shows the `send_paranoid_instructions`
    # "If your account exists, you will receive an email 
    # with instructions for how to unlock it in a few minutes."
    return unless send_unlock_instructions?

    super
  end

0
投票

active_for_authentication?
(您已经知道)方法用于控制设备是否允许用户登录。如果您为omniauth用户返回
false
,那么当用户尝试使用omniauth流程登录时,它也会禁用
omniauth
用户的登录。所以这不是一个选择。

选项1:

active_for_authentication?
不知道用户是否尝试使用密码或omniauth 登录。如果我们设法知道遵循哪个流程,那么当omniauth用户尝试使用密码登录时,我们可以返回
false

当用户尝试使用omniauth流程登录并在

active_for_authentication?

中检查它时,了解遵循哪个路径的一种方法是设置会话

在omniauth流程中:

session[:omniauth_login] = true

并在

active_for_authentication?

def active_for_authentication?
  super && (!omniauth_user? || session[:omniauth_login])
end

它将允许普通用户登录,阻止omniauth用户通过密码登录,并允许omniauth用户使用omniauth流(设置会话的地方)登录。登录后也重置会话。

选项2:

您可以覆盖

sessions_controller
并阻止启用omniauth的用户的访问。

class SessionsController < Devise::SessionsController
  def create
    #Allow login with password for all except omniauth users    
    #Define your own logic inside omniauth_user?

    if omniauth_user?(sign_in_params)                  
      redirect_to new_user_session_path, alert: "You can't login using password"
      return
    end

    super
  end
end
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.