You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

修改JWT认证头为X-Authorization后Swagger UI认证失败排查

Swagger UI 认证头配置不生效问题排查与解决

问题背景

此前因前端通过Caddy与后端交互存在认证异常,修改lexik_jwt_authentication.yaml将JWT令牌提取的请求头从Authorization改为X-Authorization,解决了前后端认证交互问题。但Swagger UI仍使用Authorization头发起请求,导致认证失败。尝试修改nelmio_api_doc.yaml配置、通过kernel.request事件订阅拦截修改请求头、使用OpenApiFactoryDecorator装饰器均无效,需排查原因并实现Swagger UI使用X-Authorization头认证。

现有配置代码

nelmio_api_doc.yaml

nelmio_api_doc:
    documentation:
        info:
            title: My App
            description: This is an awesome app!
            version: 1.0.0
        components:
            securitySchemes:
                # Bearer:
                #     type: http
                #     scheme: bearer
                ApiKeyAuth:
                    type: apiKey
                    in: header
                    name: X-Authorization
        security:
            - ApiKeyAuth: []
    areas: # to filter documented areas
        path_patterns:
            - ^/api(?!/doc$) # Accepts routes under /api except /api/doc

lexik_jwt_authentication.yaml

lexik_jwt_authentication:
    secret_key: '%env(resolve:JWT_SECRET_KEY)%'
    public_key: '%env(resolve:JWT_PUBLIC_KEY)%'
    pass_phrase: '%env(JWT_PASSPHRASE)%'
    token_ttl: 36000
    # token_ttl: 3600
    # clock_skew: 0
    # allow_no_expiration: false
    api_platform:
        check_path: /api/login_check
        username_path: email
        password_path: security.credentials.password
    # encoder:
    #     service: acme_api.encoder.nixilla_jwt_encoder
# token extraction settings
    token_extractors:
    #     # look for a token as Authorization Header
        authorization_header:
            enabled: true
            prefix: Bearer
            name:   X-Authorization

Swagger UI生成的Curl请求

curl -X 'GET' \
  'https://localhost/api/users?page=1' \
  -H 'accept: application/ld+json' \
  -H 'Authorization: xxxxxx.         <<<<<<<<<< key is not X-Authorization as specified in nelmio__api_doc.yaml or Apiplatform.yaml

OpenApiFactoryDecorator代码

#[AsDecorator('api_platform.openapi.factory')]
class OpenApiFactoryDecorator implements OpenApiFactoryInterface
{
    public function __construct(
        private OpenApiFactoryInterface $decorated,
        // private OpenApiFactory $factory,
    )
    {}

    public function __invoke(array $context = []): OpenApi
    {
        $openApi = $this->decorated->__invoke($context);   

        $components = $openApi->getComponents()->withSecuritySchemes(
            new ArrayObject(
                [
                    'access_token' => new SecurityScheme(
                        type:         'http',
                        description:  'Value for the JWT Authorization header parameter.',
                        scheme:       'bearer'
                    )
                ]
            )
        );

        return $openApi->withComponents($components);
    }
}

问题排查与解决思路

  1. 核心冲突:装饰器覆盖yaml配置
    你当前的OpenApiFactoryDecorator代码中,重新定义了access_token类型为http bearer的SecurityScheme,直接覆盖了nelmio_api_doc.yaml里配置的ApiKeyAuth,这是配置不生效的根本原因。

  2. 修正装饰器代码
    若需保留装饰器,需调整其逻辑,直接定义X-Authorization的apiKey类型认证方案,而非覆盖原有设置:

    #[AsDecorator('api_platform.openapi.factory')]
    class OpenApiFactoryDecorator implements OpenApiFactoryInterface
    {
        public function __construct(
            private OpenApiFactoryInterface $decorated,
        ) {}
    
        public function __invoke(array $context = []): OpenApi
        {
            $openApi = $this->decorated->__invoke($context);   
            $securitySchemes = $openApi->getComponents()->getSecuritySchemes() ?: new ArrayObject();
    
            // 添加/替换为X-Authorization的apiKey认证
            $securitySchemes['ApiKeyAuth'] = new SecurityScheme(
                type: 'apiKey',
                in: 'header',
                name: 'X-Authorization',
                description: 'JWT令牌格式为Bearer {token},需放在X-Authorization头中'
            );
    
            return $openApi->withComponents(
                $openApi->getComponents()->withSecuritySchemes($securitySchemes)
            );
        }
    }
    
  3. 避免配置重复冲突

    • 若使用yaml配置,直接删除装饰器中覆盖SecuritySchemes的代码,确保yaml设置生效;
    • 若使用装饰器,注释掉nelmio_api_doc.yaml里的components.securitySchemes和security配置,避免重复定义。
  4. 清除Symfony缓存
    修改配置或代码后,必须清除缓存确保新配置生效:

    # 开发环境
    php bin/console cache:clear --env=dev
    # 生产环境
    php bin/console cache:clear --env=prod
    
  5. 验证配置效果
    清除缓存后重新访问Swagger UI,检查页面认证配置是否显示为X-Authorization头,生成Curl请求确认头名称是否正确。

内容的提问来源于stack exchange,提问作者Tkay Bay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 20:39:54