Symfony 6.2配置token_extractors为header时无法触发自定义Token Handler
问题分析:Symfony 6.2中AccessTokenHandler在header模式下不触发的问题
在Symfony 6.2中,当security.yml里的access_token配置项中token_extractors设为header时,请求处理无法触发自定义的AccessTokenHandler;但改为query_string通过GET参数传递token时则可以正常触发。
现有配置代码
security.yml
security: password_hashers: Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto' providers: access_token_provider: entity: class: App\Entity\AccessToken property: secret firewalls: main: lazy: true provider: access_token_provider stateless: true pattern: ^/ access_token: token_extractors: header token_handler: App\Security\AccessTokenHandler access_control: - { path: ^/, roles: ROLE_ADMIN }
自定义AccessTokenHandler代码
namespace App\Security; use App\Repository\AccessTokenRepository; use Doctrine\ORM\NonUniqueResultException; use SensitiveParameter; use Symfony\Component\Security\Core\Exception\BadCredentialsException; use Symfony\Component\Security\Http\AccessToken\AccessTokenHandlerInterface; use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge; readonly class AccessTokenHandler implements AccessTokenHandlerInterface { public function __construct(private AccessTokenRepository $accessTokenRepository) { } /** * @throws NonUniqueResultException */ public function getUserBadgeFrom(#[SensitiveParameter] string $accessToken): UserBadge { var_dump($accessToken); die; $accessToken = $this->accessTokenRepository->getOneByToken($accessToken); if (!$accessToken || !$accessToken->isValid()) { throw new BadCredentialsException('Invalid credentials.'); } return new UserBadge($accessToken->getId()); } }
API客户端生成的请求头格式:Authorization: Bearer 00000000-0000-0000-0000-000000000000
问题根源与解决方案
问题所在
当前配置中的token_extractors: header写法错误。Symfony 6.2中,直接写header会让框架尝试从名为header的请求头中读取原始token值,而非解析标准的Authorization: Bearer <token>格式请求头,导致无法正确提取token,自然不会触发自定义的AccessTokenHandler。
正确配置方式
需要明确指定使用authorization_header类型的提取器(支持解析Bearer token格式),有两种写法:
写法一:完整配置(推荐,便于后续扩展)
access_token: token_extractors: authorization_header: enabled: true prefix: 'Bearer' name: Authorization token_handler: App\Security\AccessTokenHandler
写法二:简写形式
access_token: token_extractors: authorization_header token_handler: App\Security\AccessTokenHandler
额外验证点
- 确认服务器中间件(如Nginx)未篡改或移除
Authorization请求头 - 检查请求头格式是否正确:
Bearer与token之间必须有空格,拼写无错误
内容的提问来源于stack exchange,提问作者Vladimir
相关产品推荐
相关产品推荐

