Repository navigation
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.
Scaffold the API route file and wire up the personal_access_tokens table:
./artisan install:api
./artisan migrateinstall: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.
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 |
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 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"])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.
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)
endfind_user/1:
- SHA-256 hashes the plain token
- Looks up the hash in ETS (or the database as fallback)
- Checks expiration; revokes and returns
nilif expired - Updates
last_used_at - Stores the token's abilities in the process dictionary for scope checks
- Returns the user struct
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)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.
# 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.
./artisan sanctum:prune-expiredRuns Laravex.Auth.Token.prune_expired/0, which:
- Issues a
DELETEonpersonal_access_tokens WHERE expires_at <= NOW() - Removes expired entries from the ETS cache
Schedule this command periodically in lib/laravex/console/schedule.ex.
-
Authentication — Session-based auth and the
authmiddleware - Authorization — Gate and Policy checks
-
Starter-Kits —
install:apicommand details
Laravex — Laravel-faithful application skeleton & runtime for Elixir.
GitHub
·
Docs
·
Limitations
·
Laravel Docs
Not affiliated with Laravel LLC or the Elixir core team. Built to feel like Laravel on the BEAM.
- Home
- Installation
- Configuration
- Directory-Structure
- Request-Lifecycle
- Service-Container
- Service-Providers
- Deployment
- Routing
- Middleware
- CSRF-Protection
- Controllers
- Requests
- Responses
- Views
- Blade-Templates
- Asset-Bundling
- Session
- Validation
- Error-Handling
- Logging
- Artisan-Console
- Broadcasting
- Cache
- Collections
- Events
- File-Storage
- Helpers
- HTTP-Client
- Localization
- Notifications
- Pipeline
- Queues
- Rate-Limiting
- Strings
- Task-Scheduling