Authentication and scopes
Every request to a route in the fusion-stack middleware group (in Rust, a route wrapped in the FusionStack middleware) is matched to a client: whoever is calling, whether an API key, a Sanctum token or a user from your own guard (in Rust, your own client resolver). The client decides which scopes the request has, which API version it is pinned to and which rate limit applies.
API keys
API keys are for servers and integrations. They are built in: there is nothing to install. In Rust they need the crate's database feature.
php artisan api:key:create "Billing service" \
--scope=orders:read --scope=orders:writelaravel api:key:create "Billing service" \
--scope orders:read --scope orders:write INFO Created API key 1. Copy it now: it is not stored and cannot be shown again.
fs_live_…
Scopes ............................................. orders:read, orders:writeClients send it as a bearer token:
curl localhost:8000/v1/orders -H "Authorization: Bearer fs_live_…"- Keys start with
fs_live_, orfs_test_with--test, so they are easy to recognise in logs and secret scanners. - Test keys are for development and staging, where a key is easiest to leak. When
APP_ENVisproduction, they get a401like an unknown key, unless you turn onauth.test_keys_in_production(Config::test_keys_in_production(true)in Rust). - Only a SHA-256 hash of the key is stored. Lost keys cannot be shown again: create a new one.
- When versioning is on, a new key is pinned to the latest version, or the one
--pingives.php artisan api:key:pin 1 2027-01-15.atlas(orlaravel api:key:pin 1 2027-01-15.atlasin Rust) moves it when its owner upgrades. last_used_atis updated at most once a minute, and$key->revoke()(api_keys::revoke(id)in Rust) stops a key working at once.- A key works until it is revoked, unless it has an expiry:
--expires-in=90makes one that stops working after 90 days. Give short-lived keys to CI jobs, contractors and trials, so a forgotten key does not stay valid for ever.
In code, ApiKey::issue() (api_keys::issue() in Rust) creates a key and returns it with its plain-text value, for a settings page where your users create their own. Rust keys have no owner columns, so keep the returned ID against the owner yourself, and pass the version to pin to. Both take an expiry:
[$key, $plain] = ApiKey::issue(
'Zapier',
['orders:read'],
attributes: ['owner_id' => $team->id, 'owner_type' => Team::class],
expiresAt: now()->addDays(90),
);use fusion_stack::auth::api_keys;
let (id, plain) = api_keys::issue(api_keys::Issue {
name: "Zapier".to_owned(),
scopes: vec!["orders:read".to_owned()],
version: Some("2027-01-15.atlas".to_owned()),
expires_at: Some((laravel::now() + 90.days()).timestamp()),
..Default::default()
})
.await?;Sanctum tokens
Your own apps, such as a Nuxt frontend or a mobile app, sign users in and use Laravel Sanctum tokens. The starter kit has a POST /v1/tokens endpoint that does this. A token's abilities are its scopes. Laravel for Rust has no Sanctum: sign users in your own way, and turn their tokens into clients with Config::client_resolver and auth::resolver, as in other guards.
$token = $user->createToken('mobile', ['orders:read', 'orders:write'])->plainTextToken;use fusion_stack::auth::{self, ApiClient};
Config::new().client_resolver(auth::resolver(|headers| async move {
// Look up your own token, and return its scopes.
let Some(user) = your_app::user_for_token(&headers).await? else {
return Ok(None);
};
Ok(Some(ApiClient::new(format!("user:{}", user.id)).scopes(["orders:read", "orders:write"])))
}))A user signed in with Sanctum's cookie authentication, as a first-party single-page app is, has every scope, as Sanctum's own tokenCan() does.
Scopes
A scope is a permission, such as orders:read. Declare what each endpoint needs with #[RequiresScope], on the controller or an action. In Rust, RequiresScope is route middleware, on a group or a route, and Endpoint::scope lists it in the OpenAPI document. The description documents the scope in the API reference:
#[RequiresScope('orders:read', 'Read orders.')]
final class OrderController
{
public function index(OrderQuery $query) { ... }
// Needs orders:read from the class, and orders:write.
#[RequiresScope('orders:write', 'Change orders, such as cancelling them.')]
public function cancel(Order $order) { ... }
}use fusion_stack::RequiresScope;
route.middleware(RequiresScope::new("orders:read").describe("Read orders.")).group(|route| {
route.get("/orders", orders_index);
// Needs orders:read from the group, and orders:write.
route
.post("/orders/{order}/cancel", orders_cancel)
.middleware(RequiresScope::new("orders:write").describe("Change orders, such as cancelling them."));
});In PHP, #[RequiresScope] on a parent class applies to the controllers that extend it, so a base controller can require a scope for all of them.
For closures and routes without a controller, use the scope middleware: ->middleware('scope:reports:read,reports:export'). In Rust every route uses RequiresScope, one per scope: .middleware((RequiresScope::new("reports:read"), RequiresScope::new("reports:export"))).
A guest gets a 401 unauthenticated. A client without the scope gets a 403 that names it:
{
"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_01m8rcp01y8x0kxsc0d2vc0cv4"
}
}
]
}Granted scopes may use wildcards: orders:* covers every orders: scope, and * covers every scope.
Scopes say what kind of thing a client may do, not which records. To limit a client to its own data, scope the query: see limiting what a caller sees.
Other guards
Requests are tried against the guards in api.auth.guards, in order. The first that authenticates the request wins. Guards your app does not define are skipped, so sanctum costs nothing without Sanctum installed. Laravel for Rust has no guards: Config::client_resolver runs your own resolver first, then the crate's API keys. It has no auth.attributes either, as the resolver sets the client's scopes, version and tier itself.
// config/api.php
'auth' => [
'guards' => ['api_key', 'sanctum', 'firebase'],
// Where scopes, the pinned version and the rate limit tier come from, for guards without
// their own resolver: attributes of the user, or claims of a token.
'attributes' => [
'scopes' => 'api_scopes',
'version' => 'api_version',
'rate_limit_tier' => 'api_rate_limit_tier',
],
],use fusion_stack::auth;
// Tried before the crate's API keys. Returning None falls through to them, then to a guest.
Config::new().client_resolver(auth::resolver(firebase_client))Any Laravel guard works. For example, Firebase ID tokens with kreait/laravel-firebase, whose custom claims carry the scopes. In Rust, verify the token in the resolver:
// AppServiceProvider::boot()
Auth::viaRequest('firebase', function (Request $request): ?GenericUser {
$token = $request->bearerToken();
if ($token === null) {
return null;
}
$claims = app(\Kreait\Firebase\Contract\Auth::class)->verifyIdToken($token)->claims()->all();
return new GenericUser(['id' => $claims['sub'], ...$claims]);
});use fusion_stack::auth::ApiClient;
use laravel::axum::http::HeaderMap;
async fn firebase_client(headers: HeaderMap) -> laravel::Result<Option<ApiClient>> {
let Some(token) = headers
.get("authorization")
.and_then(|value| value.to_str().ok())
.and_then(|value| value.strip_prefix("Bearer "))
else {
return Ok(None);
};
// Your own verification of the Firebase ID token, such as with a JWT crate.
let Some(claims) = your_app::verify_firebase_token(token).await? else {
return Ok(None);
};
Ok(Some(
ApiClient::new(format!("firebase:{}", claims.sub))
.scopes(claims.api_scopes)
.version(claims.api_version)
.rate_limit_tier(claims.api_rate_limit_tier),
))
}// config/auth.php
'guards' => ['firebase' => ['driver' => 'firebase']],When reading attributes is not enough, implement ClientResolver and register it for the guard in api.auth.resolvers. In Rust there is no separate step: the resolver above already builds the ApiClient, with scopes, version and rate_limit_tier.
final class TeamMemberResolver implements ClientResolver
{
public function resolve(Authenticatable $user, string $guard): ApiClient
{
return new ApiClient(
id: "member:{$user->getAuthIdentifier()}",
scopes: $user->role->scopes(),
version: $user->team->api_version,
rateLimitTier: $user->team->plan,
);
}
}The client in your code
ApiClient::current($request) (fusion_stack::auth::client(&request) in Rust) returns the request's client, or null (None) for a guest:
$client = ApiClient::current($request);
$client?->id; // "api_key:1"
$client?->hasScope('orders:write');let client = fusion_stack::auth::client(&request);
client.as_ref().map(|client| client.id.as_str()); // Some("api_key:1")
client.as_ref().is_some_and(|client| client.has_scope("orders:write"));In PHP, $request->user() is still the authenticated user or key, from whichever guard matched.