Monday, April 26, 2010

Using Authlogic and single access token for API access

Bynarylogic's authlogic has gained much popularity for its out of the box solution to ruby on rails authentication. Yesterday, I was working on giving API access to my ruby on rails application so that other apps can use my RESTful services. The authenticated API access usually involves the following steps:
  1. API_KEY or a token to identify/authenticate an API call.
  2. Authentication of an API caller using the API_KEY.
Authlogic comes with in-built support for this. The following steps will do it for you:
#Make sure you have the single_access_token magic field in your user model.
t.string :single_access_token, :null => false
#You need to specify the request types that you want your API users to adhere to
class UserSession < Authlogic::Session::Base
single_access_allowed_request_types :any
end
or
single_access_allowed_request_types [:get, :post]
#The request from the API user should include the single access token of that user in params[:user_credentials]
http://<server>/api_accessible_controller/action?user_credentials=<single_access_token>&...
#The same param can be used for POST request as well
#You can change the user_credentials params to any custom param using the following:
class UserSession < Authlogic::Session::Base
#use param[:api_key] instead of params[:user_credentials]
params_key :api_key
single_access_allowed_request_types :any
end
#If you are using POST requests, you may need to disable request_from_forgery to allow API users bypass that requirement. The following will work.
class ApplicationController < ActionController::Base
helper :all
protect_from_forgery # See ActionController::RequestForgeryProtection for details
end
class APIAccessibleController < ApplicationController
protect_from_forgery :except=>:create
end
view raw gistfile1.rb hosted with ❤ by GitHub