Skip to content

Commit e0a49ba

Browse files
alamiraultOskarStark
authored andcommitted
[Security] Add support for dynamic CSRF id with Expression in #[IsCsrfTokenValid]
1 parent b80bbc7 commit e0a49ba

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

security/csrf.rst

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,32 @@ attribute on the controller action::
181181
// ... do something, like deleting an object
182182
}
183183

184+
Suppose you want a CSRF token per item, so in the template you have something like the following:
185+
186+
.. code-block:: html+twig
187+
188+
<form action="{{ url('admin_post_delete', { id: post.id }) }}" method="post">
189+
{# the argument of csrf_token() is a dynamic id string used to generate the token #}
190+
<input type="hidden" name="token" value="{{ csrf_token('delete-item-' ~ post.id) }}">
191+
192+
<button type="submit">Delete item</button>
193+
</form>
194+
195+
The :class:`Symfony\\Component\\Security\\Http\\Attribute\\IsCsrfTokenValid`
196+
attribute also accepts an :class:`Symfony\\Component\\ExpressionLanguage\\Expression`
197+
object evaluated to the id::
198+
199+
use Symfony\Component\HttpFoundation\Request;
200+
use Symfony\Component\HttpFoundation\Response;
201+
use Symfony\Component\Security\Http\Attribute\IsCsrfTokenValid;
202+
// ...
203+
204+
#[IsCsrfTokenValid(new Expression('"delete-item-" ~ args["post"].id'), tokenKey: 'token')]
205+
public function delete(Post $post): Response
206+
{
207+
// ... do something, like deleting an object
208+
}
209+
184210
.. versionadded:: 7.1
185211

186212
The :class:`Symfony\\Component\\Security\\Http\\Attribute\\IsCsrfTokenValid`

0 commit comments

Comments
 (0)