SecurityMiddleware is the core authorization engine of Apivalk. It ensures that the current requester has the necessary scopes and permissions to access a specific route. For a deep dive into the underlying architecture, check the Security Overview.
How it Works
The middleware retrieves theRoute object from the controller being called and examines its RouteAuthorization.
Authorization Logic
A route can have aRouteAuthorization object that defines:
- Security Scheme: The name of the security scheme required (e.g.,
BearerAuth). - Scopes: A list of required scopes.
- Permissions: A list of required permissions.
Route Examples
Private Route (Authorization Required)
A route that requires a logged-in user with specific scopes and permissions.Public Route (No Authorization)
A route that is accessible by anyone.Optional Security (Public with Authorization)
Currently, optional security (where a route is public but can optionally take a token) is handled by not defining aRouteAuthorization on the route, or by custom middleware logic. If a RouteAuthorization is present, it will be enforced.
Status Codes
When authorization fails, the middleware throws an exception that results in one of two HTTP status codes:- 401 Unauthorized: Thrown when a GuestAuthIdentity (anonymous user) attempts to access a route that requires security.
- 403 Forbidden: Thrown when an authenticated UserAuthIdentity does not have the required scopes for the route.
Scopes and Permissions
While many frameworks use roles (e.g.,ROLE_ADMIN), Apivalk follows the OpenAPI standard of using Scopes and Permissions. Scopes and permissions are more granular and describe what an identity is allowed to do (e.g., read:users) rather than who they are.
Integration
TheSecurityMiddleware should always be placed after your authentication middleware in the stack.