API keys
RailsFast is wired for the api_keys gem: self-serve API keys that belong to an organization, with a dashboard at /settings/api-keys for the people who manage it. It is opt-in, since v1.8.0: nothing runs until the gem is in your Gemfile. The template's docs/api-keys.md is the full reference.
Turn it on
# Gemfile: uncomment
gem "api_keys", "~> 0.8.0"
bundle install
bin/rails g api_keys:install --skip # --skip keeps the template's initializer
bin/rails db:migrate
Then set your own key prefix in config/initializers/api_keys.rb (config.token_prefix = "myapp_") before the first key is issued.
What is already wired
- Keys belong to the organization and act for all of it, never for one person.
- Only members whose role has
manage_settings(owner and admin by default) reach the dashboard. - A key is read only from
Authorization: Bearer <token>, never from a query parameter. - The gem's jobs run on the default queue.
Authenticate a request
class Api::V1::BaseController < ActionController::API
include ApiKeys::Controller
before_action :authenticate_api_key!
private
def current_organization = current_api_owner
end
With row-level security on, also name the key's organization for the request, after the authentication:
around_action { |_, action| Organizations.with_organization(current_api_owner, &action) }
authenticate_api_key!(scope: "projects.read") refuses a key that lacks the scope once the app has a scope policy: key types with a scope ceiling each, or default scopes. Without one, a key created without scopes may call everything. A key belongs to the organization, so it keeps working after the person who made it leaves: revoke it from the dashboard. To stop such keys automatically, run bin/rails g api_keys:add_created_by, create keys in your own code with created_by: current_user (the dashboard records no creator), and set config.trusted_key_check to refuse a key whose creator no longer manages the organization. Key types, environments, origin and IP restrictions and expiry are in the gem's README.