@@ -113,35 +113,34 @@ CSRF Protection
113113~~~~~~~~~~~~~~~
114114
115115Protection against CSRF attacks is built into the Form component, but you need
116- to explicitly enable it or replace it with a custom solution. The following
117- snippet adds CSRF protection to the form factory::
116+ to explicitly enable it or replace it with a custom solution. If you want to
117+ use the built-in support, require the Security CSRF component by executing
118+ ``composer require symfony/security-csrf ``.
119+
120+ The following snippet adds CSRF protection to the form factory::
118121
119122 use Symfony\Component\Form\Forms;
120- use Symfony\Component\Form\Extension\Csrf\CsrfExtension;
121- use Symfony\Component\Form\Extension\Csrf\CsrfProvider\SessionCsrfProvider;
122123 use Symfony\Component\HttpFoundation\Session\Session;
123-
124- // generate a CSRF secret from somewhere
125- $csrfSecret = '<generated token>';
124+ use Symfony\Component\Security\Extension\Csrf\CsrfExtension;
125+ use Symfony\Component\Security\Csrf\TokenStorage\SessionTokenStorage;
126+ use Symfony\Component\Security\Csrf\TokenGenerator\UriSafeTokenGenerator;
127+ use Symfony\Component\Security\Csrf\CsrfTokenManager;
126128
127129 // create a Session object from the HttpFoundation component
128130 $session = new Session();
129131
130- $csrfProvider = new SessionCsrfProvider($session, $csrfSecret);
132+ $csrfGenerator = new UriSafeTokenGenerator();
133+ $csrfStorage = new SessionTokenStorage($session);
134+ $csrfManager = new CsrfTokenManager($csrfGenerator, $csrfStorage);
131135
132136 $formFactory = Forms::createFormFactoryBuilder()
133137 // ...
134- ->addExtension(new CsrfExtension($csrfProvider ))
138+ ->addExtension(new CsrfExtension($csrfStorage ))
135139 ->getFormFactory();
136140
137- To secure your application against CSRF attacks, you need to define a CSRF
138- secret. Generate a random string with at least 32 characters, insert it in the
139- above snippet and make sure that nobody except your web server can access
140- the secret.
141-
142141Internally, this extension will automatically add a hidden field to every
143- form (called ``_token `` by default) whose value is automatically generated
144- and validated when binding the form.
142+ form (called ``_token `` by default) whose value is automatically generated by
143+ the CSRF generator and validated when binding the form.
145144
146145.. tip ::
147146
@@ -151,7 +150,8 @@ and validated when binding the form.
151150
152151 use Symfony\Component\Security\Csrf\TokenStorage\NativeSessionTokenStorage;
153152
154- $csrfProvider = new NativeSessionTokenStorage();
153+ $csrfStorage = new NativeSessionTokenStorage();
154+ // ...
155155
156156Twig Templating
157157~~~~~~~~~~~~~~~
0 commit comments