rails-api authentication by header's token

Anatoly picture Anatoly · Jun 13, 2012 · Viewed 11.2k times · Source

I'd like to work with rails-api gem special to create API-only application. To provide authentication mechanism I want to use built-in authenticate_or_request_with_http_token method described in Railscasts #352, but this method in missing here.

Does anybody have an experience with on rails-api gem?

P.S. I can see this approach, but is this production-ready?

Answer

Jon Rutherford picture Jon Rutherford · Jul 2, 2012

I am in the process of developing a service using the rails-api. We haven't deployed yet, but are nearing that time, and haven't had any issues in testing. You need to include any non-essential modules which you want to use, as rails-api is trimmed right down. I am using authenticate_or_request_with_http_token in ApplicationController like so:

include ActionController::HttpAuthentication::Token::ControllerMethods

def authenticate
  authenticate_or_request_with_http_token do |token, options|
    apiKey = ApiKey.where(auth_token: token).first
    @current_user = apiKey.user if apiKey
  end
end 

If you just want the token, there is a handy method token_and_options:

include ActionController::HttpAuthentication::Token

def current_user
  api_key = ApiKey.where(auth_token: token_and_options(request)).first
  User.find(api_key.user_id) if api_key
end