Symfony 6 JSON登录提示无效凭证问题求助
排查Symfony 6 JSON登录返回"invalid credentials"问题
以下是针对你的场景(Symfony 6 + API Platform 2.7)的逐一排查步骤:
1. 确认用户密码是否正确哈希
- 绝对不能直接在数据库中存储明文密码,必须通过Symfony的
UserPasswordHasherInterface生成哈希值后再保存。示例创建用户代码:$user = new User(); $user->setEmail('your-test-email@example.com'); $hashedPassword = $passwordHasher->hashPassword($user, 'your-plain-password'); $user->setPassword($hashedPassword); $entityManager->persist($user); $entityManager->flush(); - 查询数据库确认
password字段是类似$2y$13$...的哈希字符串,而非明文。
2. 检查User实体的实现
- 确保实体正确实现
Symfony\Component\Security\Core\User\UserInterface,核心方法需正确编写:public function getUserIdentifier(): string { return $this->email; // 用用户名登录则返回$this->username } public function getRoles(): array { $roles = $this->roles; // 至少保留一个基础角色,比如ROLE_USER $roles[] = 'ROLE_USER'; return array_unique($roles); } public function eraseCredentials(): void { // 清空敏感临时字段(若有) } // 兼容旧版本的可选方法 public function getUsername(): string { return $this->getUserIdentifier(); } - 确认
isEnabled()方法返回true,若实体有enabled字段,需保证测试用户的该字段为true,禁用用户会直接返回无效凭证。
3. 核对security.yaml配置
- 防火墙与登录路径:确保
json_login的check_path与登录路由匹配,且该路径允许匿名访问:security: providers: app_user_provider: entity: class: App\Entity\User property: email # 与登录用的字段一致(email或username) firewalls: main: lazy: true provider: app_user_provider json_login: check_path: api_login # 对应登录控制器的路由名称或路径 username_path: email # 对应JSON请求体的用户名字段名 password_path: password # 对应JSON请求体的密码字段名 logout: path: api_logout access_control: - { path: ^/api/login, roles: IS_AUTHENTICATED_ANONYMOUSLY } - { path: ^/api/events, roles: ROLE_USER } # 你的私有资源路径 - 编码器配置:Symfony 6默认自动检测哈希算法,手动配置需指向正确实体:
encoders: App\Entity\User: algorithm: auto
4. 验证登录请求格式
- 请求必须为
POST方法,Content-Type头设为application/json。 - 请求体字段名要与
security.yaml中username_path、password_path一致,示例请求体(若用邮箱登录):{ "email": "your-test-email@example.com", "password": "your-plain-password" } - 不要嵌套字段(如
{"user": {"email": "..."} }),除非在username_path中配置user.email这类嵌套路径。
5. 排查路由冲突
- 确保
/api/login路由未被API Platform自动路由覆盖,检查控制器注解:#[Route('/api/login', name: 'api_login', methods: ['POST'])] public function login(AuthenticationUtils $authenticationUtils): JsonResponse { $error = $authenticationUtils->getLastAuthenticationError(); $user = $this->getUser(); if ($error) { return new JsonResponse(['error' => $error->getMessageKey()], JsonResponse::HTTP_UNAUTHORIZED); } if ($user) { return new JsonResponse([ 'username' => $user->getUserIdentifier(), 'roles' => $user->getRoles(), ]); } return new JsonResponse(['error' => 'No user authenticated'], JsonResponse::HTTP_UNAUTHORIZED); } - 运行
php bin/console debug:router,确认api_login路由存在且路径正确。
6. 查看调试日志定位问题
- 打开
var/log/dev.log,查找登录相关日志:User not found for username 'xxx':说明配置的property字段(如email)无匹配用户Password verification failed for user 'xxx':说明密码不匹配- 权限类错误:检查防火墙或
access_control配置
通过以上步骤逐一排查,基本能定位到导致"invalid credentials"的具体原因。
内容的提问来源于stack exchange,提问作者Zazou
相关产品推荐
相关产品推荐

