【问题标题】:Rails - How to authorise user with third party apiRails - 如何使用第三方 api 授权用户
【发布时间】:2019-04-05 14:36:59
【问题描述】:

我正在我的 rails 应用程序中设置一些身份验证。唯一的事情是我想根据用户的凭据使用另一个 API 登录。

应用程序必须向 API 发送带有用户名和密码的 POST 请求,如果请求成功,则用户授权。

我在尝试使用设计来执行此操作时遇到了麻烦,我只是在寻找你们的提示以实现此操作。

谢谢!

【问题讨论】:

    标签: rest ruby-on-rails-4 devise


    【解决方案1】:

    Devise 允许您为身份验证定义自定义策略。因此,您可以创建一个新策略来处理它。数据库身份验证是 Devise 已经定义的策略之一。可以查看来源here

    您的策略的粗略想法可能会像这样。 在config/initializers/external_authenticatable.rb 创建一个文件并定义策略

        require 'devise/strategies/database_authenticatable'
    
        module Devise
          module Strategies
              class ExternalAuthenticatable < DatabaseAuthenticatable
                def authenticate!
                  resource  = password.present? && mapping.to.find_for_database_authentication(authentication_hash)
    
                  if validate(resource){ valid_credentials?(resource) }
                    remember_me(resource)
                    resource.after_database_authentication
                    success!(resource)
                  end
    
                  fail(:not_found_in_database) unless resource
                end
    
                def valid_credentials?(resource)
                  request_params = { email: resource.email, password: password }
                  # Make your post request here and return true false using authentication_hash
                end
              end
          end
        end
    
    

    现在我们需要通知设计我们想在任何其他默认值之前先使用此策略。这可以通过编辑/config/initializers/devise.rb来完成

    config.warden do |manager|
      manager.strategies.add(:external, Devise::Strategies::ExternalAuthenticatable) 
      manager.default_strategies(:scope => :user).unshift :external 
    end
    

    重启你的 Rails 应用程序就完成了。

    【讨论】:

      猜你喜欢
      • 2013-05-03
      • 2018-06-03
      • 1970-01-01
      • 2019-05-17
      • 1970-01-01
      • 2022-11-10
      • 2022-10-16
      • 1970-01-01
      • 2022-01-16
      相关资源
      最近更新 更多