2013-03-25 201 views
3

对于我的Web服务使用FOSRestBundle,我创建了一个防火墙,强制登录访问应用程序。Symfony2防火墙和FOSRestBundle

我的问题是,当我通过ajax调用API时,我需要得到错误代码401,当用户没有通过身份验证,而不是接收登录表单的html源代码。我如何配置应用程序?

secured_area: 
      pattern: ^/ 
      form_login: 
       provider: fos_userbundle 
       use_forward: false 
       default_target_path: /w 
      logout: 
       path: /logout 
       target: /login 

编辑:

感谢瑞安这里是KernelExceptionListener方法。

public function onKernelException(GetResponseForExceptionEvent $event) { 
    // get exception 
    $exception = $event->getException(); 
    // get path 
    $path = $event->getRequest()->getPathInfo(); 

    if ($exception instanceOf AuthenticationException && ($event->getRequest()->isXmlHttpRequest() || strpos($path, '/api') === 0)) { 
     $response = new Response(); 
     $response->setStatusCode(401); 
     $event->setResponse($response); 
     $event->stopPropagation(); 
    } 
} 
+1

很高兴你的工作。我在FOSRestBundle#411上创建了一个新问题,希望能够将此功能作为该包的一部分提供。 https://github.com/FriendsOfSymfony/FOSRestBundle/issues/411 – Ryan 2013-03-26 22:02:07

回答

2

您使用了验证字而不是授权字,不幸的是,这似乎没有写入。因此,您可能需要创建自己的。

在一般情况下,应该创建一个简单的Kernel Event listener来拦截AuthenticationException异常。捕获此事件应允许您在重定向到登录页面之前执行任何您喜欢的操作。

FOSRestBundle应该提供一个很好的例子来说明如何做到这一点。 FOSRestBundle目前为授权层提供此功能(AccessDeniedException)。通过一点点的修改,同一个框架也应该为身份验证层提供相同的功能。

请参阅拉#308以获得提供授权侦听器的更改集。 有关如何配置侦听器的文档,请参阅Security Exception Listener