@@ -2576,6 +2576,34 @@ the built-in ``is_granted_for_user()`` helper function:
25762576 <a href="...">Delete</a>
25772577 {% endif %}
25782578
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+
25792607.. _security-isgrantedforuser :
25802608
25812609Securing other Services
@@ -2622,6 +2650,37 @@ want to include extra details only for users that have a ``ROLE_SALES_ADMIN`` ro
26222650 is unavailable (e.g., in a CLI context such as a message queue or cron job), you
26232651 can use the ``isGrantedForUser() `` method to explicitly set the target user.
26242652
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+
26252684If you're using the :ref: `default services.yaml configuration <service-container-services-load-example >`,
26262685Symfony will automatically pass the ``security.helper `` to your service
26272686thanks to autowiring and the ``Security `` type-hint.
0 commit comments