Adding API Header Authentication when using Authlogic

Donnerstag, 03. März 2016, 15:13 Uhr | roberto@vasquez-angel.de |

A simple way to add Header Authentication to Authlogic, is to use a before_action filter to extract the authentication information from the header and inject it to the params hash. So you can use the default single access token.

class BackendController < ApplicationController
  before_action :extract_authentication_from_header, if: -> { request.headers['Authorization'].present? }
  before_action :authenticate_user!

  private

  def single_access_allowed?
    true
  end

  # Extract authentication from request headers and inject it into params.
  # Accepted headers example:
  # 
  # Authorization: Token token="<SINGLE_ACCESS_TOKEM>"
  # 
  def extract_authentication_from_header
    authlogic_params_key = :user_api_key
    raw_header = request.headers['Authorization']
    auth_token = raw_header.split("=\"").last[0..-2]
    params[authlogic_params_key] = auth_token
  end
end

The structure of the header is very losely based on this document: https://tools.ietf.org/html/draft-hammer-http-token-auth-01#section-5.1