4

I want to customize the behavior of Symfony2 in case of AccessDeniedException. If the HTTP request which raises the exception is an XMLHTTPRequest then I reply with a JSON otherwise I generate a 302 found to the login page.

Here's my implementation. The log shows that AccessDeneidHandler is never called after an AccessDeniedException. What am I missing ?

#security.yml
firewalls:
    secured_area:
        access_denied_handler: kernel.listener.access_denied.handler

#config.yml
kernel.listener.access_denied.handler:
   class: NoaLisa\Bundle\OVMBundle\DependencyInjection\AccessDeniedHandler
     tags:
        - { name: kernel.event_listener, event: security.kernel_response, method: handle}

#AccessDeniedHandler

class AccessDeniedHandler implements AccessDeniedHandlerInterface{

function handle(Request $request, AccessDeniedException $accessDeniedException){

    if ($request->isXmlHttpRequest()) {
        $response = new Response(json_encode(array('status' => 'protected')));
        return $response;
    }
    else {
        return new RedirectResponse($this->router->generate('login'));
    }
}
}
queto putito
  • 253
  • 3
  • 15

1 Answers1

8

Ok finally I found out what was the problem when I dig into ExceptionListener

The service pointed by access_denied_handler is only called if the user has insufficient privilege to access the resource. If the user is not authenticated at all access_dened_handler is never called.

Providing a service to entry_point in security.yml did actually solve the problem.

Darryl Hein
  • 142,451
  • 95
  • 218
  • 261
queto putito
  • 253
  • 3
  • 15
  • 7
    for anyone who found this answer lacking here is the laid out solution: http://stackoverflow.com/questions/17428987/what-is-the-best-way-to-notify-a-user-after-an-access-control-rule-redirects/17432089#17432089 – Carrie Kendall Jul 02 '13 at 17:47
  • I had the same problem when trying to figure out why accessing a controller with @Security("is_granted('IS_AUTHENTICATED_FULLY')") was not triggering the handler when $this->isGranted('IS_AUTHENTICATED_REMEMBERED') was true. So the handler is also not called for users authenticated from REMEMBER_ME and accessing resources requiring full authentication. Thanks! – Mateusz Nov 16 '17 at 23:52