Laravel / PHP PHP Free

Laravel: Sanctum Token Abilities Check in Middleware

Check a Sanctum token's abilities in middleware, so only tokens with the right permission can reach a route.

25 lines · Updated Nov 26, 2026

Preview of Laravel: Sanctum Token Abilities Check in Middleware
laravel-sanctum-token-abilities-middleware.php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class CheckTokenAbility
{
    public function handle(Request $request, Closure $next, string $ability)
    {
        $user = $request->user();

        if (! $user || ! $user->currentAccessToken()
            || ! $user->tokenCan($ability)) {
            abort(403, 'This token does not have the required ability.');
        }

        return $next($request);
    }
}

// In routes/api.php — register the middleware as 'ability'
// Route::post('/posts', [PostController::class, 'store'])
//     ->middleware(['auth:sanctum', 'ability:posts:create']);

About this snippet

Laravel Sanctum lets you give each API token a set of abilities (also called scopes) — for example orders:read or orders:write. That way a token you hand to a reporting tool can read data but never change it. This snippet checks those abilities in middleware, so every protected route rejects tokens that do not have the right permission before your controller even runs.

How it works

  1. When you create a token, you pass the list of abilities it is allowed to use.
  2. On each request, Sanctum identifies the user from the token.
  3. The middleware checks whether the current token has the ability the route requires and returns a 403 Forbidden response if it does not.

How to use it

  • Create tokens with explicit abilities, e.g. $user->createToken('reporting', ['orders:read']).
  • Register the middleware and attach it to route groups, grouping read and write routes separately.
  • Test with two tokens — one with and one without the ability — to confirm the 403.

Best practices

  • Follow least privilege: give each integration only the abilities it truly needs.
  • Abilities say what a token may do; you still need policies to check which records the user owns.
  • Set an expiry for tokens and let users revoke them from their account page.

Common problems

  • Every request returns 401: the Authorization: Bearer header is missing or the token was revoked.
  • Abilities ignored for first-party SPA requests: cookie-based SPA sessions are treated as having all abilities — that is expected Sanctum behaviour.

FAQ

Sanctum or Passport? Sanctum is simpler and fits most first-party apps and mobile APIs. Passport is for full OAuth2 servers where third parties request access.

Related: Rate-limit API routes · OWASP Top 10 explained

How to install

Save as app/Http/Middleware/CheckTokenAbility.php and register it in bootstrap/app.php with an alias like ability. Then add it to routes with the ability name, for example ability:posts:create.

Share this snippet

See all
Chat with us