如何更改身份验证错误消息?

How to change the authentication error message?

当用户尝试使用错误 username/password 登录时,出现错误消息 "Invalid credentials"!

如何更改 getLastAuthenticationError() 错误消息!

例如! 而不是 "Invalid credentials" 我希望它是 "error message 123"

控制器代码:

/**
 * @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]);
}

代码 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

视图代码:

{% 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>

您可以使用自定义翻译,也可以在抛出 CustomUserMessageAuthenticationException.

的地方构建自己的身份验证器

翻译消息可以参考the original translation file。在您的 translations/ 文件夹中只需添加一个 security.en.yaml 然后您就可以覆盖消息:

# translations/security.en.yaml
'Invalid credentials.': 'Your username or password are invalid.'

对于 CustomUserMessageException,请查看 How to Build a Login Form 上的文档页面。

第 3 步展示了如何编写 GuardAuthenticator,它还展示了如何使用自定义异常:

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