Using auth_token from request headers instead from POST/PUT parameters with Rails 3 / devise

GeorgieF picture GeorgieF · Sep 13, 2011 · Viewed 19.6k times · Source

I need to use token based authentication in a Rails 3.1 API in conjunction with the most recent version of devise. No problem so far.

Now I do not want to append my :auth_token to the POST/PUT parameters on client side but send this token as a request header like HTTP_X_MYAPP_AUTH_TOKEN".

Can I convince devise from using that rather than a token from parameters? Is it possible to implement both, so that my API users can send the token via request header OR POST/PUT parameter?

Regards. Felix

Answer

Chris Conley picture Chris Conley · Sep 28, 2011

I had the same need and came up with this solution:

class YourController < ApplicationController
  prepend_before_filter :get_api_key
  before_filter :authenticate_user!

  private
  def get_api_key
    if api_key = params[:api_key].blank? && request.headers["X-API-KEY"]
      params[:api_key] = api_key
    end
  end
end

Note I have my devise Devise.token_authentication_key set to api_key.

config.token_authentication_key = :api_key