【发布时间】:2020-01-02 19:49:06
【问题描述】:
我正在尝试使用 Symfony 实现身份验证。不幸的是,无论我尝试什么,我都会一遍又一遍地收到错误“Invalid Credentials”。
我读过其他文章,但没有一篇能派上用场。这可能是什么原因,我该如何解决?
我尝试修改 getUsername() 以返回电子邮件而不是用户名,但它没有用。我检查了我的注册过程,确定哈希是否正确,将 password_verify 的结果转储为纯密码,然后来自数据库的一个(这是真的)等等。
我认为我做错了什么。
security.yml:
security:
role_hierarchy:
encoders:
AppBundle\Entity\User: bcrypt
# https://symfony.com/doc/current/security.html#b-configuring-how-users-are-loaded
providers:
db_provider:
entity:
class: AppBundle\Entity\User
property: email
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
pattern: ^/
provider: db_provider
anonymous: ~
form_login:
username_parameter: _email
check_path: security_login
login_path: security_login
default_target_path: homepage
always_use_default_target_path: true
csrf_token_generator: security.csrf.token_manager
logout:
path: security_logout
target: security_login
access_control:
# this is a catch-all for the admin area
# addition security lices in the controllers
# - { path: '^/(%locale%)/admin', roles: ROLE_ADMIN
# - { path: '^/ucp', roles: [IS_AUTHENTICATED_FULLY] }
login.html.twig
<form name="authenticate" action="{{ path('security_login') }}" method="post" class="loginForm" id="loginForm">
<div class="form-group">
<input type="email" class="form-control" name="_email" value="{{ last_username }}" id="email" placeholder="Имейл адрес"/>
</div>
<div class="form-group">
<input type="password" class="form-control" name=_password" id="password" placeholder="Парола"/>
</div>
<input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">
<div class="text-center"><button type="submit" id="loginButton">Log in</button></div>
</form>
用户服务
class UserService implements UserServiceInterface
{
private $encryptionService;
private $entityManager;
public function __construct(UserPasswordEncoderInterface $encryptionService,
EntityManagerInterface $entityManager)
{
$this->encryptionService = $encryptionService;
$this->entityManager = $entityManager;
}
public function save(User $user): Response
{
$passwordHash = $this->encryptionService->encodePassword($user, $user->getPassword());
$user->setPassword($passwordHash);
$this->entityManager->persist($user);
$this->entityManager->flush();
return new Response();
}
}
【问题讨论】:
-
您的提供商说:email 用于身份验证,但在您的登录表单中,您使用 _username 进行身份验证。然后尝试通过UserPasswordEncoderInterface注入编码器服务来对你的密码进行编码。
-
我相信是差不多的,但是可能会混淆。但是,security.yml已经更新,现在username_parameter等于_email。那个接口,UserPasswordEncoderInterface也被注入了,但没有任何改变。跨度>
-
登录表单中的转储错误:prnt.sc/qitqp2
标签: php symfony authentication