Rails API Authentication

(1) No Authentication

class NoAuthenticationController < ApplicationController
  include ActionController::MimeResponds

  def my_api
    respond_to do |f|
      f.json {
        render json: { data: 'value' }.to_json, status: :ok
      }
      f.xml {
        render xml: { data: 'value' }.to_xml, status: :ok
      }
    end
  end
end

(2) Basic Authentication

class BasicAuthenticationController < NoAuthenticationController
  include ActionController::HttpAuthentication::Basic::ControllerMethods
  http_basic_authenticate_with name: 'username', password: 'password'
end

On the client side, you need to send this header:

Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=

(3) Token Authentication

class TokenAuthenticationController < NoAuthenticationController
  include ActionController::HttpAuthentication::Token::ControllerMethods
  before_action :authenticate, except: %i[authentication_api]

  # API to get token
  def authentication_api
    # Check username and password. Then issue a token.
    render json: { token: { value: '1234567890', expires: 2.hours.from_now.to_i } }.to_json, status: :ok
  end

  def authenticate
    authenticate_token || render_unauthorized
  end

  def authenticate_token
    authenticate_or_request_with_http_token do |token, _options|
      token == '1234567890' # Check the token
    end
  end

  def render_unauthorized
    headers['WWW-Authenticate'] = 'Token realm="Application"'
    head :unauthorized
  end
end

On the client side, you need to call the authentication api to get the token, then supply the token in the header:

Authorization: Token token=1234567890

(4) API Key Authentication

class ApiKeyAuthenticationController < NoAuthenticationController
  before_action :authenticate

  # api_key is supplied via query param
  def authenticate
    authenticate_token || render_unauthorized
  end

  def authenticate_token
    params.key?(:api_key) && params[:api_key] == '1823976172839823'
  end

  def render_unauthorized
    head :unauthorized
  end
end

On the client side, when you make a request, supply the api key in query param.

?api_key=1823976172839823

AI Summary
Chrome On-device AI 2024-10-04 22:51:08

Share Article