Skip to content

API Tokens

David Ciulla edited this page Nov 7, 2026 · 1 revision

API Tokens

Laravex includes a Sanctum-inspired personal access token system via Laravex.Auth.Token. Tokens are issued per-user, carry named abilities, support expiration, and are stored in the personal_access_tokens table backed by an ETS in-process cache.

Installation

Scaffold the API route file and wire up the personal_access_tokens table:

./artisan install:api
./artisan migrate

install:api writes routes/api.ex, which registers a GET /api/user endpoint that authenticates via bearer token. The route is auto-registered on boot once the module is compiled.

The personal_access_tokens Table

Created by 0001_01_01_000003_create_personal_access_tokens_table.ex:

Column Type Notes
id INTEGER PK Auto-increment
tokenable_type TEXT e.g. "App.Models.User"
tokenable_id INTEGER User ID
name TEXT Human-readable label
token TEXT UNIQUE SHA-256 hash of the plain token
abilities TEXT JSON array or "*"
last_used_at TEXT ISO-8601, updated on each use
expires_at TEXT ISO-8601 or NULL
created_at / updated_at TEXT ISO-8601

Issuing Tokens

result = Laravex.Auth.Token.create(user, "mobile-app", ["posts:read", "posts:write"])

plain_token = result["plainTextToken"]
# => "abc123…" (40 hex chars — show to user once and discard)

The plain-text token is returned only once at creation time. Store only the SHA-256 hash in the database. Pass the plain token in HTTP requests via the Authorization header.

Abilities

Abilities are arbitrary strings. Use ["*"] to grant unrestricted access:

# Full access token
Laravex.Auth.Token.create(user, "admin-cli", ["*"])

# Scoped token
Laravex.Auth.Token.create(user, "read-only", ["posts:read", "users:read"])

Expiration

Pass :expires_at (a DateTime) or :expires_in (seconds):

# Expires in one hour
Laravex.Auth.Token.create(user, "temp", ["*"], expires_in: 3600)

# Expires at a specific time
Laravex.Auth.Token.create(user, "scheduled", ["*"],
  expires_at: ~U[2027-01-01 00:00:00Z])

Expired tokens are rejected automatically in find_user/1 and are cleaned up by prune_expired/0.

Authenticating Requests

Send the plain token as a Bearer token:

Authorization: Bearer <plain-token>

The Authenticate middleware (alias auth) resolves the user from the bearer token when no session user is present:

# Internally (Laravex.Http.Middleware.Authenticate.boot_user/1):
case Laravex.Http.Request.bearer_token(request) do
  nil   -> nil
  token -> Laravex.Auth.Token.find_user(token)
end

find_user/1:

  1. SHA-256 hashes the plain token
  2. Looks up the hash in ETS (or the database as fallback)
  3. Checks expiration; revokes and returns nil if expired
  4. Updates last_used_at
  5. Stores the token's abilities in the process dictionary for scope checks
  6. Returns the user struct

Checking Abilities

After authentication via bearer token, check abilities in controller logic or middleware:

# Check a single ability (uses process-local ability store)
Laravex.Auth.Token.token_can?("posts:read")   # => true | false

# Or check against an explicit list
Laravex.Auth.Token.can?(["posts:read", "*"], "posts:write")  # => true (wildcard)

ability and abilities Middleware

Protect routes by required token abilities:

# Require a single ability
Router.group([middleware: ["ability:posts:read"]], fn ->
  Router.get("/api/posts", &App.Http.Controllers.PostController.index/1)
end)

# Require all abilities in the list
Router.group([middleware: ["abilities:posts:read,posts:write"]], fn ->
  Router.post("/api/posts", &App.Http.Controllers.PostController.create/1)
end)
Alias Checks
ability:<name> Token has the named ability or "*"
abilities:<a>,<b> Token has all listed abilities or "*"

Returns 401 if unauthenticated, 403 if the token lacks the required ability.

Revoking Tokens

# Revoke by plain-text token
Laravex.Auth.Token.revoke(plain_token)

# Revoke by SHA-256 hash (64 lowercase hex chars)
Laravex.Auth.Token.revoke(hash)

Revocation removes the entry from both ETS and the personal_access_tokens table.

Pruning Expired Tokens

./artisan sanctum:prune-expired

Runs Laravex.Auth.Token.prune_expired/0, which:

  1. Issues a DELETE on personal_access_tokens WHERE expires_at <= NOW()
  2. Removes expired entries from the ETS cache

Schedule this command periodically in lib/laravex/console/schedule.ex.

See Also

Clone this wiki locally