好,调试小时后我发现,这种行为是在异常监听硬编码的安全组件(Symfony \ Component \ Security \ Http \ Firewall \ ExceptionListener)。
所以我不得不写我自己的ExceptionListener,与onKernelException方法:
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
do {
if ($exception instanceof AccessDeniedException) {
if(substr($event->getRequest()->server->get('PATH_INFO'), 0, 4) == '/api') {
$event->setException(new AjaxAccessDeniedException());
}
}
} while (null !== $exception = $exception->getPrevious());
}
来检查,如果路径始于/ API,并抛出自己的AjaxAccessDeniedException。 此异常具有与AccessDeniedException相同的代码,但不会继承它(因为否则它将再次被安全组件ExceptionListener捕获)。这个我可以在异常控制器中捕获,因为它不会在其他地方被捕获。
最后一步是将我的ExceptionListener注册为服务,但具有比默认更高的优先级。
my.exception_listener:
class: Acme\MyBundle\EventListener\ExceptionListener
arguments: [@security.context, @security.authentication.trust_resolver]
tags:
- { name: kernel.event_listener, event: kernel.exception, priority: 256 }
您是否在模板中使用了'{%if is_granted('...')%}'或者{%if app.user和is_granted('...')%}'? –
我使用 @Security(“has_role('...')”)和 @Security(“is_granted(...)”) 直接在控制器操作 – user2534194
因此,您得到一个'Expression ...拒绝访问。有点错误? –