Skip to content

CSRF Token, SameSite Cookie

Choose a tag to compare

@devosc devosc released this 27 Dec 18:55
· 47 commits to master since this release

CSRF Token

A CSRF token is now used to protect routes against CSRF attacks. A new token is generated every time a new PHP session is created for the user. The token is then added to a POST form using a hidden HTML input element. The csrf_token helper function can be used to retrieve the current token.

<input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($this->csrf_token()); ?>">

The HTTP methods GET, HEAD, OPTIONS and TRACE, are considered "safe" and do not require a CSRF token. Safe HTTP methods should not be used to change the state of the application. Any other HTTP method is considered "unsafe" and requires a CSRF token to be sent with the request, either as a POST parameter, or using the X-CSRF-Token HTTP header. A 403 Forbidden HTTP Error is returned when the token is not valid.

new Request([
    'method' => 'POST', 
    'data' => ['csrf_token' => '882023fdc5f837855a...'],
    'headers' => ['X-CSRF-Token' => '882023fdc5f837855a...'],
]);

Routes can be configured not to verify the CSRF token by setting the csrf_token route attribute to false. Child routes inherit the csrf_token value of a parent route.

'api' => [
    'path' => '/api',
    'controller' => Api\Controller::class,
    'csrf_token' => false,
],

SameSite Cookies

The Cookies interface has been updated to match the new setcookie(string $name, string $value = '', array $options = []) method signature available in PHP 7.3, and to support the new SameSite cookie attribute. PHP 7.2 and below can still be used, but without the SameSite cookie attribute. A cookie can now be set in the following ways, and each cookie is stored as an associative array.

$cookies->with('foo', '', ['expires' => 0, ...]);
$cookies->with(['foo', '', 0, ...]);
$cookies->with(['name' => 'foo', 'value' => '', 'expires' => 0, 'raw' => true, ...]);

The PHPCookies::send(array $cookie, array $defaults = []) static method can now set raw cookies by setting the cookie raw attribute to true. To remove a PHP cookie, use PHPCookies::delete($name, array $options = []) or $cookies->without($name, array $options = []). Cookie defaults are now only applied when sending a cookie. The default value for SameSite cookies is lax.

PHP Sessions

To use SameSite session cookies in PHP 7.3, set the cookie_samesite attribute to lax or strict in the session configuration file.