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.
Add to your Gemfile:
gem"token_gate"Run the install generator:
rails generate token_gate:install
rails db:migrateclassApi::V1::JobsController < ApplicationControllerincludeTokenGate::Controller::Authenticatable# All actions now require: Authorization: Bearer <token># Returns 401 JSON if missing/invalid/expireddefrun# current_api_token is availableresult=JobRunner.new(params[:name]).executerenderjson: resultendendclassApi::V1::JobsController < ApplicationControllerincludeTokenGate::Controller::Authenticatableskip_before_action:authenticate_api_token!,only: [:status,:batch_status,:history]# POST /run requires token# GET /status, /batch_status, /history are openend# 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# Createrecord,raw_token=TokenGate.create!(name: "my-service",expires_at: 30.days.from_now)# Authenticatetoken=TokenGate.authenticate(raw_token)# returns ApiToken or niltoken=TokenGate.authenticate!(raw_token)# returns ApiToken or raises# RevokeTokenGate.revoke!("my-service")# ListTokenGate.list# => ActiveRecord relationcurl -X POST http://localhost:3000/api/v1/jobs/GBP03010/run \
-H "Authorization: Bearer a3f8c9d1e2b4..."- 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_atis updated on every successful auth for auditing
| Format | Example | Meaning |
|---|---|---|
h | 24h | Hours |
d | 30d | Days |
w | 4w | Weeks |
m | 6m | Months |
y | 1y | Years |
MIT License. See LICENSE for details.