Skip to content

5. Authentication and scopes ​

Right now anyone who can reach the API can read every order and place new ones, as step 3 warned. In this step you say what each endpoint needs, give each program only the access it needs, and see how people signing in to the web app fit in.

Two questions decide whether a request may go ahead:

  1. Who is calling? This is authentication. Programs send an API key, as you did in step 2. People using your web app sign in with their email and password, and get a token. Both are sent the same way: Authorization: Bearer ….
  2. What may they do? Each key and token has scopes, permissions such as orders:read. Each endpoint says which scope it needs.

Say which scope each endpoint needs ​

Add #[RequiresScope] to the controller's methods. The first time a scope is used, it also says what the scope is for, which the API reference shows:

diff
 use App\Models\Order;
+use FusionStack\Laravel\Auth\RequiresScope;
 use FusionStack\Laravel\OpenApi\Endpoint;
 use Illuminate\Http\Resources\Json\AnonymousResourceCollection;

 final class OrderController
 {
+    #[RequiresScope('orders:read', 'Read orders.')]
     #[Endpoint('List orders', 'Orders, newest first.')]
     public function index(OrderQuery $query): AnonymousResourceCollection
     {
         return OrderResource::collection($query->paginate());
     }

+    #[RequiresScope('orders:read')]
     #[Endpoint('Get an order')]
     public function show(OrderQuery $query, string $order): OrderResource
     {
         return new OrderResource($query->find($order));
     }

+    #[RequiresScope('orders:write', 'Place orders.')]
     #[Endpoint('Place an order', 'New orders are pending until they are paid.')]

An endpoint that needs a scope also needs a key or token, so ask again without one:

sh
curl localhost:8000/v1/orders
json
{
  "errors": [
    {
      "status": "401",
      "code": "unauthenticated",
      "title": "Unauthorized",
      "detail": "Authenticate to use this endpoint.",
      "meta": { "request_id": "req_01m8rgk2c5vbn3x8q7w4e6t9ya" }
    }
  ]
}

Give a program only what it needs ​

Suppose a reporting tool reads your orders. It never places any, so give its key only orders:read:

sh
php artisan api:key:create "Reporting" --scope=orders:read
text
   INFO  Created API key 2. Copy it now: it is not stored and cannot be shown again.

  fs_live_…

  Scopes ......................................................... orders:read

Keep it in another variable, next to the KEY from step 2:

sh
export REPORTING_KEY=fs_live_…

It can read orders. Here, the newest order's status:

sh
curl -g "localhost:8000/v1/orders?fields[orders]=status&page[size]=1" -H "Authorization: Bearer $REPORTING_KEY"
json
{
  "data": [{ "id": "1", "type": "orders", "attributes": { "status": "pending" } }],
  "links": { "first": "http://localhost:8000/v1/orders?…", "prev": null, "next": "http://localhost:8000/v1/orders?…" },
  "meta": { "page": { "size": 1 } }
}

But it cannot place one:

sh
curl localhost:8000/v1/orders -H "Authorization: Bearer $REPORTING_KEY" -H "Content-Type: application/vnd.api+json" \
  -d '{"data":{"type":"orders","attributes":{"total_cents":2500,"currency":"GBP"},"relationships":{"team":{"data":{"type":"teams","id":"1"}}}}}'
json
{
  "errors": [
    {
      "status": "403",
      "code": "insufficient_scope",
      "title": "Insufficient scope",
      "detail": "This request needs the [orders:write] scope.",
      "meta": { "required_scope": "orders:write", "request_id": "req_01m8rgm7d1q2w3e4r5t6y7u8i9" }
    }
  ]
}

401 means "I do not know who you are", and 403 "I know, and you may not". meta.required_scope tells the developer of the reporting tool exactly what to ask you for.

If the key leaks, whoever has it can only read orders. Giving each program its own key with the fewest scopes it needs limits the damage, and lets you revoke one key without breaking the others.

Your own key from step 2 has every scope, *, so it can still place orders:

sh
curl localhost:8000/v1/orders -H "Authorization: Bearer $KEY" -H "Content-Type: application/vnd.api+json" \
  -d '{"data":{"type":"orders","attributes":{"total_cents":2500,"currency":"GBP"},"relationships":{"team":{"data":{"type":"teams","id":"1"}}}}}'
json
{
  "data": {
    "id": "8",
    "type": "orders",
    "attributes": { "status": "pending", "total_cents": 2500, "currency": "GBP", "created_at": "2026-12-01T10:30:12.000000Z" }
  }
}

People: sign-in tokens ​

API keys are for programs, created by you. People using your web app sign in instead: the app sends their email and password to POST /v1/tokens, and gets a token back. This is what the sign-in page of the web app from step 2 does. Try it yourself:

sh
curl localhost:8000/v1/tokens -H "Content-Type: application/vnd.api+json" \
  -d '{"data":{"type":"tokens","attributes":{"email":"test@example.com","password":"password","name":"curl"}}}'
json
{
  "data": {
    "id": "…",
    "type": "tokens",
    "attributes": {
      "name": "curl",
      "abilities": ["*"],
      "plain_text_token": "…",
      "created_at": "2026-12-01T10:30:14.000000Z"
    }
  }
}

plain_text_token is sent like a key, and abilities are its scopes. Without scopes in the request, a token has every scope: it acts for the person, and can do what they can. The tokens are Laravel Sanctum tokens. Fusion Stack treats keys and tokens alike, so your endpoints and scopes work for both.

Scopes and records

Scopes say what a caller may do with orders in general. Whether a person may see this order, such as only their own team's, is a different question, which Laravel's policies answer. The authentication guide shows both together.

Every request now gets a 401, even with $KEY

Check that $KEY is still set in this terminal: echo $KEY should print your key. If the terminal was closed, run export KEY=… again, or create a new key as in step 2.

A request gets a 403 the key should not get

A key's scopes are set when it is created, and api:key:create lists them. Create a new key with the scopes it needs. To stop the old one working, revoke it by the number api:key:create showed, here 2:

sh
php artisan tinker --execute="FusionStack\Laravel\Auth\ApiKey::find(2)?->revoke();"

Test it ​

The tests now need keys too. Update tests/Feature/OrderTest.php: each request gets a key with the scope it needs, and a new test checks the scopes are enforced:

php
<?php

use App\Models\Order;
use App\Models\Team;

it('places a pending order for a team', function (): void {
    $team = Team::factory()->create();

    $this->api()->withKey(apiKey('orders:write'))->postJson('/v1/orders', ['data' => [
        'type' => 'orders',
        'attributes' => ['total_cents' => 2500, 'currency' => 'GBP'],
        'relationships' => ['team' => ['data' => ['type' => 'teams', 'id' => (string) $team->id]]],
    ]])
        ->assertCreated()
        ->assertJsonApiResource('orders')
        ->assertJsonPath('data.attributes.status', 'pending');

    expect(Order::query()->sole()->team_id)->toBe($team->id);
});

it('rejects an order in a currency it does not take', function (): void {
    $this->api()->withKey(apiKey('orders:write'))->postJson('/v1/orders', ['data' => [
        'type' => 'orders',
        'attributes' => ['total_cents' => 2500, 'currency' => 'JPY'],
        'relationships' => ['team' => ['data' => ['type' => 'teams', 'id' => (string) Team::factory()->create()->id]]],
    ]])
        ->assertApiError('validation_failed', 422)
        ->assertJsonPath('errors.0.source.pointer', '/data/attributes/currency');

    expect(Order::query()->count())->toBe(0);
});

it('lists orders, newest first', function (): void {
    $old = Order::factory()->create(['created_at' => now()->subDay()]);
    $new = Order::factory()->create();

    $this->api()->withKey(apiKey('orders:read'))->getJson('/v1/orders')
        ->assertJsonApiCollection('orders', 2)
        ->assertJsonPath('data.0.id', (string) $new->id)
        ->assertJsonPath('data.1.id', (string) $old->id);
});

it('filters by status and total, and sorts by total', function (): void {
    Order::factory()->createMany([
        ['status' => 'paid', 'total_cents' => 9000],
        ['status' => 'shipped', 'total_cents' => 6000],
        ['status' => 'paid', 'total_cents' => 4000],
        ['status' => 'pending', 'total_cents' => 8000],
    ]);

    $this->api()->withKey(apiKey('orders:read'))->getJson('/v1/orders?filter[status][in]=paid,shipped&filter[total_cents][gte]=5000&sort=total_cents')
        ->assertJsonApiCollection('orders', 2)
        ->assertJsonPath('data.0.attributes.total_cents', 6000)
        ->assertJsonPath('data.1.attributes.total_cents', 9000);
});

it('includes the team, and rejects what the query does not allow', function (): void {
    Order::factory()->for(Team::factory()->create(['name' => 'Acme Ltd']))->create();

    $this->api()->withKey(apiKey('orders:read'))->getJson('/v1/orders?include=team')
        ->assertJsonPath('data.0.relationships.team.data.type', 'teams')
        ->assertJsonPath('included.0.attributes.name', 'Acme Ltd');

    $this->api()->withKey(apiKey('orders:read'))->getJson('/v1/orders?sort=status')->assertApiError('invalid_sort', 400);
    $this->api()->withKey(apiKey('orders:read'))->getJson('/v1/orders?filter[currency][in]=GBP,USD')->assertApiError('invalid_filter', 400);
});

it('needs a key with the orders scopes', function (): void {
    $order = Order::factory()->create();

    $this->api()->getJson('/v1/orders')->assertApiError('unauthenticated', 401);
    $this->api()->withKey(apiKey('teams:read'))->getJson("/v1/orders/{$order->id}")
        ->assertApiError('insufficient_scope', 403)
        ->assertJsonPath('errors.0.meta.required_scope', 'orders:read');
    $this->api()->withKey(apiKey('orders:read'))->postJson('/v1/orders', ['data' => ['type' => 'orders']])
        ->assertApiError('insufficient_scope', 403);

    expect(Order::query()->count())->toBe(1);
});
sh
composer check
text
Tests: … passed (… assertions)

Next: a custom action.

Released under the MIT License.