Skip to content

How to Create a Custom Access Denied Handler

Warning: You are browsing the documentation for Symfony 2.x, which is no longer maintained.

Read the updated version of this page for Symfony 7.2 (the current stable version).

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:

1
2
3
4
5
# app/config/security.yml
firewalls:
    foo:
        # ...
        access_denied_handler: app.security.access_denied_handler

Your handler must implement the 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):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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:

1
2
3
4
# 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.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version