1

I'm using Symfony 5.4 as REST API.

I would like to override this class :(Symfony\Component\Security\Core\Exception\BadCredentialsException)

<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Symfony\Component\Security\Core\Exception;

/**
 * BadCredentialsException is thrown when the user credentials are invalid.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Alexander <iam.asm89@gmail.com>
 */
class BadCredentialsException extends AuthenticationException
{
    /**
     * {@inheritdoc}
     */
    public function getMessageKey()
    {
        return 'Invalid credentials.';
    }
}

By my custom class :

<?php
declare(strict_types=1);

namespace App\Exception;

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


class BadCredentialsException extends AuthenticationException
{
    /**
     * {@inheritdoc}
     */
    public function getMessageKey()
    {
        return 'Invalid custom message';
    }
}

I think the best way is to use a decorator but i can't achieve that.

Thank you for your help

  • It seems like [this answer](https://stackoverflow.com/a/58806137/8993284) is applicable for overriding any file via Composer. – Michel Rummens Oct 06 '22 at 09:13
  • I don't think is a good answer.. What's happen if you delete the vendor and forget to remove these lines.. I need to remplace more than one exception Thanks for the reply – Yohann Daniel Carter Oct 06 '22 at 13:29

1 Answers1

2

I got the same issue and i solved it thanks to this solution :

In service.yml :

App\EventListener\AuthenticationFailureListener:    
     tags: - { name: kernel.event_listener, event: lexik_jwt_authentication.on_authentication_failure, method: onAuthenticationFailureResponse }

And the listener :

<?php

class authenticationfailurelistener
{
    public function onauthenticationfailureresponse(authenticationfailureevent $event): void
    {
        $exception = $event->getexception();
        if ($exception instanceof badcredentialsexception) {
            // your logic
        }
        
        $response = new jsonresponse($message, jsonresponse::http_unauthorized);
        $event->setresponse($response);
    }
}
AlexisM
  • 21
  • 2