diff --git a/security.rst b/security.rst index 2c7686c7e50..99c4956d9a6 100644 --- a/security.rst +++ b/security.rst @@ -1295,6 +1295,7 @@ Authorization (Denying Access) security/force_https security/securing_services security/access_control + security/access_denied_handler Other Security Related Topics ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/security/access_denied_handler.rst b/security/access_denied_handler.rst new file mode 100644 index 00000000000..c7b63a67592 --- /dev/null +++ b/security/access_denied_handler.rst @@ -0,0 +1,77 @@ +.. index:: + single: Security; Creating a Custom Access Denied Handler + +How to Create a Custom Access Denied Handler +============================================ + +When your application throws an ``AccessDeniedException``, you can handle this exception +with a service to return a custom response. + +Each firewall context can define its own custom access denied handler: + +.. configuration-block:: + + .. code-block:: yaml + + # app/config/security.yml + firewalls: + foo: + # ... + access_denied_handler: app.security.access_denied_handler + + .. code-block:: xml + + + + app.security.access_denied_handler + + + + .. code-block:: php + + // app/config/security.php + $container->loadFromExtension('security', array( + 'firewalls' => array( + 'foo' => array( + // ... + 'access_denied_handler' => 'app.security.access_denied_handler', + ), + ), + )); + + +Your handler must implement the +:class:`Symfony\\Component\\Security\\Http\\Authorization\\AccessDeniedHandlerInterface`. +This interface defines one method called ``handle()`` that implements the logic to +execute when access is denied to the current user (send a mail, log a message, or +generally return a custom response). + +.. code-block:: php + + namespace AppBundle\Security; + + use Symfony\Component\HttpFoundation\Request; + use Symfony\Component\HttpFoundation\Response; + use Symfony\Component\Security\Core\Exception\AccessDeniedException; + use Symfony\Component\Security\Http\Authorization\AccessDeniedHandlerInterface; + + class AccessDeniedHandler implements AccessDeniedHandlerInterface + { + public function handle(Request $request, AccessDeniedException $accessDeniedException) + { + // ... + + return new Response($content, 403); + } + } + +Then, register the service for the access denied handler: + +.. code-block:: yaml + + # app/config/services.yml + services: + app.security.access_denied_handler: + class: AppBundle\Security\AccessDeniedHandler + +That's it! Any ``AccessDeniedException`` thrown by the ``foo`` firewall will now be handled by your service.