开发者

Validate API with Authlogic

开发者 https://www.devze.com 2022-12-10 06:35 出处:网络
I\'m using Authlogic for authentication in my app, using the standard User and UserSession models.I\'m building an API into my app, and I want to authenticate API access with a single access token.In

I'm using Authlogic for authentication in my app, using the standard User and UserSession models. I'm building an API into my app, and I want to authenticate API access with a single access token. In my app, every User belongs_to a Company, which has_many users. The API is for access to resources belonging to the company, so I'd like to use one single access token for the whole company.

My initial thought was to add a dummy user to Company that only has permission to access the API, whose single access token the company would then use to grant access to the API. It doesn't appear that I can set a user's e-mail and password blank with AuthLogic, so this isn't panning out. My next thought was perhaps I could add acts_as_authentic to the company itself, but I'm not sure how this would work.

I really want to use Authlogic for the solution because it integrates nicely with my ACL, and appears to have the functionallity I'm looking for mostly built in.

Is it possible to have two models that act_as_authentic? Is there an easier way that I'm not thinking of, built into 开发者_JAVA百科Authlogic? Is there a way I can use a dummy user for their API key? Which way should I do this?


The way I do this is:

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

This works great for ActiveResource FYI.


Sure, you can have two models acts_as_authentic. Set up the Company with the minimum Authlogic db fields , and use it's single_access_token for API access. Note that your API will not know which User is using the system, just the Company.

0

精彩评论

暂无评论...
验证码 换一张
取 消