使用symfony2处理身份验证异常


handle authentication exception with symfony2

我只想通过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。。。登录表单的代码

看看这个:

<?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>