Documentation/Container/Services/Csrf

Protection against CSRF

The Csrf service in the HLEB2 framework is designed to protect against CSRF(Cross-Site Request Forgery) attacks, based on cross-site user request forgery.

The principle of protection is implemented in the framework by passing a token through the frontend of the application while simultaneously saving the token value in the user's session. These values will be checked by the framework to ensure the user came from the page where the token was set, otherwise an error message will be displayed.

To have the framework verify the passed token, add the protect() method to the target route.

Methods of using the Csrf service in controllers (and all classes inherited from Hleb\Base\Container) illustrated by obtaining the hash code for request verification:

// variant 1
use Hleb\Reference\CsrfInterface;
$token $this->container->get(CsrfInterface::class)->token();

// variant 2
$token $this->container->csrf()->token();

Example of accessing the Csrf service in template code:

<?php
/** @var \App\Bootstrap\ContainerInterface $container */
?>
<form action="/url">
    <!-- ... -->
    <input type="hidden" name="_token" value="<?= $container->csrf()->token(); ?>">
</form>

For TWIG template engine:

<form action="/url">
    <!-- ... -->
    <
input type="hidden" name="_token" value="{{ container.csrf.token }}">
</
form>

The Csrf object can also be obtained through dependency injection using the Hleb\Reference\Interface\Csrf interface.


#token()

The token() method returns a unique user session token.


#field()

The field() method returns HTML content to insert in the form to pass the token with other data.


#validate()

This method allows manual token validation (if protection is not enabled on the route).

Getting settings Conversion to PSR

Page translated: chatgpt 4-o
Back to top