API authentication with a token in Rails

There are times when you’re building web applications and just the basics is enough for your initial needs. Take tonight when I needed a single API end point that was protected by a token.

Rather than go down the road of utilizing web tokens or another authentication method, I decided to use the authenticate_or_request_with_token method that rails provides.

What it does is it takes the token from the request and we can then use it to match against an existing record or environment variable in our application. For this scenario, I need just to do a check on an environment variable.

module Api
  class EventsController < ApplicationController
    before_action :authenticate

    def index
      # Do some action here


    def authenticate
      authenticate_or_request_with_http_token do |token, _options|
        token == ENV['API_TOKEN']