CSRF is one of the most well-known attacks, it has existed since the “foundation” of the Web. It occurs when an HTTP request is made between sites in an attempt to impersonate a legitimate user. Whoever uses this type of attack usually focuses on doing so hoping that the target user will be authenticated on the site where the fraudulent request will be made, in order to have more privileges and access to operations. And the reason for the whole problem is how browsers handle Cookies.
Any forms posting to POST
, PUT
or DELETE
routes should include the CSRF-token. We strongly recommend that you enable CSRF-verification on your site to maximize security.
The CSRF check is generated by default in Solital, but it is possible to extend this check.
If you want to store the token elsewhere, please refer to the "Creating custom Token Provider" section below.
By default, Solital will use the BaseCsrfVerifier
class.
When you've created your CSRF-verifier you need to tell Solital that it should use it. You can do this by editing the following line in your bootstrap.yaml
file:
# Custom CSRF verifier class
custom_csrf: BaseCsrfVerifier
When posting to any of the urls that has CSRF-verification enabled, you need post your CSRF-token or else the request will get rejected.
You can get the CSRF-token by calling the helper method:
csrf_token();
The default name/key for the input-field is csrf_token
and is defined in the POST_KEY
constant in the BaseCsrfVerifier
class.
You can change the key by overwriting the constant in your own CSRF-verifier class.
Example:
The example below will post to the current url with a hidden field "csrf_token
".
<form method="post" action="{{ url(); }}">
{{ csrf_token(); }}
<!-- other input elements here -->
</form>
Create a new class and extend the `BaseCsrfVerifier
middleware class provided by default with the Solital library.
Add the property except with an array of the urls to the routes you want to exclude/whitelist from the CSRF validation. Using *
at the end for the url will match the entire url.
Here's a basic example on a CSRF-verifier class:
namespace Solital\Middleware;
use Solital\Core\Http\Middleware\BaseCsrfVerifier;
class CustomCsrfVerifier extends BaseCsrfVerifier
{
/**
* CSRF validation will be ignored on the following urls.
*/
protected array $except = ['/api/*'];
}
And change in bootstrap.yaml
# Custom CSRF verifier class
custom_csrf: CustomCsrfVerifier