无法验证数据库symfony 4中的用户重定向到同一登录页面



在基本登录表单中,我试图检查我插入的数据库中的用户是否在登录表单中输入,但由于我的getUser或LoginAuthenticator的checkCredentials中存在错误,该页面正在重定向到同一页面。我搞不清楚我的代码出了什么问题
LoginAuthenticator

<?php
namespace AppSecurity;
use AppRepositoryUsersRepository;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentRoutingRouterInterface;
use SymfonyComponentSecurityCoreAuthenticationTokenTokenInterface;
use SymfonyComponentSecurityCoreSecurity;
use SymfonyComponentSecurityCoreUserUserInterface;
use SymfonyComponentSecurityCoreUserUserProviderInterface;
use SymfonyComponentSecurityGuardAuthenticatorAbstractFormLoginAuthenticator;
class LogAuthenticator extends AbstractFormLoginAuthenticator
{
private $usersRepository;
private $router;
public function __construct(UsersRepository $usersRepository, RouterInterface $router){
$this->usersRepository = $usersRepository;
$this->router = $router;
}
public function supports(Request $request)
{
return $request->attributes->get('_route') === 'app_login'
&& $request->isMethod('POST');
}
public function getCredentials(Request $request)
{
$credentials = [
'email' => $request->request->get('user_email'),
'password' => $request->request->get('password')
];
$request ->getSession()->set(
Security::LAST_USERNAME,
$credentials['email']
);
return $credentials;
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
$this->usersRepository->findOneBy(['user_email' =>$credentials['email']]);
}
public function checkCredentials($credentials, UserInterface $user)
{
return true;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
return $this->router->generate('app_homepage');
}
protected function getLoginUrl()
{
return $this->router->generate('app_login');
}
}

登录控制器

<?php
namespace AppController;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyComponentSecurityHttpAuthenticationAuthenticationUtils;
class LoginController extends AbstractController
{
/**
* @Route("/login", name="app_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="app_logout")
*/
public function logout()
{
throw new LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');
}
}

用户存储库

<?php
namespace AppRepository;
use AppEntityUser;
use DoctrineBundleDoctrineBundleRepositoryServiceEntityRepository;
use DoctrinePersistenceManagerRegistry;
/**
* @method User|null find($id, $lockMode = null, $lockVersion = null)
* @method User|null findOneBy(array $criteria, array $orderBy = null)
* @method User[]    findAll()
* @method User[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class UserRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, User::class);
}
// /**
//  * @return User[] Returns an array of User objects
//  */
/*
public function findByExampleField($value)
{
return $this->createQueryBuilder('u')
->andWhere('u.exampleField = :val')
->setParameter('val', $value)
->orderBy('u.id', 'ASC')
->setMaxResults(10)
->getQuery()
->getResult()
;
}
*/
/*
public function findOneBySomeField($value): ?User
{
return $this->createQueryBuilder('u')
->andWhere('u.exampleField = :val')
->setParameter('val', $value)
->getQuery()
->getOneOrNullResult()
;
}
*/
}

Security.yaml

security:
encoders:
AppEntityUsers:
algorithm: auto
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
# used to reload user from session & other features (e.g. switch_user)
app_user_provider:
entity:
class: AppEntityUsers
property: email
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: lazy
provider: app_user_provider
logout:
path: app_logout
guard:
authenticators:
- AppSecurityLoginAuthenticator
# 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 }

在此处输入图像描述

您使用了错误的用户提供程序,现在您的防火墙使用了具有null值的memory提供程序:

security:
...
providers:
users_in_memory: { memory: null }
...

当你想从数据库中检索用户时,你应该使用entity提供者:

# config/packages/security.yaml
security:
# ...
providers:
users:
entity:
# the class of the entity that represents users
class: 'AppEntityUser'
# the property to query by - e.g. username, email, etc
property: 'username'
# optional: if you're using multiple Doctrine entity
# managers, this option defines which one to use
# manager_name: 'customer'
# ...

https://symfony.com/doc/4.4/security/user_provider.html#security-实体用户提供商

完整的文档可以在这里找到:https://symfony.com/doc/4.4/security.html

编辑:我刚刚注意到你还在security.yaml中设置了enable_authenticator_manager。如果您的项目运行Symfony 4.x,这将不起作用,因为它是在Symfony 5.1中引入的。

最新更新