我想在 AccessDeniedException 的情况下自定义 Symfony2 的行为。如果引发异常的 HTTP 请求是 XMLHTTPRequest,那么我会回复一个 JSON,否则我会在登录页面生成 302。
这是我的实现。日志显示在 AccessDeniedException 之后永远不会调用 AccessDeneidHandler。我错过了什么?
#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'));
}
}
}