AuthenticationMiddleware
in package
implements
MiddlewareInterface
PSR-15 middleware that authenticates every inbound request.
Delegates authentication to an Authenticator and, if credentials are
valid, stamps the resulting Principal onto the 'principal' request
attribute for downstream handlers to consume. Anonymous requests (no or
unrecognised credentials) flow through unchanged — this middleware never
produces a 401 response by itself. The 401/403 decision is made downstream
by AuthorizationMiddleware, which inspects route-level PHP attributes such
as RequiresAuth, RequiresRole, and RequiresScope.
Additionally, the boolean flag CHECKED_ATTRIBUTE is set on every request that passes through. Downstream resolvers use this flag to distinguish "no credentials supplied" (401) from "middleware was never registered" (500).
Register once globally so every route is covered:
$app->middleware(new AuthenticationMiddleware($authenticator, $logger))
->get('/health', static fn() => Response::ok()) // public route
->get('/orders', OrderListHandler::class); // #[RequiresAuth] on class
Tags
Table of Contents
Interfaces
- MiddlewareInterface
Constants
- CHECKED_ATTRIBUTE = 'nexus.auth.checked'
- Request attribute set unconditionally on every passage through this middleware.
Methods
- __construct() : mixed
- process() : ResponseInterface
- Authenticate the request and pass it to the next handler.
Constants
CHECKED_ATTRIBUTE
Request attribute set unconditionally on every passage through this middleware.
public
mixed
CHECKED_ATTRIBUTE
= 'nexus.auth.checked'
Resolvers and downstream middleware read this flag to distinguish "middleware ran, no credentials" (should 401) from "middleware was never registered" (likely a configuration error that should 500).
Methods
__construct()
public
__construct(Authenticator $authenticator[, LoggerInterface $logger = new NullLogger() ]) : mixed
Parameters
- $authenticator : Authenticator
- $logger : LoggerInterface = new NullLogger()
process()
Authenticate the request and pass it to the next handler.
public
process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
Sets CHECKED_ATTRIBUTE on the request, then attempts authentication.
On success the Principal is added as the 'principal' attribute.
Anonymous requests pass through with only the checked flag set.
Parameters
- $request : ServerRequestInterface
- $handler : RequestHandlerInterface