加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

php – symfony2在限制区域没有重定向

发布时间:2020-12-13 18:05:13 所属栏目:PHP教程 来源:网络整理
导读:我的安全文件配置如下: 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: / 目前,如果我访问成员网址而不进行
我的安全文件配置如下:
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: /

目前,如果我访问成员网址而不进行身份验证,它会将我重定向到/ public / login但我不希望它重定向.我主要是在控制器上使用json进行响应,所以我只想在受限制的URL上显示警告,例如{“error”:“Access denied”}.如果我取出login_path:/ public / login代码,它会重定向到默认的url / login.如何阻止它重定向?

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

听众代码 –

namespace YourNameSpaceBundleListener;

use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentSecurityCoreExceptionAuthenticationCredentialsNotFoundException;
use SymfonyComponentSecurityCoreExceptionAuthenticationException;
use SymfonyComponentSecurityCoreExceptionAccessDeniedException;
use SymfonyComponentHttpKernelEventGetResponseForExceptionEvent;

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: YourNameSpaceBundleListenerAjaxAuthenticationListener
    tags:
      - { name: kernel.event_listener,event: kernel.exception,method: onCoreException,priority: 1000 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读