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:migrateclass 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
endclass 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# 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# 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 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.