简体   繁体   中英

handle authentication exception with symfony2

I'd like simply return an apropriate message like return new Response('authentication faild'); to my client throught an API but it doesn't behave as it suppose to be as in the following code

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);
    }

The error returned is the html/css ... code of the login form

Look at this:

<?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);
    }
}

This listener will catch the exception and you can send a response your desired way. In this example only if the request is a json request.

Don't forget to register the subscriber as a service:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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