Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 37 ยท Authentication and Security

API Authentication with Tokens

Build a token-protected JSON API in Rails: api-only mode, bearer tokens, hashed token storage, authenticate_with_http_token, rate limiting and CORS. Includes runnable Ruby stand-ins for token issuing and checking.

Browser users stay logged in with a session cookie. Mobile apps, scripts and other servers do not have a cookie jar, so they send a token with every request instead, usually in the Authorization header. Rails handles both worlds, and the same models and controllers can serve HTML pages and JSON.

The real Rails code in this lesson is read-only, because the site's Ruby runner has no gems and no database. The ideas that matter most, how tokens are made, stored and compared, are shown as runnable Ruby stand-ins and labelled as such. You already know sessions and cookies; here we replace the cookie with a header.

Rendering JSON

A controller can answer with JSON instead of HTML. render json: calls to_json on whatever you pass:

Ruby
class Api::PostsController < ApplicationController
  def index
    posts = Post.published.order(created_at: :desc).limit(20)
    render json: posts.as_json(only: %i[id title created_at])
  end

  def show
    post = Post.find(params[:id])
    render json: post
  rescue ActiveRecord::RecordNotFound
    render json: { error: "not found" }, status: :not_found
  end
end

Namespacing (Api::) and a route scope keep API controllers apart from page controllers:

Ruby
# config/routes.rb
namespace :api do
  resources :posts, only: %i[index show create]
end

If your app is only an API, generate it with rails new shop --api. That skips views, cookies and sessions, and ApplicationController inherits from ActionController::API, a lighter base class. Add rack-cors if a browser app on another origin needs to call it, and allow only the origins you trust.

What a token is

A token is a long random string that stands for a user. Whoever holds it is treated as that user, so it must be unguessable and secret, like a password:

  • Generate it with a secure random generator, never from the user id or the time.
  • Send it only over HTTPS.
  • Store only a digest (hash) of it in your database, like a password. If the table leaks, the tokens in it are useless.
  • Let users revoke tokens, and give them an expiry date when you can.

Because a token is already random with plenty of entropy, a fast hash such as SHA-256 is enough for storing it. That differs from passwords, which are short and guessable and need slow hashes.

Stand-in: issue and check tokens

Ruby Stand-in: issuing and verifying API tokens

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The table is keyed by the digest, so looking a token up is one indexed query and never compares secrets in Ruby code. When you do compare two secret strings yourself, use ActiveSupport::SecurityUtils.secure_compare (or OpenSSL.fixed_length_secure_compare) so the time taken does not leak how many characters matched.

Reading the Authorization header

HTTP clients send Authorization: Bearer <token>. Rails has a helper that parses it:

Ruby
class Api::BaseController < ActionController::API
  include ActionController::HttpAuthentication::Token::ControllerMethods

  before_action :authenticate!

  private

  def authenticate!
    authenticate_or_request_with_http_token do |token, _options|
      @current_user = ApiToken.authenticate(token)
    end
  end

  attr_reader :current_user
end

When the block returns a falsy value, Rails responds 401 Unauthorized with a WWW-Authenticate header. Every other API controller inherits from Api::BaseController and gets the check for free. Rails 7.1 and later also has generates_token_for, which creates signed, expiring tokens from a record without a table:

Ruby
class User < ApplicationRecord
  generates_token_for :api, expires_in: 1.hour do
    password_salt.last(10)   # token becomes invalid when the password changes
  end
end

token = user.generate_token_for(:api)
User.find_by_token_for(:api, token)

Stand-in: a tiny request pipeline

The next block imitates the controller filter and JSON response with plain Ruby so you can see the status codes. The "request" is a hash of headers.

Ruby Stand-in: bearer auth and status codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Note that the response only includes id and title. Never render a whole model blindly: columns such as password_digest or internal notes would leak. List the fields explicitly, or use a serializer (jbuilder, alba, or a plain as_json(only:)).

Protecting the API

  • Status codes tell clients what happened: 401 for no or bad credentials, 403 when authenticated but not allowed, 404 for missing, 422 for validation errors, 429 for too many requests.
  • Rate limiting: Rails 8 has rate_limit to: 10, within: 1.minute in a controller; earlier versions use the rack-attack gem.
  • CSRF: ActionController::API does not check CSRF tokens, which is correct for header-based tokens, because browsers do not attach an Authorization header on their own. Do not mix cookie sessions into an API without CSRF protection.
  • Scope data to the token's user (current_user.posts.find(...)), as shown in web security and authorization.
  • Version your API (/api/v1/...) so you can change it without breaking old clients.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why store only a digest of an API token?

    Like a password, a token is a credential. If only its hash is stored, someone who steals the table cannot present the tokens.
  2. 2. Which HTTP status should an API return when the token is missing or invalid?

    401 means the client has not proven who it is. 403 is for an identified user who lacks permission.
  3. 3. Why is a fast hash like SHA-256 acceptable for random API tokens but not for passwords?

    Passwords are short and guessable, so attackers try billions of guesses and need a slow hash. A 32-byte random token cannot be guessed.
  4. 4. What does rails new app --api change?

    API-only mode removes browser-oriented middleware and uses a lighter controller base class.

Summary

  • API clients send a token in the Authorization: Bearer header instead of a session cookie.
  • Generate tokens with SecureRandom, show them once, store only a digest, and support expiry and revocation.
  • authenticate_or_request_with_http_token parses the header and answers 401 for you; generates_token_for makes signed expiring tokens.
  • Render only the fields you intend to expose, use correct status codes, rate limit, and scope data to the current user.

Next: Testing Rails with Minitest