@@ -113,35 +113,34 @@ CSRF Protection
113
113
~~~~~~~~~~~~~~~
114
114
115
115
Protection 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::
118
121
119
122
use Symfony\Component\Form\Forms;
120
- use Symfony\Component\Form\Extension\Csrf\CsrfExtension;
121
- use Symfony\Component\Form\Extension\Csrf\CsrfProvider\SessionCsrfProvider;
122
123
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;
126
128
127
129
// create a Session object from the HttpFoundation component
128
130
$session = new Session();
129
131
130
- $csrfProvider = new SessionCsrfProvider($session, $csrfSecret);
132
+ $csrfGenerator = new UriSafeTokenGenerator();
133
+ $csrfStorage = new SessionTokenStorage($session);
134
+ $csrfManager = new CsrfTokenManager($csrfGenerator, $csrfStorage);
131
135
132
136
$formFactory = Forms::createFormFactoryBuilder()
133
137
// ...
134
- ->addExtension(new CsrfExtension($csrfProvider ))
138
+ ->addExtension(new CsrfExtension($csrfStorage ))
135
139
->getFormFactory();
136
140
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
-
142
141
Internally, 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.
145
144
146
145
.. tip ::
147
146
@@ -151,7 +150,8 @@ and validated when binding the form.
151
150
152
151
use Symfony\Component\Security\Csrf\TokenStorage\NativeSessionTokenStorage;
153
152
154
- $csrfProvider = new NativeSessionTokenStorage();
153
+ $csrfStorage = new NativeSessionTokenStorage();
154
+ // ...
155
155
156
156
Twig Templating
157
157
~~~~~~~~~~~~~~~
0 commit comments