On this page
CSRF Guard Middleware
Since CSRF token generation and validation relies on request artifacts, we
Mezzio\Csrf\CsrfMiddleware to generate the appropriate guard
instance and pass it into a request attribute.
This approach allows you to have a single location or specific locations where CSRF guards are generated, which can then be used by any middleware in your application.
CsrfMiddleware has the following constructor arguments:
CsrfGuardFactoryInterface $guardFactory: a concrete instance to use for generating the CSRF guard instance.
string $attributeKey: the name of the request attribute in which to store the CSRF guard instance. Defaults to the
We provide and map a factory for the middleware,
Mezzio\Csrf\CsrfMiddlewareFactory; that factory depends on having the
Mezzio\Csrf\CsrfGuardFactoryInterface defined (by default it
is, and points to the
If you want to override the defaults, create and map a custom factory.
Registering the middleware
The middleware depends on the
must be piped AFTER that middleware. It can be piped either in the
application pipeline, or within routed middleware.
As an example, in
Within routed middleware:
$app->get('/user/login', [ \Mezzio\Session\SessionMiddleware::class, \Mezzio\Csrf\CsrfMiddleware::class, UserLoginFormHandler::class, ]); $app->post('/user/login', [ \Mezzio\Session\SessionMiddleware::class, \Mezzio\Csrf\CsrfMiddleware::class, ProcessUserLoginHandler::class, ]);
Found a mistake or want to contribute to the documentation? Edit this page on GitHub!