Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

symfony - Symfony2: why access_denied_handler doesn't work

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: NoaLisaBundleOVMBundleDependencyInjectionAccessDeniedHandler
     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'));
    }
}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...