Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 38 ยท Authentication and Security

API Tokens and Session Authentication

Authenticate API clients in Phoenix: signed tokens with Phoenix.Token, database-backed API tokens, a bearer-token plug, expiry, revocation and rate limiting.

Browser users log in with a form and a session cookie. Mobile apps, scripts and other servers cannot use that flow; they send a token with each request, usually in an Authorization: Bearer ... header. Phoenix gives you the building blocks: Phoenix.Token for signed values, plain database rows for revocable tokens, and a plug to check them.

Phoenix code is read-only on this site. The runnable editors rebuild the key ideas, signing, verifying and expiry, with Node's crypto module.

Two kinds of token

Signed (stateless) Stored (database)
Example Phoenix.Token.sign/4 a random string in an api_tokens table
Server keeps state? No Yes, a row per token
Revoke one token Hard (wait for expiry) Delete the row
Lookup cost CPU only One query
Best for Short-lived links, channel auth Long-lived API keys

mix phx.gen.auth (see the auth overview) already stores session tokens in the database, hashed, and the same pattern works for API keys.

Phoenix.Token: signed, expiring values

Phoenix.Token signs data with your endpoint's secret_key_base. Anyone can read the payload (it is encoded, not encrypted), but nobody can change it without the key.

ELIXIR
# create
token = Phoenix.Token.sign(MyAppWeb.Endpoint, "user auth", user.id)

# verify, rejecting tokens older than one day
case Phoenix.Token.verify(MyAppWeb.Endpoint, "user auth", token, max_age: 86_400) do
  {:ok, user_id} -> ...
  {:error, :expired} -> ...
  {:error, :invalid} -> ...
end

The second argument is a salt: a purpose label. A token signed for "user auth" fails to verify as "password reset", so one kind of token can never be replayed as another. This is the same idea channels use to authenticate a socket: the page embeds a token, and connect/3 verifies it.

Database-backed API tokens

For API keys that users create and revoke, store a hash, never the raw token:

ELIXIR
def create_api_token(user) do
  raw = :crypto.strong_rand_bytes(32) |> Base.url_encode64(padding: false)
  hash = :crypto.hash(:sha256, raw)

  Repo.insert!(%ApiToken{user_id: user.id, token_hash: hash, expires_at: days_from_now(30)})
  raw   # shown to the user exactly once
end

def get_user_by_api_token(raw) do
  hash = :crypto.hash(:sha256, raw)

  from(t in ApiToken,
    join: u in assoc(t, :user),
    where: t.token_hash == ^hash and t.expires_at > ^DateTime.utc_now(),
    select: u
  )
  |> Repo.one()
end

Why hash? If the table leaks, an attacker gets hashes, not working tokens. A fast hash like SHA-256 is fine here because the raw value is 256 random bits, unlike a human password that needs a slow hash such as bcrypt. Revoking is Repo.delete/1.

The bearer plug

Put authentication in a plug in the :api pipeline:

ELIXIR
defmodule MyAppWeb.Plugs.ApiAuth do
  import Plug.Conn
  import Phoenix.Controller

  def init(opts), do: opts

  def call(conn, _opts) do
    with ["Bearer " <> raw] <- get_req_header(conn, "authorization"),
         %User{} = user <- Accounts.get_user_by_api_token(raw) do
      assign(conn, :current_user, user)
    else
      _ ->
        conn
        |> put_status(:unauthorized)
        |> put_resp_header("www-authenticate", ~s(Bearer realm="api"))
        |> json(%{error: "unauthorized"})
        |> halt()
    end
  end
end

halt/1 is essential: without it the request continues into the controller. The router wires it up once (see router and pipelines):

ELIXIR
pipeline :api_auth do
  plug :accepts, ["json"]
  plug MyAppWeb.Plugs.ApiAuth
end

scope "/api", MyAppWeb do
  pipe_through :api_auth
  resources "/notes", NoteController, except: [:new, :edit]
end

Good habits

  • Always HTTPS. A bearer token is a password in a header; anyone who sees it can use it.
  • Short lifetimes plus refresh, or per-key scopes (read-only vs read-write; see authorization).
  • Do not log tokens. Phoenix filters password params by default; add your own filter for authorization headers if you log them.
  • Compare in constant time when checking secrets by hand, with Plug.Crypto.secure_compare/2.
  • Rate limit token endpoints to slow guessing and abuse.

Runnable models

First, a signed token with a salt and expiry, built on HMAC. It mirrors how Phoenix.Token behaves: tampering, a wrong salt and age are all rejected.

Node.js Signed tokens with salt and max_age (stand-in)

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 node:readline or process.stdin), it gets the next line from this box.

Second, the stored-token pattern: random token, only a hash stored, one-time display, lookup, and revocation.

Node.js Hashed, revocable API tokens (stand-in)

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 node:readline or process.stdin), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the purpose of the salt argument in Phoenix.Token.sign/4?

    A token signed for one salt fails verification under another, so a reset token cannot act as a login token.
  2. 2. Why store a hash of an API token instead of the token?

    Only the user holds the raw value. The server compares hashes.
  3. 3. What must an authentication plug do after sending a 401 response?

    Without halt/1 the pipeline keeps running and the controller would still execute.
  4. 4. Which is easiest to revoke immediately?

    Deleting the row ends access at once. A stateless signed token stays valid until it expires.

Summary

  • Signed tokens (Phoenix.Token) are stateless and expire; stored tokens are revocable.
  • Store only a hash of API tokens and show the raw value once.
  • A bearer-token plug in the :api pipeline authenticates, assigns the user and halts on failure.
  • Use HTTPS, short lifetimes, scopes, constant-time comparison and rate limits.

Next: Testing Controllers and Contexts