CSRF Protection

Introducion

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.

You can use the BaseCsrfVerifier to enable CSRF-validation on all request. If you need to disable verification for specific urls, please refer to the "Custom CSRF-verifier" section below.

By default Solital will use the CookieTokenProvider class. This provider will store the security-token in a cookie on the clients machine. If you want to store the token elsewhere, please refer to the "Creating custom Token Provider" section below.

Adding CSRF-verifier

When you've created your CSRF-verifier you need to tell Solital that it should use it. You can do this by adding the following line in your routes.php file:

Course::csrfVerifier(new \Solital\Core\Http\Middleware\BaseCsrfVerifier());

Getting CSRF-token

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();

You can also get the token directly:

return Course::router()->getCsrfVerifier()->getTokenProvider()->setToken();

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>

What to see next?


Built with MkDocs.