Symfony 5使用json_login实现AJAX JSON登录失效问题
Symfony迁移场景下JSON登录接口异常问题
- 我是Symfony新手,正在将自研基础MVC架构的PHP项目迁移至Symfony
- 原项目运行状态稳定,适配Symfony的过程中遇到了登录功能改造的卡点
- 已基于Symfony基础骨架,通过
make:user、make:auth命令搭建基础功能,原生模板登录流程可正常运行,尝试将登录改造为AJAX JSON接口时流程阻塞 - 已参照官方JSON登录配置教程完成参数设置,目前出现响应不符合预期的问题
现有security.yaml配置
security: encoders: App\Entity\User: algorithm: auto # 用户提供方配置 providers: # 用于从会话中重载用户、支持切换用户等安全特性 app_user_provider: entity: class: App\Entity\User property: email firewalls: dev: pattern: ^/(_(profiler|wdt)|css|images|js)/ security: false main: anonymous: true lazy: true provider: app_user_provider json_login: check_path: app_login username_path: email password_path: password guard: authenticators: - App\Security\UserAuthenticator logout: path: app_logout # 登出后跳转目标 target: home
现有SecurityController代码
最初路由绑定了POST方法限制,为排查请求方法相关问题,已移除该限制
class SecurityController extends AbstractController { /** * @Route("/api/login", name="app_login") */ public function login(Request $request): Response { return $this->json([ 'user' => $this->getUser() ? $this->getUser()->getId(): null, 'error' => 1, 'content' => $request->getMethod() ]); } }
接口测试命令
使用如下curl命令发送POST请求,携带JSON格式的登录参数:
curl -X POST -H "Content-Type: application/json" https://127.0.0.1:8000/api/login -d '{"email": "test@test.de", "password": "1234"}'
异常现象
- 发送请求后收到302重定向到/api/login的HTML响应
- 控制器内
$request->getMethod()返回值始终为GET,$this->getUser()始终为null
服务端日志输出
[PHP ] [Thu Mar 25 16:05:13 2021] 127.0.0.1:60846 [302]: POST /api/login [PHP ] [Thu Mar 25 16:05:13 2021] 127.0.0.1:60846 Closing [PHP ] [Thu Mar 25 16:05:13 2021] 127.0.0.1:60848 Accepted [PHP ] [Thu Mar 25 16:05:13 2021] [info] Matched route "app_login". [PHP ] [PHP ] [Thu Mar 25 16:05:13 2021] [debug] Checking for guard authentication credentials. [PHP ] [PHP ] [Thu Mar 25 16:05:13 2021] [debug] Checking support on guard authenticator. [PHP ] [PHP ] [Thu Mar 25 16:05:13 2021] [debug] Guard authenticator does not support the request.
自定义UserAuthenticator完整代码
<?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\Generator\UrlGeneratorInterface; 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\Guard\PasswordAuthenticatedInterface; use Symfony\Component\Security\Http\Util\TargetPathTrait; class UserAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface { use TargetPathTrait; public const LOGIN_ROUTE = 'app_login'; private $entityManager; private $urlGenerator; private $csrfTokenManager; private $passwordEncoder; public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder) { $this->entityManager = $entityManager; $this->urlGenerator = $urlGenerator; $this->csrfTokenManager = $csrfTokenManager; $this->passwordEncoder = $passwordEncoder; } 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) { 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 getPassword($credentials): ?string { return $credentials['password']; } public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $providerKey) { if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) { return new RedirectResponse($targetPath); } return new RedirectResponse($this->urlGenerator->generate('home')); } protected function getLoginUrl() { return $this->urlGenerator->generate(self::LOGIN_ROUTE); } }
核心待解问题
现有配置和代码存在什么问题,导致登录流程无法正常运行?
内容的提问来源于stack exchange,提问作者Just Pilot
相关产品推荐
相关产品推荐

