Skip to content

Commit f35eec7

Browse files
committed
feature #19870 [Security] Add support for dynamic CSRF id with 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 #19753 Commits ------- e0a49ba [Security] Add support for dynamic CSRF id with Expression in `#[IsCsrfTokenValid]`
2 parents 8c17143 + e0a49ba commit f35eec7

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
@@ -213,6 +213,32 @@ attribute on the controller action::
213213
// ... do something, like deleting an object
214214
}
215215

216+
Suppose you want a CSRF token per item, so in the template you have something like the following:
217+
218+
.. code-block:: html+twig
219+
220+
<form action="{{ url('admin_post_delete', { id: post.id }) }}" method="post">
221+
{# the argument of csrf_token() is a dynamic id string used to generate the token #}
222+
<input type="hidden" name="token" value="{{ csrf_token('delete-item-' ~ post.id) }}">
223+
224+
<button type="submit">Delete item</button>
225+
</form>
226+
227+
The :class:`Symfony\\Component\\Security\\Http\\Attribute\\IsCsrfTokenValid`
228+
attribute also accepts an :class:`Symfony\\Component\\ExpressionLanguage\\Expression`
229+
object evaluated to the id::
230+
231+
use Symfony\Component\HttpFoundation\Request;
232+
use Symfony\Component\HttpFoundation\Response;
233+
use Symfony\Component\Security\Http\Attribute\IsCsrfTokenValid;
234+
// ...
235+
236+
#[IsCsrfTokenValid(new Expression('"delete-item-" ~ args["post"].id'), tokenKey: 'token')]
237+
public function delete(Post $post): Response
238+
{
239+
// ... do something, like deleting an object
240+
}
241+
216242
.. versionadded:: 7.1
217243

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

0 commit comments

Comments
 (0)