Amanda Ferrari
Amanda Ferrari

Reputation: 946

What's the correct header to use when using API Key based authentication

I'm trying to create an API that uses API key based protection. The key is generated when a user is created, with a hook. Now I'm not sure what authorization schema to use with it. The avialable ones (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Authorization) don't seem correct. I have in my applications_controller:

# frozen_string_literal: true

class ApplicationController < ActionController::API
  include ActionController::HttpAuthentication::Token::ControllerMethods

  protected

  def authenticate
    authenticate_token || render_unauthorized
  end

  def authenticate_token
    authenticate_with_http_token do |token, options|
      @current_user = User.find_by_api_key(token)
    end
  end

  def render_unauthorized(realm = 'Application')
    self.headers['WWW-Authenticate'] = %(Token realm='#{realm}')
    render json: 'Bad credentials', status: :unauthorized
  end
end

But I know that this is not correct:

self.headers['WWW-Authenticate'] = %(Token realm='#{realm}')

There is no Token authorization schema. What should I use instead? I'm not finding much information about it.

I also know that Basic is not the correct type because it's not a user:password encoded in base64. Maybe X-Api-Key? I would like some help in the matter if possible :].

Upvotes: 0

Views: 671

Answers (1)

Amadan
Amadan

Reputation: 198324

You need HTTP_AUTHORIZATION header of the form Token token="####################", though you don't need to do this yourself. Use the code provided in the documentation:

authorization = ActionController::HttpAuthentication::Token.encode_credentials(users(:dhh).token)
get "/notes/1.xml", headers: { 'HTTP_AUTHORIZATION' => authorization }

Upvotes: 2

Related Questions