SecurityMiddleware is the core authorization engine of Apivalk. It ensures that the current requester has the necessary scopes 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 securityRequirements.
OR Logic (Requirements)
A route can have multiple security requirements. If any one of these requirements is satisfied, the request is allowed.AND Logic (Scopes)
Each security requirement can have multiple Scopes. The current Identity must possess all of those scopes to satisfy that specific requirement.Route Examples
Private Route (Scopes Required)
A route that requires a logged-in user with specific Scopes.Public Route (No Scopes)
A route that is accessible by anyone.Optional Security (Public with Scopes)
A route that is public but allows extra access if a token with specific scopes is provided. This is achieved by adding an emptySecurityRequirementObject.
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 vs. Roles
While many frameworks use roles (e.g.,ROLE_ADMIN), Apivalk follows the OpenAPI standard of using Scopes. Scopes 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.