Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails-api authentication by header's token

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?

like image 244
Anatoly Avatar asked Jun 13 '12 14:06

Anatoly


2 Answers

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
like image 189
Jon Rutherford Avatar answered Sep 19 '22 13:09

Jon Rutherford


From the README:

Basic, Digest and Token Authentication: Rails comes with out-of-the-box support for three kinds of HTTP authentication.

So, yes, this is production ready (it's still Rails after all). The example you linked to is the way to go (the trick is to include only what you need from Action Pack).

like image 34
Oscar Del Ben Avatar answered Sep 18 '22 13:09

Oscar Del Ben