Skip to content

clearstackio/token_gate

Repository files navigation

TokenGate

Lightweight bearer token authentication for Rails APIs. No JWT, no OAuth — just simple, revocable API tokens hashed with SHA256 and stored in your database.

Built for machine-to-machine auth where you need API keys, not user sessions.

Installation

Add to your Gemfile:

gem "token_gate"

Run the install generator:

rails generate token_gate:install
rails db:migrate

Usage

Protect a controller

class Api::V1::JobsController < ApplicationController
  include TokenGate::Controller::Authenticatable

  # All actions now require: Authorization: Bearer <token>
  # Returns 401 JSON if missing/invalid/expired

  def run
    # current_api_token is available
    result = JobRunner.new(params[:name]).execute
    render json: result
  end
end

Protect specific actions only

class Api::V1::JobsController < ApplicationController
  include TokenGate::Controller::Authenticatable
  skip_before_action :authenticate_api_token!, only: [:status, :batch_status, :history]

  # POST /run requires token
  # GET /status, /batch_status, /history are open
end

Manage tokens via rake

# Create a token
rails token_gate:create NAME=esp-scheduler
# => Token: a3f8c9d1e2b4...  (shown once, save it!)

# Create with expiry
rails token_gate:create NAME=temp-debug EXPIRES_IN=24h

# List all tokens
rails token_gate:list

# Revoke a token
rails token_gate:revoke NAME=esp-scheduler

# Rotate (revoke + create new with same name)
rails token_gate:rotate NAME=esp-scheduler

Manage tokens programmatically

# Create
record, raw_token = TokenGate.create!(name: "my-service", expires_at: 30.days.from_now)

# Authenticate
token = TokenGate.authenticate(raw_token)  # returns ApiToken or nil
token = TokenGate.authenticate!(raw_token) # returns ApiToken or raises

# Revoke
TokenGate.revoke!("my-service")

# List
TokenGate.list  # => ActiveRecord relation

Use with curl

curl -X POST http://localhost:3000/api/v1/jobs/GBP03010/run \
  -H "Authorization: Bearer a3f8c9d1e2b4..."

How it works

  • Tokens are generated with SecureRandom.hex(32) (64-char hex string)
  • Only the SHA256 hash is stored in the database — raw tokens are never persisted
  • Authentication hashes the incoming bearer token and looks up the digest
  • Tokens can be revoked (soft-disable) or expired (time-based)
  • last_used_at is updated on every successful auth for auditing

EXPIRES_IN formats

Format Example Meaning
h 24h Hours
d 30d Days
w 4w Weeks
m 6m Months
y 1y Years

License

MIT License. See LICENSE for details.

About

Lightweight bearer token authentication for Rails APIs. No JWT, no OAuth — just simple, revocable API tokens hashed with SHA256 and stored in your database.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors