@@ -237,22 +237,22 @@ Checking for Roles inside a Voter
237237---------------------------------
238238
239239What 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
243243with ``ROLE_SUPER_ADMIN ``::
244244
245245 // src/Security/PostVoter.php
246246
247247 // ...
248- use Symfony\Bundle\SecurityBundle\ Security;
248+ use Symfony\Component\ Security\Core\Authorization\AccessDecisionManagerInterface ;
249249
250250 class PostVoter extends Voter
251251 {
252252 // ...
253253
254254 public function __construct(
255- private Security $security ,
255+ private AccessDecisionManagerInterface $accessDecisionManager ,
256256 ) {
257257 }
258258
@@ -261,14 +261,33 @@ with ``ROLE_SUPER_ADMIN``::
261261 // ...
262262
263263 // 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'] )) {
265265 return true;
266266 }
267267
268268 // ... all the normal voter logic
269269 }
270270 }
271271
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+
272291If you're using the :ref: `default services.yaml configuration <service-container-services-load-example >`,
273292you're done! Symfony will automatically pass the ``security.helper ``
274293service when instantiating your voter (thanks to autowiring).
0 commit comments