Security & errors
The security of an operation and most of its error responses come from what the route already does: its middlewares, its bound models, its form request and the exceptions its action throws.
Security from the middlewares
| Middleware | Security scheme | Also adds |
|---|---|---|
auth:sanctum | sanctum (bearer token), or session + xsrf (the cookie of a SPA) | 401 |
auth:api | passport (OAuth2 authorization code on /oauth/authorize and /oauth/token) | 401 |
auth, auth:<guard> | bearer, or a bearer token named after the guard | 401 |
auth.basic | basic (HTTP basic) | 401 |
abilities:, ability: (Sanctum) | the scopes of the sanctum requirement from 3.1; a sentence of the description before | |
scopes:, scope: (Passport) | the scopes of the passport requirement, declared in its flows | |
can:, Authorize | 403 | |
signed | signature and expires query parameters, 403 | |
throttle | 429 with X-RateLimit-Limit, X-RateLimit-Remaining, Retry-After, X-RateLimit-Reset | |
ValidateCsrfToken (the web group) | X-CSRF-TOKEN header and 419, on the methods that change something |
Each guard of auth:sanctum,api is an alternative requirement.
Your own schemes
security_schemes completes or replaces the schemes the middlewares give, by name. Write each scheme as an OpenAPI
Security Scheme Object: its keys are the OpenAPI field names, in camelCase.
'documents' => [
'v1' => [
'security_schemes' => [
'passport' => [
'type' => 'oauth2',
'flows' => ['authorizationCode' => [
'authorizationUrl' => 'https://example.com/oauth/authorize',
'tokenUrl' => 'https://example.com/oauth/token',
'scopes' => ['books:read' => 'Read the books'],
]],
],
'oidc' => [
'type' => 'openIdConnect',
'openIdConnectUrl' => 'https://example.com'
. '/.well-known/openid-configuration',
],
],
'security' => [], // names of the schemes required on every operation
],
],
security lists the schemes required by default on every operation, on top of those of the middlewares.
Declaring the security
#[Security] replaces the requirements of the middlewares. It is repeatable: each attribute is an alternative.
use Ark4ne\OpenApi\Attributes\Security;
#[Security('oidc', scopes: ['books:write'])]
#[Security('passport', scopes: ['books:write'])]
public function store(StoreBookRequest $request): BookResource
On the controller, it applies to each action; on the action, it replaces those of the class.
To add what a middleware of your own means (a header, a scheme, an error), write a middleware mapper.
Error responses
| Status | Comes from |
|---|---|
| 401 | auth, auth:<guard>, auth.basic, the default security |
| 403 | can:, Authorize, signed, a form request that redefines authorize(), @throws AuthorizationException |
| 404 | a bound model or backed enum in the path, @throws ModelNotFoundException |
| 419 | the CSRF middleware |
| 422 | a form request with rules, @throws ValidationException |
| 429 | throttle |
| any | the @throws of the action |
They are shared responses of components.responses (Unauthenticated, NotFound, ValidationFailed…), with the
bodies Laravel renders: Error ({"message": …}) and ValidationError ({"message": …, "errors": {…}}).
"responses": {
"201": { "…": "…" },
"401": { "$ref": "#/components/responses/Unauthenticated" },
"422": { "$ref": "#/components/responses/ValidationFailed" }
}
With the JSON:API integration and integrations.json_api.errors,
the bodies are JSON:API error documents.
Exceptions of the action
Each @throws of the action becomes a response:
/**
* Book a seat.
*
* @throws SeatTakenException
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function book(string $seat): JsonResponse
The status and the body of an exception come from, in order:
#[Response]on the exception class, or on a parent class:use Ark4ne\OpenApi\Attributes\Response; #[Response(409, description: 'The seat is already taken')] final class SeatTakenException extends RuntimeException {}
Without body, the response has the error body; it acceptsresource,type,headersandexampleas on an action.exceptions.mapof the configuration, for the exceptions you cannot annotate and thosebootstrap/app.phprenders through closures. The exception or its closest parent class wins:config/openapi.php'exceptions' => [ 'read_throws' => true, 'map' => [ PaymentRequiredException::class => 402, SeatTakenException::class => [ 'status' => 409, 'description' => 'Seat taken', ], ], ],- Laravel's rendering:
AuthenticationException401,AuthorizationException403,ModelNotFoundException404,TokenMismatchException419,ValidationException422,ThrottleRequestsException429, subclasses included. - Symfony's HTTP exceptions whose class fixes the status (
NotFoundHttpException…), and an HTTP exception of the application whose constructor without arguments sets its status.
Several causes of one status become one response: a declared #[Response] wins, otherwise their descriptions are put
together and different bodies become oneOf.
Set exceptions.read_throws to false to ignore the @throws tags.