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?
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
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).