|
| 1 | +.. index:: |
| 2 | + single: Security; Creating a Custom Access Denied Handler |
| 3 | + |
| 4 | +How to Create a Custom Access Denied Handler |
| 5 | +============================================ |
| 6 | + |
| 7 | +When your application throws an ``AccessDeniedException``, you can handle this exception |
| 8 | +with a service to return a custom response. |
| 9 | + |
| 10 | +Each firewall context can define its own custom access denied handler: |
| 11 | + |
| 12 | +.. configuration-block:: |
| 13 | + |
| 14 | + .. code-block:: yaml |
| 15 | +
|
| 16 | + # app/config/security.yml |
| 17 | + firewalls: |
| 18 | + foo: |
| 19 | + # ... |
| 20 | + access_denied_handler: app.security.access_denied_handler |
| 21 | +
|
| 22 | + .. code-block:: xml |
| 23 | +
|
| 24 | + <config> |
| 25 | + <firewall name="foo"> |
| 26 | + <access_denied_handler>app.security.access_denied_handler</access_denied_handler> |
| 27 | + </firewall> |
| 28 | + </config> |
| 29 | +
|
| 30 | + .. code-block:: php |
| 31 | +
|
| 32 | + // app/config/security.php |
| 33 | + $container->loadFromExtension('security', array( |
| 34 | + 'firewalls' => array( |
| 35 | + 'foo' => array( |
| 36 | + // ... |
| 37 | + 'access_denied_handler' => 'app.security.access_denied_handler', |
| 38 | + ), |
| 39 | + ), |
| 40 | + )); |
| 41 | +
|
| 42 | +
|
| 43 | +Your handler must implement the |
| 44 | +:class:`Symfony\\Component\\Security\\Http\\Authorization\\AccessDeniedHandlerInterface`. |
| 45 | +This interface defines one method called ``handle()`` that implements the logic to |
| 46 | +execute when access is denied to the current user (send a mail, log a message, or |
| 47 | +generally return a custom response). |
| 48 | + |
| 49 | +.. code-block:: php |
| 50 | +
|
| 51 | + namespace AppBundle\Security; |
| 52 | +
|
| 53 | + use Symfony\Component\HttpFoundation\Request; |
| 54 | + use Symfony\Component\HttpFoundation\Response; |
| 55 | + use Symfony\Component\Security\Core\Exception\AccessDeniedException; |
| 56 | + use Symfony\Component\Security\Http\Authorization\AccessDeniedHandlerInterface; |
| 57 | +
|
| 58 | + class AccessDeniedHandler implements AccessDeniedHandlerInterface |
| 59 | + { |
| 60 | + public function handle(Request $request, AccessDeniedException $accessDeniedException) |
| 61 | + { |
| 62 | + // ... |
| 63 | +
|
| 64 | + return new Response($content, 403); |
| 65 | + } |
| 66 | + } |
| 67 | +
|
| 68 | +Then, register the service for the access denied handler: |
| 69 | + |
| 70 | +.. code-block:: yaml |
| 71 | +
|
| 72 | + # app/config/services.yml |
| 73 | + services: |
| 74 | + app.security.access_denied_handler: |
| 75 | + class: AppBundle\Security\AccessDeniedHandler |
| 76 | +
|
| 77 | +That's it! Any ``AccessDeniedException`` thrown by the ``foo`` firewall will now be handled by your service. |
0 commit comments