Core Concepts
The security layer consists of four main pillars:- Identities: Objects representing the current requester (e.g., a logged-in user or a guest).
- Scopes: Value objects that define specific permissions or capabilities.
- Authenticators: Services that turn credentials (like a JWT) into an Identity.
- Middleware: The glue that executes authentication and enforces authorization on routes.
The Security Flow
- Request Arrival: An HTTP request enters the application.
- Authentication: An authentication middleware (like
AuthenticationMiddleware) uses anAuthenticatorto identify the requester and sets anAuthIdentityon the request. - Authorization: The
SecurityMiddlewarecompares theAuthIdentity’s granted scopes against thesecurityRequirementsdefined in theRoute. - Controller: If authorized, the controller receives the request and can access the identity via
$request->getAuthIdentity().
Quick Example: Private Route
BearerAuth with the admin:read scope.
Connection to OpenAPI
When generating documentation using theOpenAPIGenerator, the name you use in your SecurityRequirementObject (e.g., 'BearerAuth') MUST match the name of a SecuritySchemeObject defined in your ComponentsObject.
If the names match, Apivalk will use your full configuration (flows, descriptions, etc.) in the generated Swagger file. This is the best practice for complex setups like OAuth2, as it allows Swagger UI to “just work” with your authentication server.
If they don’t match, Apivalk will generate a basic placeholder scheme automatically.
Keep in mind: Future Auto-Discovery. Apivalk is moving towards full auto-discovery of security schemes. In the future, it will be able to automatically detect and document your security configuration (including names and versions) directly from your middleware and authenticators.See the OpenAPI Generator documentation for details on how to configure these components.
Examples: Getting Started with Middleware
To use the security system, you typically need to register two middlewares in yourMiddlewareStack.