Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 1 commit into from
May 10, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions security/csrf.rst
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,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
Loading