@@ -9,27 +9,56 @@ Using Expressions in Security Access Controls
99 The best solution for handling complex authorization rules is to use
1010 the :doc: `Voter System </security/voters >`.
1111
12- In addition to a role like ``ROLE_ADMIN ``, the ``isGranted() `` method also
13- accepts an :class: `Symfony\\ Component\\ ExpressionLanguage\\ Expression ` object::
12+ In addition to security roles like ``ROLE_ADMIN ``, the ``isGranted() `` method
13+ and ``#[IsGranted()] `` attribute also accept an
14+ :class: `Symfony\\ Component\\ ExpressionLanguage\\ Expression ` object:
1415
15- // src/Controller/MyController.php
16- namespace App\Controller;
16+ .. configuration-block ::
1717
18- use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
19- use Symfony\Component\ExpressionLanguage\Expression;
20- use Symfony\Component\HttpFoundation\Response;
18+ .. code-block :: php-attributes
2119
22- class MyController extends AbstractController
23- {
24- public function index(): Response
20+ // src/Controller/MyController.php
21+ namespace App\Controller;
22+
23+ use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
24+ use Symfony\Component\ExpressionLanguage\Expression;
25+ use Symfony\Component\HttpFoundation\Response;
26+
27+ class MyController extends AbstractController
2528 {
26- $this->denyAccessUnlessGranted (new Expression(
29+ #[IsGranted (new Expression(
2730 '"ROLE_ADMIN" in role_names or (is_authenticated() and user.isSuperAdmin())'
28- ));
31+ ))]
32+ public function index(): Response
33+ {
34+ // ...
35+ }
36+ }
37+
38+ .. code-block :: php
2939
30- // ...
40+ // src/Controller/MyController.php
41+ namespace App\Controller;
42+
43+ use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
44+ use Symfony\Component\ExpressionLanguage\Expression;
45+ use Symfony\Component\HttpFoundation\Response;
46+
47+ class MyController extends AbstractController
48+ {
49+ public function index(): Response
50+ {
51+ $this->denyAccessUnlessGranted(new Expression(
52+ '"ROLE_ADMIN" in role_names or (is_authenticated() and user.isSuperAdmin())'
53+ ));
54+
55+ // ...
56+ }
3157 }
32- }
58+
59+ .. versionadded :: 6.2
60+
61+ The ``#[IsGranted()] `` attribute was introduced in Symfony 6.2.
3362
3463In this example, if the current user has ``ROLE_ADMIN `` or if the current
3564user object's ``isSuperAdmin() `` method returns ``true ``, then access will
0 commit comments