ruby 102 lines · 3 tabs

API key authentication for service-to-service calls

Alex Kumar Jan 2026
3 tabs
class CreateApiKeys < ActiveRecord::Migration[6.1]
  def change
    create_table :api_keys do |t|
      t.references :user, null: false, foreign_key: true
      t.string :name, null: false
      t.string :key_digest, null: false
      t.string :key_prefix, null: false
      t.text :scopes, array: true, default: []
      t.datetime :last_used_at
      t.datetime :expires_at
      t.timestamps
    end

    add_index :api_keys, :key_digest, unique: true
    add_index :api_keys, :key_prefix
  end
end
3 files · ruby Explain with highlit

While JWT works well for user authentication, service-to-service communication often uses simpler API key authentication. I generate cryptographically random API keys using SecureRandom.hex(32) and store them hashed in the database, similar to passwords. Clients send keys via Authorization: Bearer <key> or custom X-API-Key headers. Each key has associated scopes defining permissions, rate limits, and belongs to a specific account or service. I support key rotation by allowing multiple active keys per account. API keys are logged (partially, like key_abc...xyz) for audit purposes. For security, I require HTTPS for all API requests and implement rate limiting per key. Keys can be revoked immediately by deletion from the database.


Related snips

Share this code

Here's the card — post it anywhere.

API key authentication for service-to-service calls — share card
Link copied