繁体   English   中英

捕获AccountStatusException

[英]Catch AccountStatusException

我想为实现AdvancedUserInterface的用户实现自定义逻辑

我想允许未启用权限的用户访问某些区域(例如帐户区域,如果他们输入错误,他们可以在其中更改电子邮件)。

根据文档:

如果此接口中的任何方法返回false,则身份验证将失败。

如果您需要针对这些情况中的任何一种执行自定义逻辑,则将需要注册一个异常侦听器,并注意每种情况下抛出的特定异常实例。 所有异常都是AccountStatusException的子类

因此,我尝试通过使本食谱文章适应安全事件来创建侦听器:

<?php

namespace Acme\DemoBundle\Listener;


use Symfony\Component\Security\Core\SecurityContextInterface;

use Symfony\Component\Security\Core\Exception\AccountStatusException;

class NecdocPatientExceptionListener
{
    public function onKernelException($event)
    {
        // Handle event code goes here
    }
}

并且我已将其添加到捆绑包的services.xml中:

services:
    kernel.listener.acme_user_exception_listener:
        class: Acme\DemoBundle\Listener\AcmeExceptionListener
        tags:
            - { name: kernel.event_listener, event: security.authentication.success, method: onKernelException }

这捕获AuthenticationFailureEvent (调用onKernelException),但不捕获AccountStatusException (不调用onKernelException)

我一直在寻找“安全性”组件代码,而且似乎在不触发任何事件的情况下捕获了异常。 无论如何,有没有办法捕捉那些异常?

namespace Acme\DemoBundle\Listener;

use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccountStatusException;

class AcmeExceptionListener
{
    public function onKernelException(GetResponseForExceptionEvent $event)
    {
        // We get the exception object from the received event
        $exception = $event->getException();
        $message = 'My Error says: ' . $exception->getMessage() . ' with code: ' . $exception->getCode();

        // Customize our response object to display our exception details
        $response = new Response();
        $response->setContent($message);

        // Checks that the exception is an account status exception
        if ($exception instanceof AccountStatusException) {
            $response->setStatusCode($exception->getStatusCode());
            $response->headers->replace($exception->getHeaders());
        } else {
            $response->setStatusCode(500);
        }

        // Send our modified response object to the event
        $event->setResponse($response);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM