yiisoft / csrf
Yii CSRF Protection Library
Fund package maintenance!
Opencollective
yiisoft
Installs: 173 440
Dependents: 19
Suggesters: 0
Security: 0
Stars: 25
Watchers: 18
Forks: 9
Open Issues: 3
Requires
- php: ^7.4|^8.0
- ext-hash: *
- psr/http-factory: ^1.0
- psr/http-factory-implementation: 1.0
- psr/http-message: ^1.0|^2.0
- psr/http-message-implementation: 1.0
- psr/http-server-handler: ^1.0
- psr/http-server-middleware: ^1.0
- yiisoft/http: ^1.2
- yiisoft/security: ^1.0
- yiisoft/session: ^1.0|^2.0
- yiisoft/strings: ^2.0
Requires (Dev)
- maglnet/composer-require-checker: ^3.8|^4.2
- nyholm/psr7: ^1.3
- phpunit/phpunit: ^9.5
- rector/rector: ^1.2
- roave/infection-static-analysis-plugin: ^1.16
- spatie/phpunit-watcher: ^1.23
- vimeo/psalm: ^4.30|^5.24
- yiisoft/di: ^1.1
README
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
- PHP 7.4 or higher.
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);
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.
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 based token
HMAC based token is a stateless CSRF token that does not require any storage. The token is a hash from session ID and a timestamp used to prevent replay attacks. The token is added to a form. When the form is submitted, we re-generate the token from the current session ID and a timestamp from the original token. If two hashes match, we check that the timestamp is less than the token lifetime.
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
orsha512
are recommended;$lifetime
— number of seconds that the token is valid for.
To learn more about HMAC based token pattern check 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
configuration in the DI container:
// config/web/di/csrf-header.php use Yiisoft\Csrf\CsrfHeaderMiddleware; use Yiisoft\Http\Method; return [ CsrfHeaderMiddleware::class => [ 'withUnsafeMethods()' => [[Method::POST]], 'withHeaderName()' => ['X-CSRF-PROTECTION'], ], ];
The use of a custom request header for CSRF protection is based on the CORS Protocol. Thus, you must configure the CORS module to allow or deny cross-origin access to the backend API.
Warning
CsrfHeaderMiddleware
can be used to prevent forgery of same-origin requests and requests from the list of specific origins only.
Protecting same-origin requests
In this scenario:
- AJAX/SPA frontend and API backend have the same origin.
- Cross-origin requests to the API server are denied.
- Simple CORS requests must be restricted.
Configure CORS module
- Responses to a CORS preflight requests must not contain CORS headers.
- Responses to an actual requests must not contain CORS headers.
Configure middlewares stack
Add CsrfHeaderMiddleware
to the MiddlewareDispatcher
configuration:
$middlewareDispatcher = $injector->make(MiddlewareDispatcher::class); $middlewareDispatcher = $middlewareDispatcher->withMiddlewares([ ErrorCatcher::class, CsrfHeaderMiddleware::class, // <-- add this Router::class, ]);
or to the routes that must be protected to the router configuration:
$collector = $container->get(RouteCollectorInterface::class); $collector->addGroup( Group::create('/api') ->middleware(CsrfHeaderMiddleware::class) // <-- add this ->routes($routes) );
Configure frontend requests
On the frontend add to the GET
, HEAD
, POST
requests a custom header defined in the CsrfHeaderMiddleware
with an empty or random value.
let response = fetch('https://example.com/api/whoami', { headers: { "X-CSRF-HEADER": crypto.randomUUID() } });
Protecting requests from the list of specific origins
In this scenario:
- AJAX/SPA frontend and API backend have different origins.
- Allow cross origin requests to the API server from the list of specific origins only.
- Simple CORS requests must be restricted.
Configure CORS module
- A successful responses to a CORS preflight requests must contain appropriate CORS headers.
- Responses to an actual requests must contain appropriate CORS headers.
- Value of the CORS header
Access-Control-Allow-Origin
must contain origin from the predefined list.
// assuming frontend origin is https://example.com and backend origin is https://api.example.com
Access-Control-Allow-Origin: https://example.com
Configure middlewares stack
Add CsrfHeaderMiddleware
to the MiddlewareDispatcher
configuration:
$middlewareDispatcher = $injector->make(MiddlewareDispatcher::class); $middlewareDispatcher = $middlewareDispatcher->withMiddlewares([ ErrorCatcher::class, CsrfHeaderMiddleware::class, // <-- add this Router::class, ]);
or to the routes that must be protected to the router configuration:
$collector = $container->get(RouteCollectorInterface::class); $collector->addGroup( Group::create('/api') ->middleware(CsrfHeaderMiddleware::class) // <-- add this ->routes($routes) );
Configure frontend requests
On the frontend add to the GET
, HEAD
, POST
requests a custom header defined in the CsrfHeaderMiddleware
with an empty or random value.
let response = fetch('https://api.example.com/whoami', { headers: { "X-CSRF-HEADER": crypto.randomUUID() } });
Protecting requests passed from any origin
In this scenario:
- AJAX/SPA frontend and API backend have different origins.
- Allow cross origin requests to the API server from any origin.
- All requests are considered unsafe and must be protected against CSRF with CSRF-token.
Configure CORS module
- A successful responses to a CORS preflight requests must contain appropriate CORS headers.
- Responses to an actual requests must contain appropriate CORS headers.
- The CORS header
Access-Control-Allow-Origin
has the same value asOrigin
header in the request.
$frontendOrigin = $request->getOrigin();
Access-Control-Allow-Origin: $frontendOrigin
Configure middlewares stack
By default, CsrfTokenMiddleware
considers GET
, HEAD
, OPTIONS
methods as safe operations and doesn't perform CSRF validation.
In JavaScript-based apps, requests are made programmatically; therefore, to increase application protection, the only OPTIONS
method can be considered safe and need not be appended with a CSRF token header.
Configure CsrfTokenMiddleware
safe methods:
use Yiisoft\Csrf\CsrfTokenMiddleware; use Yiisoft\Http\Method; $csrfTokenMiddleware = $container->get(CsrfTokenMiddleware::class); $csrfTokenMiddleware = $csrfTokenMiddleware->withSafeMethods([Method::OPTIONS]);
or in the DI container:
// config/web/di/csrf-token.php use Yiisoft\Csrf\CsrfTokenMiddleware; use Yiisoft\Http\Method; return [ CsrfTokenMiddleware::class => [ 'withSafeMethods()' => [[Method::OPTIONS]], ], ];
Add CsrfTokenMiddleware
to the MiddlewareDispatcher
configuration:
$middlewareDispatcher = $injector->make(MiddlewareDispatcher::class); $middlewareDispatcher = $middlewareDispatcher->withMiddlewares([ ErrorCatcher::class, SessionMiddleware::class, CsrfTokenMiddleware::class, // <-- add this Router::class, ]);
or to the routes that must be protected to the router configuration:
$collector = $container->get(RouteCollectorInterface::class); $collector->addGroup( Group::create('/api') ->middleware(CsrfTokenMiddleware::class) // <-- add this ->routes($routes) );
Configure routes
Create a route for acquiring CSRF-tokens from the frontend application to the router configuration.
use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Yiisoft\Http\Header; use Yiisoft\Http\Method; use Yiisoft\Router\Route; Route::options('/csrf-token') ->action(static function ( ResponseFactoryInterface $responseFactory, CsrfTokenInterface $token ): ResponseInterface { $tokenValue = $token->getValue(); $response = $responseFactory->createResponse() ->withHeader(Header::ALLOW, Method::OPTIONS) ->withHeader('X-CSRF-TOKEN', $tokenValue); $response->getBody()->write($tokenValue); return $response; }),
Configure frontend requests
On the frontend first make a request to the configured endpoint and acquire a CSRF-token to use it in the subsequent requests.
let response = await fetch('https://api.example.com/csrf-token'); let csrfToken = await response.text(); // OR let csrfToken = response.headers.get('X-CSRF-TOKEN');
Add to all requests a custom header defined in the CsrfTokenMiddleware
with acquired CSRF-token value.
let response = fetch('https://api.example.com/whoami', { headers: { "X-CSRF-TOKEN": csrfToken } });
Documentation
If you need help or have a question, the Yii Forum is a good place for that. You may also check out other Yii Community Resources.
License
The Yii CSRF Protection Library is free software. It is released under the terms of the BSD License.
Please see LICENSE
for more information.
Maintained by Yii Software.