@@ -9,27 +9,56 @@ Using Expressions in Security Access Controls
9
9
The best solution for handling complex authorization rules is to use
10
10
the :doc: `Voter System </security/voters >`.
11
11
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:
14
15
15
- // src/Controller/MyController.php
16
- namespace App\Controller;
16
+ .. configuration-block ::
17
17
18
- use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
19
- use Symfony\Component\ExpressionLanguage\Expression;
20
- use Symfony\Component\HttpFoundation\Response;
18
+ .. code-block :: php-attributes
21
19
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
25
28
{
26
- $this->denyAccessUnlessGranted (new Expression(
29
+ #[IsGranted (new Expression(
27
30
'"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
29
39
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
+ }
31
57
}
32
- }
58
+
59
+ .. versionadded :: 6.2
60
+
61
+ The ``#[IsGranted()] `` attribute was introduced in Symfony 6.2.
33
62
34
63
In this example, if the current user has ``ROLE_ADMIN `` or if the current
35
64
user object's ``isSuperAdmin() `` method returns ``true ``, then access will
0 commit comments