Skip to content

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

classApi::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: resultendend

Protect specific actions only

classApi::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

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

# 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 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

FormatExampleMeaning
h24hHours
d30dDays
w4wWeeks
m6mMonths
y1yYears

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

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages