Reputation: 1289
When the user attempts to login with wrong username/password an error message "Invalid credentials" appear!
How can I change the getLastAuthenticationError()
error message !
For example! instead of "Invalid credentials" I want it to be "error message 123"
Code of the controlleur :
/**
* @Route("/login",name="security_login")
*/
public function login(AuthenticationUtils $authenticationUtils)
{
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('123/login.html.twig',[
'lastUsername'=>$lastUsername,
'error' => $error]);
}
Code of security.yaml
security:
encoders:
App\Entity\User:
algorithm: bcrypt
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
in_memory: { memory: null }
in_database:
entity:
class: App\Entity\User
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: lazy
provider: in_database
form_login:
login_path: security_login
check_path: security_login
logout:
path: security_logout
target: user_index
code of the view :
{% if error %}
<div>{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}
<form action="{{ path('security_login') }}" method="post">
<div class="form-group">
<input placeholder="username" requied name="_username" value ="{{lastUsername}}"
type="text" class="form-control">
</div>
<div class="form-group">
<input placeholder="Mode de passe..." requied name="_password"
type="password" class="form-control">
</div>
<div class="form-group">
<button type="submit" class="btn btn-success">Connexion</button>
</div>
</form>
Upvotes: 3
Views: 5398
Reputation: 17166
You can either use a custom translation or build your own authenticator where you throw a CustomUserMessageAuthenticationException
.
For translating the message you can look at the original translation file for reference. In your translations/ folder just add a security.en.yaml
and then you can overwrite the message:
# translations/security.en.yaml
'Invalid credentials.': 'Your username or password are invalid.'
For the CustomUserMessageException
, check the docs page on How to Build a Login Form.
Step 3 shows how to write a GuardAuthenticator
and it also shows how to use the custom exception:
public function getUser($credentials, UserProviderInterface $userProvider)
{
$token = new CsrfToken('authenticate', $credentials['csrf_token']);
if (!$this->csrfTokenManager->isTokenValid($token)) {
throw new InvalidCsrfTokenException();
}
$user = $this->entityManager->getRepository(User::class)->findOneBy(['email' => $credentials['email']]);
if (!$user) {
// fail authentication with a custom error
throw new CustomUserMessageAuthenticationException('Email could not be found.');
}
return $user;
}
Upvotes: 9