当用户尝试使用错误的用户名/密码登录时,将显示错误消息“无效的凭据”!
如何更改getLastAuthenticationError()
错误消息!
例如!而不是“无效的凭据”,我希望它是“错误消息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]);
}
安全代码.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的地方构建自己的身份验证器。
要翻译邮件,您可以查看原始翻译文件以供参考。在您的translations /文件夹中,仅添加security.en.yaml,然后可以覆盖以下消息:
# translations/security.en.yaml
'Invalid credentials.': 'Your username or password are invalid.'
对于CustomUserMessageException,请查看如何构建登录表单上的docs页面。步骤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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句