我'd like to use the @Security annotation for controller actions which should be called by ajax requests. Problem is, if I use 2990962 for the firewall in security.yml and the the action is called by a user who is not logged in, symfony intercepts the response and sends a 302 redirect to the configured login page. Since it'是一个ajax请求,302重定向在这里没有意义 . 是否有(简单)方法将"form_login"的行为更改为不发送302重定向但是将401代码发送回客户端(ajax)?我可以找到很多关于如何为$ request-> isXmlHttpRequest()覆盖AuthenticationSuccessHandler和AuthenticationFaliureHandler的信息,如:http://www.webtipblog.com/adding-an-ajax-login-form-to-a-symfony-project/
但这只是其中的一部分,这样您就可以避免在用户提交表单时获得重定向 . 但我想做的是不仅在他已经尝试登录时向客户端发回401,而且由于@Security注释或“access_control”配置而不是将用户重定向到登录表单URL .
我现在该怎么做:
class AjaxController extends Controller
{
/**
* @Route("/ajax/task/save")
*/
public function ajaxAction()
{
$user = $this->getUser();
if (!$user) {
// load login-form in JS code
return new JsonResponse(array('authenticated'=> false), 401);
}
// do...
}
}
但我想做的是:
class AjaxController extends Controller
{
/**
* @Route("/ajax/task/save")
* @Security("has_role('ROLE_USER')")
*/
public function ajaxAction()
{
// do...
}
}
但是这样我必须确保不会将重定向到登录表单的302发送到客户端,而是像我之前的示例中的JsonResponse .
How can I do this?
1 回答
如果我理解您正在寻找的内容,您应该能够创建一个自定义异常监听器,该异常监听器在Symfony重定向用户之前根据内容类型标头和您喜欢的任何状态代码返回JSON响应 .
http://symfony.com/doc/current/cookbook/service_container/event_listener.html