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