AuthenticationMiddleware acts as the first gate in your security pipeline. Its primary job is to extract a token (usually from the Authorization header) and verify it.
Overview
Unlike many frameworks, Apivalk does not throw exceptions if authentication fails in this middleware. Instead:- It attempts to authenticate the token using an AuthenticatorInterface.
- If successful, it sets a UserAuthIdentity on the Request.
- If it fails or no token is provided, the Request remains with its default GuestAuthIdentity.
Usage
To use it, you must provide an implementation of the AuthenticatorInterface.JWT / OAuth Example
If you are using JWT with JWKS (e.g., Auth0, Okta, Azure AD), use the JwtAuthenticator.Custom Authentication Logic
If you have custom authentication needs (e.g., API Keys in database), you can implement your own authenticator or middleware.Implementing a Custom Authenticator
Implementing a Custom Middleware
If you want full control over the process, you can implement theMiddlewareInterface directly and use setAuthIdentity() on the request.
Important: Middleware Ordering
TheAuthenticationMiddleware MUST run BEFORE the SecurityMiddleware.
The authentication middleware populates the “Who” (Identity), while the security middleware validates the “What” (Scopes). If run out of order, the security middleware will always see a GuestAuthIdentity.