我按照guide来实现我自己的自定义用户登录。不幸的是,它在登录时说Bad credentials
。此例外来自Symfony\Component\Security\Core\Authentication\Provider\UserAuthenticationProvider
的第72行。抛出此异常是因为它无法检索用户。
我为自定义需求而更改的是用户没有用户名。他们将使用他们的电子邮件地址登录但我认为实施起来没有问题。
security.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 }
UserRepository:
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
有关?如何将其添加到控制器和twig文件?这是问题吗?我做错了其他事吗?
答案 0 :(得分:0)
默认情况下,Symfony安全性使用_username
和_password
参数通过表单提交对用户进行身份验证。您可以在security configuration reference
form_login:
username_parameter: _username
password_parameter: _password
因此,您需要将_username
字段名称替换为_email
。