Skip to content

Commit

Permalink
feature symfony#19870 [Security] Add support for dynamic CSRF id with…
Browse files Browse the repository at this point in the history
… Expression in `#[IsCsrfTokenValid]` (alamirault)

This PR was squashed before being merged into the 7.1 branch.

Discussion
----------

[Security] Add support for dynamic CSRF id with Expression in `#[IsCsrfTokenValid]`

Fix symfony#19753

Commits
-------

e0a49ba [Security] Add support for dynamic CSRF id with Expression in `#[IsCsrfTokenValid]`
  • Loading branch information
OskarStark committed May 10, 2024
2 parents 8c17143 + e0a49ba commit f35eec7
Showing 1 changed file with 26 additions and 0 deletions.
26 changes: 26 additions & 0 deletions security/csrf.rst
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,32 @@ attribute on the controller action::
// ... do something, like deleting an object
}

Suppose you want a CSRF token per item, so in the template you have something like the following:

.. code-block:: html+twig

<form action="{{ url('admin_post_delete', { id: post.id }) }}" method="post">
{# the argument of csrf_token() is a dynamic id string used to generate the token #}
<input type="hidden" name="token" value="{{ csrf_token('delete-item-' ~ post.id) }}">

<button type="submit">Delete item</button>
</form>

The :class:`Symfony\\Component\\Security\\Http\\Attribute\\IsCsrfTokenValid`
attribute also accepts an :class:`Symfony\\Component\\ExpressionLanguage\\Expression`
object evaluated to the id::

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Attribute\IsCsrfTokenValid;
// ...

#[IsCsrfTokenValid(new Expression('"delete-item-" ~ args["post"].id'), tokenKey: 'token')]
public function delete(Post $post): Response
{
// ... do something, like deleting an object
}

.. versionadded:: 7.1

The :class:`Symfony\\Component\\Security\\Http\\Attribute\\IsCsrfTokenValid`
Expand Down

0 comments on commit f35eec7

Please sign in to comment.