A developer notebook I should have started 10 years ago..

Simple token authentication for an API Rails application

How can I quickly set up a token authentication for my Rails API app?

module API
  class V1Controller < ApplicationController
    before_action :authenticate_user_with_token

    private 
    
    def authenticate_user_with_token
      authenticate_with_http_token do |token, _|
        @api_user ||= User.find_by(token: token)
      end
      return if @api_user

      render json: { message: "Bad credentials" }, status: :unauthorized
    end
  end
end

And now, inherit all your controllers from API::V1Controller.
Rails is expecting the token through the request headers as, "Authorization" => "Token <<token>>".

If your base controller inherits from ActionController::API, you must include the ` ActionController::HttpAuthentication::Token::ControllerMethods` module.

module API
  class V2Controller < ActionController::API
    include ActionController::HttpAuthentication::Token::ControllerMethods

    ...
  end
end

Resources:

  • https://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Basic.html
  • https://apidock.com/rails/v6.1.3.1/ActionController/HttpAuthentication/Token/ControllerMethods