symfony2限制区域没有重定向


symfony2 No redirect on restricted areas

我的安全文件配置如下:

security:
...
            pattern:    ^/[members|admin]
            form_login:
                check_path: /members/auth
                login_path: /public/login
                failure_forward: false
                failure_path: null
            logout:
                path:   /public/logout
                target: /

目前,如果我在未经身份验证的情况下访问成员url,它会将我重定向到/public/login,但我不希望它重定向。我主要在控制器上使用json进行响应,所以我只想在受限制的url(如{"error": "Access denied"})上显示一个警告。如果我去掉login_path: /public/login代码,它会重定向到默认的url/login。我该如何阻止它重定向?

您需要创建一个监听器,然后触发响应。我的解决方案基于-https://gist.github.com/xanf/1015146

侦听器代码——

namespace Your'NameSpace'Bundle'Listener;
use Symfony'Component'HttpFoundation'JsonResponse;
use Symfony'Component'Security'Core'Exception'AuthenticationCredentialsNotFoundException;
use Symfony'Component'Security'Core'Exception'AuthenticationException;
use Symfony'Component'Security'Core'Exception'AccessDeniedException;
use Symfony'Component'HttpKernel'Event'GetResponseForExceptionEvent;
class AjaxAuthenticationListener
{
/**
 * Handles security related exceptions.
 *
 * @param GetResponseForExceptionEvent $event An GetResponseForExceptionEvent instance
 */
public function onCoreException(GetResponseForExceptionEvent $event)
{
    $exception = $event->getException();
    $request = $event->getRequest();
    if ($request->isXmlHttpRequest()) {
        if ($exception instanceof AuthenticationException || $exception instanceof AccessDeniedException || $exception instanceof AuthenticationCredentialsNotFoundException) {
            $responseData = array('status' => 401, 'msg' => 'User Not Authenticated');
            $response = new JsonResponse();
            $response->setData($responseData);
            $response->setStatusCode($responseData['status']);
            $event->setResponse($response);
        }
    }
}
}

您需要为侦听器创建一个服务——

e_ent_int_baems.ajaxauthlistener:
    class: Your'NameSpace'Bundle'Listener'AjaxAuthenticationListener
    tags:
      - { name: kernel.event_listener, event: kernel.exception, method: onCoreException, priority: 1000 }

你可以像我一样:yml

firewalls:
        administrators:
            pattern: ^/
            form_login:
                check_path:  _security_check
                login_path:  _security_login
            logout: true
            security: true
            anonymous: true
            access_denied_url: access_denied

在路由中。yml

access_denied:
    path: /error403
    defaults :
        _controller: FrameworkBundle:Template:template
        template: 'DpUserBundle:Static:error403.html.twig'

只需添加到防火墙部分*access_denied_url*param

有关完整的security.yml配置参考,请参阅本页。此外,这是一个更好的参考,每个键的解释。

我建议您创建自己的侦听器类,以便在用户需要登录时处理返回的JSON。示例:https://gist.github.com/1015146