@@ -237,22 +237,22 @@ Checking for Roles inside a Voter
237
237
---------------------------------
238
238
239
239
What if you want to call ``isGranted() `` from *inside * your voter - e.g. you want
240
- to see if the current user has ``ROLE_SUPER_ADMIN ``. That's possible by injecting
241
- the :class: `Symfony\\ Bundle \\ SecurityBundle \\ Security `
242
- into your voter. You can use this to, for example, *always * allow access to a user
240
+ to see if the current user has ``ROLE_SUPER_ADMIN ``. That's possible by using an
241
+ :class: `access decision manager < Symfony\\ Component \\ Security \\ Core \\ Authorization \\ AccessDecisionManagerInterface> `
242
+ inside your voter. You can use this to, for example, *always * allow access to a user
243
243
with ``ROLE_SUPER_ADMIN ``::
244
244
245
245
// src/Security/PostVoter.php
246
246
247
247
// ...
248
- use Symfony\Bundle\SecurityBundle\ Security;
248
+ use Symfony\Component\ Security\Core\Authorization\AccessDecisionManagerInterface ;
249
249
250
250
class PostVoter extends Voter
251
251
{
252
252
// ...
253
253
254
254
public function __construct(
255
- private Security $security ,
255
+ private AccessDecisionManagerInterface $accessDecisionManager ,
256
256
) {
257
257
}
258
258
@@ -261,14 +261,33 @@ with ``ROLE_SUPER_ADMIN``::
261
261
// ...
262
262
263
263
// ROLE_SUPER_ADMIN can do anything! The power!
264
- if ($this->security ->isGranted('ROLE_SUPER_ADMIN')) {
264
+ if ($this->accessDecisionManager ->isGranted($token, [ 'ROLE_SUPER_ADMIN'] )) {
265
265
return true;
266
266
}
267
267
268
268
// ... all the normal voter logic
269
269
}
270
270
}
271
271
272
+ .. caution ::
273
+
274
+ In the previous example, avoid using the following code to check if a role
275
+ is granted permission::
276
+
277
+ // DON'T DO THIS
278
+ use Symfony\Component\Security\Core\Security;
279
+ // ...
280
+
281
+ if ($this->security->isGranted('ROLE_SUPER_ADMIN')) {
282
+ // ...
283
+ }
284
+
285
+ The ``Security::isGranted()`` method inside a voter has a significant
286
+ drawback: it does not guarantee that the checks are performed on the same
287
+ token as the one in your voter. The token in the token storage might have
288
+ changed or could change in the meantime. Always use the ``AccessDecisionManager``
289
+ instead.
290
+
272
291
If you're using the :ref: `default services.yaml configuration <service-container-services-load-example >`,
273
292
you're done! Symfony will automatically pass the ``security.helper ``
274
293
service when instantiating your voter (thanks to autowiring).
0 commit comments