Uncategorized

Correct messages during incorrect login in your website

By default, regardless of whether the user does not exist, we entered the wrong password or the blocked message always looks the same:

{
    "code": 401,
    "message": "Bad credentials"
}

You can easily get the exact message about the error, just register a simple subscriber that will enter the message from the first exception that occurred (the first exception probably comes from FosUser and contains the first user validation error which contains the exact error message)

<?php


namespace App\Event\Subscriber;


use Lexik\Bundle\JWTAuthenticationBundle\Event\AuthenticationFailureEvent;
use Lexik\Bundle\JWTAuthenticationBundle\Events;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class AuthenticationFailureSubscriber implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            Events::AUTHENTICATION_FAILURE => 'onAuthenticationFailure'
        ];
    }

    public function onAuthenticationFailure(AuthenticationFailureEvent $event) {
        $firstEvent = $event->getException();
        while($firstEvent->getPrevious()) {
            $firstEvent = $firstEvent->getPrevious();
        }
        $response = $event->getResponse();
        $response->setMessage($firstEvent->getMessage());
        $event->setResponse($response);
    }
}

Thanks to this we get responses like:

{
    "code": 401,
    "message": "The presented password is invalid."
}
{
    "code": 401,
    "message": "User account is disabled."
}
{
    "code": 401,
    "message": "Username \"admsin\" does not exist."
}
PREV POST Black hole. REST API and WORDPRESS
NEXT POST Black hole. REST API and WORDPRESS

Let's talk

We can help to make your idea come true, just drop us a line. If you want to join our team don’t wait. We are always looking for a talents!

PREV POST Black hole. REST API and WORDPRESS
NEXT POST Black hole. REST API and WORDPRESS
Website development Lublin

Something went wrong

Probably Charles broke something.
Please try again. Sorry!