Symfony2:为什么 access_denied_handler 不起作用 [英] Symfony2: why access_denied_handler doesn't work

查看:26
本文介绍了Symfony2:为什么 access_denied_handler 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在出现 AccessDeniedException 的情况下自定义 Symfony2 的行为.如果引发异常的 HTTP 请求是 XMLHTTPRequest,那么我会回复一个 JSON,否则我会在登录页面生成一个 302.

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.

这是我的实现.日志显示 AccessDeneidHandler 永远不会在 AccessDeniedException 之后被调用.我错过了什么?

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'));
    }
}
}

推荐答案

好吧,当我深入研究 ExceptionListener 时,我终于发现了问题所在

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

access_denied_handler 指向的服务只有在用户没有足够的权限访问资源时才会调用.如果用户根本没有经过身份验证,则永远不会调用 access_dened_handler.

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.

security.yml中的entry_point提供服务确实解决了问题.

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

这篇关于Symfony2:为什么 access_denied_handler 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆