|
| 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 throw an ``AccessDeniedException`` you can catch this exception |
| 8 | +with a service to return a custom Response. |
| 9 | + |
| 10 | +On each firewall context you can define a 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: custom_handler.service.id |
| 21 | +
|
| 22 | + .. code-block:: php |
| 23 | +
|
| 24 | + // app/config/security.php |
| 25 | + $container->loadFromExtension('security', array( |
| 26 | + 'firewalls' => array( |
| 27 | + 'foo' => array( |
| 28 | + // ... |
| 29 | + 'access_denied_handler' => 'custom_handler.service.id', |
| 30 | + ), |
| 31 | + ), |
| 32 | + )); |
| 33 | +
|
| 34 | +
|
| 35 | +Your handler must implement the interface |
| 36 | +:class:`Symfony\\Component\\Security\\Http\\Authorization\\AccessDeniedHandlerInterface`. |
| 37 | +This interface define one method called ``handle()`` that can do whatever you want. |
| 38 | +You can use it to send a mail, log a message, or generally return a custom Response. |
| 39 | + |
| 40 | + |
| 41 | +.. code-block:: php |
| 42 | +
|
| 43 | + namespace AppBundle\Security; |
| 44 | +
|
| 45 | + use Symfony\Component\Security\Http\Authorization\AccessDeniedHandlerInterface; |
| 46 | + use Symfony\Component\HttpFoundation\Request; |
| 47 | + use Symfony\Component\HttpFoundation\Response; |
| 48 | + use Symfony\Component\Security\Core\Exception\AccessDeniedException; |
| 49 | +
|
| 50 | + class AccessDeniedHandler implements AccessDeniedHandlerInterface |
| 51 | + { |
| 52 | + public function handle(Request $request, AccessDeniedException $accessDeniedException) |
| 53 | + { |
| 54 | + // to some stuff... |
| 55 | + return new Response($content, 403); |
| 56 | + } |
| 57 | + } |
| 58 | +
|
| 59 | +Then you must register your service : |
| 60 | + |
| 61 | +.. code-block:: yml |
| 62 | +
|
| 63 | + # app/config/services.yml |
| 64 | + services: |
| 65 | + custom_handler.service.id: |
| 66 | + class: AppBundle\Security\AccessDeniedHandler |
| 67 | +
|
| 68 | +That's it, now on the ``foo`` firewall, all ``AccessDeniedException`` will be notified to you service. |
0 commit comments