@@ -2576,6 +2576,34 @@ the built-in ``is_granted_for_user()`` helper function:
2576
2576
<a href="...">Delete</a>
2577
2577
{% endif %}
2578
2578
2579
+ Symfony also provides the ``access_decision() `` and ``access_decision_for_user() ``
2580
+ Twig functions to check authorization and to retrieve the reasons for denying
2581
+ permission in :ref: `your custom security voters <creating-the-custom-voter >`:
2582
+
2583
+ .. code-block :: html+twig
2584
+
2585
+ {% set voter_decision = access_decision('post_edit', post) %}
2586
+ {% if voter_decision.isGranted() %}
2587
+ {# ... #}
2588
+ {% else %}
2589
+ {# before showing voter messages to end users, make sure it's safe to do so #}
2590
+ <p>{{ voter_decision.message }}</p>
2591
+ {% endif %}
2592
+
2593
+ {% set voter_decision = access_decision('post_edit', post, anotherUser) %}
2594
+ {% if voter_decision.isGranted() %}
2595
+ {# ... #}
2596
+ {% else %}
2597
+ <p>The {{ anotherUser.name }} user doesn't have sufficient permission:</p>
2598
+ {# before showing voter messages to end users, make sure it's safe to do so #}
2599
+ <p>{{ voter_decision.message }}</p>
2600
+ {% endif %}
2601
+
2602
+ .. versionadded :: 7.4
2603
+
2604
+ The ``access_decision() `` and ``access_decision_for_user() `` Twig functions
2605
+ were introduced in Symfony 7.4.
2606
+
2579
2607
.. _security-isgrantedforuser :
2580
2608
2581
2609
Securing other Services
@@ -2622,6 +2650,37 @@ want to include extra details only for users that have a ``ROLE_SALES_ADMIN`` ro
2622
2650
is unavailable (e.g., in a CLI context such as a message queue or cron job), you
2623
2651
can use the ``isGrantedForUser() `` method to explicitly set the target user.
2624
2652
2653
+ You can also use the ``getAccessDecision() `` and ``getAccessDecisionForUser() ``
2654
+ methods to check authorization and get to retrieve the reasons for denying
2655
+ permission in :ref: `your custom security voters <creating-the-custom-voter >`::
2656
+
2657
+ // src/SalesReport/SalesReportManager.php
2658
+
2659
+ // ...
2660
+ use Symfony\Bundle\SecurityBundle\Security;
2661
+
2662
+ class SalesReportManager
2663
+ {
2664
+ public function __construct(
2665
+ private Security $security,
2666
+ ) {
2667
+ }
2668
+
2669
+ public function generateReport(): void
2670
+ {
2671
+ $voterDecision = $this->security->getAccessDecision('ROLE_SALES_ADMIN');
2672
+ if ($voterDecision->isGranted('ROLE_SALES_ADMIN')) {
2673
+ // ...
2674
+ } else {
2675
+ // do something with $voterDecision->getMessage()
2676
+ }
2677
+
2678
+ // ...
2679
+ }
2680
+
2681
+ // ...
2682
+ }
2683
+
2625
2684
If you're using the :ref: `default services.yaml configuration <service-container-services-load-example >`,
2626
2685
Symfony will automatically pass the ``security.helper `` to your service
2627
2686
thanks to autowiring and the ``Security `` type-hint.
0 commit comments