使用symfony2处理身份验证异常

时间:2015-12-09 11:42:29

标签: php symfony

我想通过一个API向我的客户端返回一个类似return new Response('authentication faild');的适当消息,但它的行为并不像以下代码那样;

try{
        $token = $this->get('security.authentication.manager')
                      ->authenticate(new UsernamePasswordToken($username, $password, 'main'));
        $this->get('security.context')->setToken($token);
    }
    catch (BadCredentialsException $e){
        return new Response('authentication faild', 403);
    }

返回的错误是登录表单的html / css ...代码

1 个答案:

答案 0 :(得分:3)

看看这个:

<?php

namespace YourBundle\EventListener;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;

class CatchErrorsEventSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return ["kernel.exception" => ['catchException', 200]];
    }

    /**
     * @param GetResponseForExceptionEvent $evt
     */
    public function catchException(GetResponseForExceptionEvent $evt)
    {
        $request = $evt->getRequest()->getRequestFormat('json');

        if($request != 'json') {
            return;
        }

        $response = $evt->getResponse() ?: new Response();
        $evt->stopPropagation();  // stop the other listener to redirect to login
        $evt->setResponse($response);
    }
}

此侦听器将捕获异常,您可以按所需方式发送响应。仅在此示例中,如果请求是json请求。

不要忘记将订户注册为服务:

    <service class="YourBundle\EventListener\CatchErrorsEventSubscriber" id="your_bundle.catch_error_event_subscriber">
        <tag name="kernel.event_subscriber"/>
    </service>