好,調試小時後我發現,這種行爲是在異常監聽硬編碼的安全組件(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 ...拒絕訪問。有點錯誤? –