问题描述
我正在尝试在 Symfony 4.4 中登录一个用户,但收到此消息“凭据无效”。我不知道如何解决。我在这个平台上看到一些帖子我没有解决我的问题。
security:
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
users:
entity:
# the class of the entity that represents users
class: 'App\Entity\User'
property: 'email'
encoders:
# use your user class name here
App\Entity\User:
# Use native password encoder
# This value auto-selects the best possible hashing algorithm
# (i.e. sodium when available).
algorithm: bcrypt
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: lazy
provider: users
guard:
authenticators:
- App\Security\LoginFormAuthenticator
logout:
path: logout
# where to redirect after logout
# target: app_any_route
# activate different ways to authenticate
# https://symfony.com/doc/current/security.html#firewalls-authentication
# https://symfony.com/doc/current/security/impersonating_user.html
# switch_user: true
# Easy way to control access for large sections of your site
# Note: Only the *first* access control that matches will be used
access_control:
# - { path: ^/admin,roles: ROLE_ADMIN }
# - { path: ^/profile,roles: ROLE_USER }
LoginFormAuthenticator.PHP
class LoginFormAuthenticator 扩展了 AbstractformLoginAuthenticator { 使用 TargetPathTrait;
public const LOGIN_ROUTE = 'login';
private $entityManager;
private $urlGenerator;
private $csrftokenManager;
public function __construct(EntityManagerInterface $entityManager,UrlGeneratorInterface $urlGenerator,CsrftokenManagerInterface $csrftokenManager)
{
$this->entityManager = $entityManager;
$this->urlGenerator = $urlGenerator;
$this->csrftokenManager = $csrftokenManager;
}
public function supports(Request $request)
{
return self::LOGIN_ROUTE === $request->attributes->get('_route')
&& $request->isMethod('POST');
}
public function getCredentials(Request $request)
{
$credentials = [
'email' => $request->request->get('email'),'password' => $request->request->get('password'),'csrf_token' => $request->request->get('_csrf_token'),];
$request->getSession()->set(
Security::LAST_USERNAME,$credentials['email']
);
return $credentials;
}
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;
}
public function checkCredentials($credentials,UserInterface $user)
{
return "Logeado";
// Check the user's password or other credentials and return true or false
// If there are no credentials to check,you can just return true
throw new \Exception('Todo: check the credentials inside '.__FILE__);
}
public function onAuthenticationSuccess(Request $request,TokenInterface $token,$providerKey)
{
if ($targetPath = $this->getTargetPath($request->getSession(),$providerKey)) {
return new RedirectResponse($targetPath);
}
// For example : return new RedirectResponse($this->urlGenerator->generate('some_route'));
throw new \Exception('Todo: provide a valid redirect inside '.__FILE__);
}
protected function getLoginUrl()
{
return $this->urlGenerator->generate(self::LOGIN_ROUTE);
}
}
用户实体
class User implements UserInterface
{
/**
* @ORM\Id
* @ORM\GeneratedValue
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string",length=255)
*/
private $username;
/**
* @ORM\Column(type="string",length=255)
*/
private $password;
/**
* @ORM\Column(type="string",length=255)
*/
private $email;
/**
* @ORM\Column(type="boolean")
*/
private $isverified = false;
public function getId(): ?int
{
return $this->id;
}
public function getUsername(): ?string
{
return $this->username;
}
public function setUsername(string $username): self
{
$this->username = $username;
return $this;
}
public function getpassword(): ?string
{
return $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
public function getRoles()
{
// Todo: Implement getRoles() method.
}
public function getSalt()
{
// Todo: Implement getSalt() method.
}
public function eraseCredentials()
{
// Todo: Implement eraseCredentials() method.
}
public function isverified(): bool
{
return $this->isverified;
}
public function setIsverified(bool $isverified): self
{
$this->isverified = $isverified;
return $this;
}
}
class SecurityController extends AbstractController
{
/**
* @Route("/login",name="login")
*/
public function login(AuthenticationUtils $authenticationUtils): Response
{
// if ($this->getUser()) {
// return $this->redirectToRoute('target_path');
// }
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render('security/login.html.twig',['last_username' => $lastUsername,'error' => $error]);
}
/**
* @Route("/logout",name="logout")
*/
public function logout()
{
throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
解决方法
如果您将属性设置为“电子邮件” 在您的用户实体中 getusername 必须返回您应该更改它的电子邮件