我按照本指南实现了我自己的自定义用户登录。不幸的是,它Bad credentials
在登录时说。这个例外来自第 72 行Symfony\Component\Security\Core\Authentication\Provider\UserAuthenticationProvider
。抛出此异常是因为它无法检索用户。
我为自定义需求所做的更改是用户没有用户名。他们将使用他们的电子邮件地址登录。但我认为实施起来没有问题。
安全性.yml:
security:
encoders:
Acme\UserBundle\Entity\User: plaintext
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
providers:
administrators:
entity: { class: AcmeUserBundle:User }
firewalls:
secured_area:
pattern: ^/
anonymous: ~
form_login: ~
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/, roles: ROLE_USER }
用户存储库:
class UserRepository extends EntityRepository implements UserProviderInterface
{
public function loadUserByUsername($username)
{
$q = $this
->createQueryBuilder('u')
->where('u.email = :email')
->setParameter('email', $username)
->getQuery();
try {
// The Query::getSingleResult() method throws an exception
// if there is no record matching the criteria.
$user = $q->getSingleResult();
} catch (NoResultException $e) {
$message = sprintf(
'Unable to find an active admin AcmeUserBundle:User object identified by "%s".',
$username
);
throw new UsernameNotFoundException($message, 0, $e);
}
return $user;
}
public function refreshUser(UserInterface $user)
{
$class = get_class($user);
if (!$this->supportsClass($class)) {
throw new UnsupportedUserException(
sprintf(
'Instances of "%s" are not supported.',
$class
)
);
}
return $this->find($user->getId());
}
public function supportsClass($class)
{
return $this->getEntityName() === $class
|| is_subclass_of($class, $this->getEntityName());
}
}
login.twig.html:
{% if error %}
<div>{{ error.message }}</div>
{% endif %}
<form action="{{ path('login_check') }}" method="post">
<legend>Login</legend>
<label for="email">Email:</label>
<input type="email" id="email" name="_email" value="{{ email }}"
<label for="password">Password:</label>
<input type="password" id="password" name="_password" />
<button type="submit">Login</button>
</form>
我在这里做错了什么?其中UserRepository
明确将电子邮件作为用户名查询,为什么找不到用户?我猜测它与csrf_token
? 如何将其添加到控制器和树枝文件中?这完全是问题吗,还是我做错了什么?