php - symfony 5 getUser() 的身份验证问题
问题描述
我正在尝试使用 Symfony 5 和安全组件,但我被阻止了一个错误。该错误是重定向后认证成功,$this->getUser()
返回null但同时,开发面板显示我的角色(存储在数据库中)
我的安全.yaml:
security:
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
in_database:
entity:
class: App\Entity\User
property: email
role_hierarchy:
ROLE_CLIENT: ROLE_USER
ROLE_ADMIN: ROLE_CLIENT
ROLE_DEV: [ROLE_CLIENT, ROLE_ADMIN]
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: true
provider: in_database
form_login:
check_path: app_login
login_path: app_login
default_target_path: /test
username_parameter: email
password_parameter: password
csrf_parameter: _csrf_security_token
csrf_token_id: a_private_string
logout:
path: app_logout
target: app_login
# 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: ^/backoffice, roles: ROLE_ADMIN }
- { path: ^/profile, roles: ROLE_USER }
encoders:
App\Entity\User: plaintext
而且我没有修改用户实体。
编辑
根据建议,我在 security.yaml 中添加了这些行:
guard:
authenticators:
- App\Security\LoginFormAuthentificator
和 LoginFormAuthentificator 文件(对不起,它会很长)
<?php
namespace App\Security;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
class LoginFormAuthentificator extends AbstractFormLoginAuthenticator {
use TargetPathTrait;
private $entityManager;
private $router;
private $csrfTokenManager;
private $passwordEncoder;
public function __construct(EntityManagerInterface $entityManager, RouterInterface $router, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder){
$this->entityManager = $entityManager;
$this->router = $router;
$this->csrfTokenManager = $csrfTokenManager;
$this->passwordEncoder = $passwordEncoder;
}
public function supports(Request $request){
return 'app_login' === $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 $this->passwordEncoder->isPasswordValid($user, $credentials['password']);
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey){
if($targetPath = $this->getTargetPath($request->getSession(), $providerKey)){
return new RedirectResponse($targetPath);
}
return new RedirectResponse($this->router->generate('BackOffice_home_index'));
// throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
}
protected function getLoginUrl(){
return $this->router->generate('app_login');
}
}
非常感谢您的帮助和时间。
解决方案
经过一些调试,我发现您实现Serializable
了类的接口User
。使用这种方法,来自此接口的方法应该返回正确的数据,因为User
对象将通过这些方法序列化到会话。在您的案例方法中,serialize
并且unserialize
是空的,这导致会话中存储了空值。所以你应该Serializable
从你的类中删除接口和它的方法User
(在这种情况下,应用程序在会话中存储一些默认字段),或者至少为这些方法实现最小的功能:
public function serialize(){
return serialize([
$this->id,
$this->email,
$this->password
]);
}
public function unserialize($serialized){
list(
$this->id,
$this->email,
$this->password
) = unserialize($serialized, ['allowed_classes' => false]);
}
此外,将返回值添加到getUsername
从 实现的方法中UserInterface
,例如
public function getUsername(){
return $this->email;
}
推荐阅读
- php - 如何在ajax循环中调用codeigniter函数
- python - 试图创造混乱游戏
- git - Azure Repos 文件夹/目录比较
- c# - 如何在 C# 中生成 12AM 和 6PM 之间的随机时间?
- android - Android - 视图不是 CoordinatorLayout (BottomSheet) 的子视图
- sql - SQL 脚本,STOCK 返回相同的结果
- java - 尝试创建循环时不断收到 java.util.NoSuchElementException 错误
- c - 交叉编译的根文件系统中未声明的变量
- c# - 在应用程序的另一部分检索 IApplicationBuilder 和 IWebHostEnvironment
- javascript - 如何修复设计中给出的滑块的导航和点