Skip to main content
The 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 the Route object from the controller being called and examines its RouteAuthorization.

Authorization Logic

A route can have a RouteAuthorization object that defines:
  1. Security Scheme: The name of the security scheme required (e.g., BearerAuth).
  2. Scopes: A list of required scopes.
  3. Permissions: A list of required permissions.
The current Identity must possess all the required scopes and permissions to be granted access.

Route Examples

Private Route (Authorization Required)

A route that requires a logged-in user with specific scopes and permissions.
use apivalk\apivalk\Router\Route;
use apivalk\apivalk\Security\RouteAuthorization;

$route = Route::get('/admin/dashboard')
                ->description('Admin Dashboard')
                ->authorization(new RouteAuthorization('BearerAuth', ['admin'], ['admin:dashboard:read']))

Public Route (No Authorization)

A route that is accessible by anyone.
$route = Route::get('/about')->description('About page');

Optional Security (Public with Authorization)

Currently, optional security (where a route is public but can optionally take a token) is handled by not defining a RouteAuthorization 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:
  1. 401 Unauthorized: Thrown when a GuestAuthIdentity (anonymous user) attempts to access a route that requires security.
  2. 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

The SecurityMiddleware should always be placed after your authentication middleware in the stack.
$configuration->addMiddleware(new AuthenticationMiddleware($authenticator));
$configuration->addMiddleware(new SecurityMiddleware());