API Platform v2.2.5如何为自定义认证路由生成文档?
为API Platform v2.2.5添加自定义认证路由到Swagger文档
嘿,我之前在Symfony 4 Flex + API Platform v2.x的项目里正好解决过这个问题——默认的API Platform只会自动收录它管理的资源路由,像JWT认证的/login这类自定义路由确实不会出现在Swagger文档里。下面给你两个实操性强的方案:
方案一:用API Platform的Swagger装饰器(推荐)
这是最贴合API Platform生态的方式,通过装饰器扩展默认的Swagger规范,手动把认证路由加进去。
1. 创建Swagger装饰器类
在src/Swagger目录下新建AuthSwaggerDecorator.php(目录不存在就自己建):
<?php namespace App\Swagger; use Symfony\Component\Serializer\Normalizer\NormalizerInterface; final class AuthSwaggerDecorator implements NormalizerInterface { private $decorated; public function __construct(NormalizerInterface $decorated) { $this->decorated = $decorated; } public function normalize($object, $format = null, array $context = []) { $docs = $this->decorated->normalize($object, $format, $context); // 添加JWT认证的安全方案定义 $docs['components']['securitySchemes']['JWT'] = [ 'type' => 'http', 'scheme' => 'bearer', 'bearerFormat' => 'JWT', ]; // 全局设置默认需要JWT认证(可选,如果你大部分接口都需要的话) $docs['security'] = [['JWT' => []]]; // 添加/login路由的文档定义 $docs['paths']['/login'] = [ 'post' => [ 'tags' => ['Authentication'], 'summary' => '获取JWT Token', 'requestBody' => [ 'content' => [ 'application/json' => [ 'schema' => [ 'type' => 'object', 'properties' => [ 'username' => ['type' => 'string'], 'password' => ['type' => 'string'], ], 'required' => ['username', 'password'], ], ], ], ], 'responses' => [ '200' => [ 'description' => '成功获取Token', 'content' => [ 'application/json' => [ 'schema' => [ 'type' => 'object', 'properties' => [ 'token' => ['type' => 'string'], ], ], ], ], ], '401' => [ 'description' => '用户名或密码错误', ], ], ], ]; return $docs; } public function supportsNormalization($data, $format = null) { return $this->decorated->supportsNormalization($data, $format); } }
2. 注册装饰器服务
在config/services.yaml里添加服务配置:
services: App\Swagger\AuthSwaggerDecorator: decorates: 'api_platform.swagger.normalizer.api_gateway' arguments: ['@.inner'] tags: - { name: 'api_platform.swagger.normalizer.decorator' }
3. 测试效果
清除缓存(php bin/console cache:clear)后,访问/api的Swagger页面,就能看到Authentication标签下的/login路由了,还能直接在页面上测试获取Token的请求。
方案二:配合NelmioApiDocBundle(适合需要更复杂文档的场景)
如果你的自定义路由不止一个,或者需要更灵活的文档配置,可以搭配NelmioApiDocBundle:
- 安装bundle:
composer require nelmio/api-doc-bundle - 在路由配置(比如
config/routes/nelmio_api_doc.yaml)里启用Nelmio的文档路由 - 给你的
/login控制器方法添加Nelmio的注解(比如@ApiDoc)来定义文档 - 配置API Platform的Swagger页面整合Nelmio的文档(或者直接用Nelmio的文档页面)
不过这个方案相对重一点,如果只是加个认证路由,方案一足够轻便。
内容的提问来源于stack exchange,提问作者Chris Brown
相关产品推荐
相关产品推荐

