Yii CSRF Protection Library

The package provides PSR-15 middleware for CSRF protection:
- It supports two algorithms out of the box:
- Synchronizer CSRF token with customizable token generation and storage. By default, it uses random data and session.
- HMAC based token with customizable identity generation. Uses session by default.
- It has ability to apply masking to CSRF token string to make BREACH attack impossible.
- It supports CSRF protection by custom header for AJAX/SPA backend API.
Requirements
Installation
The package could be installed with Composer:
composer require yiisoft/csrf
General usage
In order to enable CSRF protection you need to add CsrfTokenMiddleware to your main middleware stack.
In Yii it is done by configuring MiddlewareDispatcher:
$middlewareDispatcher = $injector->make(MiddlewareDispatcher::class);
$middlewareDispatcher = $middlewareDispatcher->withMiddlewares([
ErrorCatcher::class,
SessionMiddleware::class,
CsrfTokenMiddleware::class, // <-- add this
Router::class,
]);
or define the MiddlewareDispatcher configuration in the DI container:
// config/web/di/application.php
return [
MiddlewareDispatcher::class => [
'withMiddlewares()' => [[
ErrorCatcher::class,
SessionMiddleware::class,
CsrfTokenMiddleware::class, // <-- add this
Router::class,
]]
],
];
By default, CSRF token is obtained from _csrf request body parameter or X-CSRF-Token header.
You can access currently valid token as a string using CsrfTokenInterface:
/** @var Yiisoft\Csrf\CsrfTokenInterface $csrfToken */
$csrf = $csrfToken->getValue();
If the token does not pass validation, the response 422 Unprocessable Entity will be returned.
You can change this behavior by implementing your own request handler:
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Yiisoft\Csrf\CsrfTokenMiddleware;
/**
* @var Psr\Http\Message\ResponseFactoryInterface $responseFactory
* @var Yiisoft\Csrf\CsrfTokenInterface $csrfToken
*/
$failureHandler = new class ($responseFactory) implements RequestHandlerInterface {
private ResponseFactoryInterface $responseFactory;
public function __construct(ResponseFactoryInterface $responseFactory)
{
$this->responseFactory = $responseFactory;
}
public function handle(ServerRequestInterface $request): ResponseInterface
{
$response = $this->responseFactory->createResponse(400);
$response
->getBody()
->write('Bad request.');
return $response;
}
};
$middleware = new CsrfTokenMiddleware($responseFactory, $csrfToken, $failureHandler);
or define the CsrfTokenMiddleware configuration in the DI container, using
your own RequestHandlerInterface implementation as a regular service instead of the anonymous class above:
// config/web/di/csrf-token.php
use Yiisoft\Csrf\CsrfTokenMiddleware;
use Yiisoft\Definitions\Reference;
return [
CsrfTokenMiddleware::class => [
'__construct()' => [
'failureHandler' => Reference::to(MyFailureHandler::class),
],
],
];
By default, CsrfTokenMiddleware considers GET, HEAD, OPTIONS methods as safe operations and doesn't perform CSRF validation. You can change this behavior as follows:
use Yiisoft\Csrf\CsrfTokenMiddleware;
use Yiisoft\Http\Method;
$csrfTokenMiddleware = $container->get(CsrfTokenMiddleware::class);
// Returns a new instance with the specified list of safe methods.
$csrfTokenMiddleware = $csrfTokenMiddleware->withSafeMethods([Method::OPTIONS]);
// Returns a new instance with the specified header name.
$csrfTokenMiddleware = $csrfTokenMiddleware->withHeaderName('X-CSRF-PROTECTION');
or define the CsrfTokenMiddleware configuration in the DI container:
// config/web/di/csrf-token.php
use Yiisoft\Csrf\CsrfTokenMiddleware;
use Yiisoft\Http\Method;
return [
CsrfTokenMiddleware::class => [
'withSafeMethods()' => [[Method::OPTIONS]],
'withHeaderName()' => ['X-CSRF-PROTECTION'],
],
];
CSRF Tokens
In case Yii framework is used along with config plugin, the package is configured
automatically to use synchronizer token and masked decorator. You can change that depending on your needs.
Use synchronizer token for sensitive anonymous forms; use HMAC signed token for authenticated-only forms when it is
acceptable for a submitted token to stay valid until it expires.
flowchart TD
A{Anonymous forms to protect?}
A -- Yes --> S[Synchronizer]
A -- No --> B{Old or repeated submits must fail?}
B -- Yes --> S
B -- No --> C{Per-environment secret key?}
C -- No --> S
C -- Yes --> D{Token replay within lifetime OK?}
D -- No --> S
D -- Yes --> H[HMAC signed]
Detailed comparison:
| Factor |
Synchronizer |
HMAC signed |
| I/O per request |
Session read and write |
No token storage I/O |
| File based session GC |
May scan session files |
Not triggered by CSRF token storage |
| Token storage growth |
Depends on session storage |
Nothing to store |
| Token revocation |
Possible by removing stored token |
Not possible before token expiration |
| Replay within lifetime |
Prevented by storage policy |
Possible until expiration |
To switch to HMAC signed token:
use Yiisoft\Csrf\CsrfTokenInterface;
use Yiisoft\Csrf\Hmac\HmacCsrfToken;
use Yiisoft\Csrf\MaskedCsrfToken;
use Yiisoft\Definitions\Reference;
return [
CsrfTokenInterface::class => [
'class' => MaskedCsrfToken::class,
'__construct()' => [
'token' => Reference::to(HmacCsrfToken::class),
],
],
];
Synchronizer CSRF token
Synchronizer CSRF token is a stateful CSRF token that is a unique random string. It is saved in persistent storage
available only to the currently logged-in user. The same token is added to a form. When the form is submitted,
token that came from the form is compared against the token stored.
SynchronizerCsrfToken requires implementation of the following interfaces:
CsrfTokenGeneratorInterface for generating a new CSRF token;
CsrfTokenStorageInterface for persisting a token between requests.
Package provides RandomCsrfTokenGenerator that generates a random token and
SessionCsrfTokenStorage that persists a token between requests in a user session.
To learn more about the synchronizer token pattern,
check OWASP CSRF cheat sheet.
HMAC signed token
HMAC signed token is a stateless CSRF token that does not require any storage. The token contains expiration timestamp
and its signature is bound to the current identity. The token is added to a form. When the form is submitted, we verify
the token signature, check that it belongs to the current identity, and check that it has not expired.
HmacCsrfToken requires implementation of CsrfTokenIdentityGeneratorInterface for generating an identity.
The package provides SessionCsrfTokenIdentityGenerator that is using session ID thus making the session a token scope.
Parameters set via the HmacCsrfToken constructor are:
$secretKey — shared secret key used to generate the hash;
$algorithm — hash algorithm for message authentication. sha256, sha384 or sha512 are recommended;
$lifetime — number of seconds that the token is valid for.
When using HMAC with the config plugin, configure these constructor arguments through parameters:
return [
'yiisoft/csrf' => [
'hmacToken' => [
'secretKey' => (string) getenv('YII_CSRF_SECRET_KEY'),
'algorithm' => 'sha256',
'lifetime' => 300,
],
],
];
To learn more about employing HMAC CSRF tokens, check the
OWASP CSRF cheat sheet.
Stub CSRF token
The StubCsrfToken simply stores and returns a token string. It does not perform any additional validation.
This implementation can be useful when mocking CSRF token behavior during unit testing or when providing
placeholder functionality in temporary solutions.
Masked CSRF token
MaskedCsrfToken is a decorator for CsrfTokenInterface that applies masking to a token string.
It makes BREACH attack impossible, so it is safe to use token in HTML to be later passed to
the next request either as a hidden form field or via JavaScript async request.
It is recommended to always use this decorator.
CSRF protection for AJAX/SPA backend API
If you are using a cookie to authenticate your AJAX/SPA, then you do need CSRF protection for the backend API.
Employing custom request header
In this pattern, AJAX/SPA frontend appends a custom header to API requests that require CSRF protection. No token is needed for this approach. This defense relies on the CORS preflight mechanism which sends an OPTIONS request to verify CORS compliance with the destination server. All modern browsers, according to the same-origin policy security model, designate requests with custom headers as "to be preflighted". When the API requires a custom header, you know that the request must have been preflighted if it came from a browser.
The header can be any arbitrary key-value pair, as long as it does not conflict with existing headers. Empty value is also acceptable.
X-CSRF-HEADER=1
When handling the request, the API checks for the existence of this header. If the header does not exist, the backend rejects the request as potential forgery. Employing a custom header allows to reject simple requests that browsers do not designate as "to be preflighted" and permit them to be sent to any origin.
In order to enable CSRF protection you need to add CsrfHeaderMiddleware to the MiddlewareDispatcher configuration:
$middlewareDispatcher = $injector->make(MiddlewareDispatcher::class);
$middlewareDispatcher = $middlewareDispatcher->withMiddlewares([
ErrorCatcher::class,
CsrfHeaderMiddleware::class, // <-- add this
Router::class,
]);
or in the DI container:
// config/web/di/application.php
return [
MiddlewareDispatcher::class => [
'withMiddlewares()' => [[
ErrorCatcher::class,
CsrfHeaderMiddleware::class, // <-- add this
Router::class,
]]
],
];
or add CsrfHeaderMiddleware to the routes that must be protected to the router configuration:
// config/web/di/router.php
return [
RouteCollectionInterface::class => static function (RouteCollectorInterface $collector) use ($config) {
$collector
->middleware(CsrfHeaderMiddleware::class) // <-- add this
->addGroup(Group::create(null)->routes($routes));
return new RouteCollection($collector);
},
];
By default, CsrfHeaderMiddleware considers only GET, HEAD, POST methods as unsafe operations. Requests with other HTTP methods trigger CORS preflight and do not require CSRF header validation. You can change this behavior as follows:
use Yiisoft\Csrf\CsrfHeaderMiddleware;
use Yiisoft\Http\Method;
$csrfHeaderMiddleware = $container->get(CsrfHeaderMiddleware::class);
// Returns a new instance with the specified list of unsafe methods.
$csrfHeaderMiddleware = $csrfHeaderMiddleware->withUnsafeMethods([Method::POST]);
// Returns a new instance with the specified header name.
$csrfHeaderMiddleware = $csrfHeaderMiddleware->withHeaderName('X-CSRF-PROTECTION');
or define the CsrfHeaderMiddleware