8000 Add documentation to overwrite token widget block using esi by alexander-schranz · Pull Request #10867 · symfony/symfony-docs · GitHub
[go: up one dir, main page]

Skip to content

Add documentation to overwrite token widget block using esi #10867

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

Closed
wants to merge 5 commits into from
Closed
Changes from 1 commit
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
Next Next commit
Add documentation to overwrite token widget block using esi
  • Loading branch information
alexander-schranz authored Jan 12, 2019
commit 7226f6cecfb00f18e851b7081c4f3d711803934a
29 changes: 28 additions & 1 deletion http_cache/form_csrf_caching.rst
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,32 @@ How to Cache Most of the Page and still be able to Use CSRF Protection

To cache a page that contains a CSRF token, you can use more advanced caching
techniques like :doc:`ESI fragments </http_cache/esi>`, where you cache the full
page and embedding the form inside an ESI tag with no cache at all.
page and embedding the form inside an ESI tag with no cache at all. When you
have your custom form theme you can do this by create a new token_widget block
and call render_esi there:

.. code-block:: twig

{%- block token_widget %}
{{ render_esi(controller('App\\Controller\\FormController::token', { 'form': form.parent.vars.name })) }}
{%- endblock token_widget -%}

You can use the ``security.csrf.token_manager`` service to generate a token for your given form:

.. code-block:: php

public function token(Request $request, TokenGeneratorInterface $generator)
{
$formName = $request->attributes->get('form');
$csrfToken = $csrfTokenManager->getToken($formName)->getValue();

return new Response(sprintf(
'<input type="hidden" id="%s__token" name="%s[_token]" value="%s" />',
$formName,
$formName,
$csrfToken
));
}

Another option would be to load the form via an uncached AJAX request, but
cache the rest of the HTML response.
Expand All @@ -39,5 +64,7 @@ Or you can even load just the CSRF token with an AJAX request and replace the
form field value with it. Take a look at :doc:`hinclude.js </templating/hinclude>`
for a nice solution.



.. _`Cross-site request forgery`: http://en.wikipedia.org/wiki/Cross-site_request_forgery
.. _`Security CSRF Component`: https://github.com/symfony/security-csrf
0