【问题标题】:Validate API with Authlogic使用 Authlogic 验证 API
【发布时间】:2009-11-06 23:59:01
【问题描述】:

我在我的应用程序中使用 Authlogic 进行身份验证,使用标准的 User 和 UserSession 模型。我正在将 API 构建到我的应用程序中,并且我想使用单个访问令牌对 API 访问进行身份验证。在我的应用程序中,每个用户 belongs_to 一个公司,其中 has_many 用户。该 API 用于访问属于公司的资源,因此我想为整个公司使用一个访问令牌。

我最初的想法是向 Company 添加一个仅有权访问 API 的虚拟用户,然后公司将使用其单一访问令牌来授予对 API 的访问权限。看来我不能使用 AuthLogic 将用户的电子邮件和密码设置为空白,所以这不会成功。我的下一个想法是也许我可以将acts_as_authentic 添加到公司本身,但我不确定这会如何工作。

我真的很想为解决方案使用 Authlogic,因为它与我的 ACL 很好地集成在一起,并且似乎具有我正在寻找的大部分内置功能。

是否可以有两个act_as_authentic 的模型?有没有一种我没有想到的更简单的方法,内置在 Authlogic 中?有没有办法可以使用虚拟用户作为他们的 API 密钥?我应该怎么做?

【问题讨论】:

    标签: ruby-on-rails authentication authlogic


    【解决方案1】:

    我这样做的方法是:

    class Something
      acts_as_authentic do |m|
        # API keys are auto generated (See +regenerate_api_key+.)
        # The password is not used for authentication (its just an api_key lookup), so a dummy field is used
        m.login_field = :api_key
        m.validate_login_field = false
        m.validate_email_field = false
        m.crypted_password_field = :api_key_hash
        m.require_password_confirmation = false
        m.validate_password_field = false
        m.crypto_provider = ApiKeyCrypto
      end
    end
    
    class ApiKeyCrypto
      def self.encrypt(*tokens)
        'X'
      end
    
      def self.matches?(crypted, *tokens)
        crypted == 'X'
      end
    end
    
    #application_controller.rb
    def current_session
      return @current_session if defined?(@current_session)
      ...
        format.any(*api_formats) do
          @current_session = SomethingSession.find
        end
      end
      @current_session
    end
    def api_formats
      [:xml, :json]
    end
    

    这非常适合 ActiveResource 仅供参考。

    【讨论】:

      【解决方案2】:

      当然,您可以有两个模型acts_as_authentic。使用最少的 Authlogic db 字段设置 Company,并使用它的 single_access_token 进行 API 访问。请注意,您的 API 不会知道哪个 User 正在使用系统,而只会知道 Company

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-11
        • 1970-01-01
        相关资源
        最近更新 更多