首页 > 解决方案 > 在 NelmioApiDocBundle 中向 Swagger 添加身份验证文档

问题描述

我将 Symfony (5) 与 NelmioApiDocBundle (4.0) 和 LexikJWTAuthenticationBundle 一起使用来使用 Swagger 创建 API。我已经设置了端点和身份验证,一切都按预期工作。我有功能齐全的身份验证 API,有一个文档,我可以成功生成 Open API 规范。规范中缺少一件事:“身份验证端点”,我找不到将其添加到生成的规范和文档的方法(覆盖整个身份验证除外)

因为我使用的是 Symfony 安全层和防火墙,并且它与 LexikJWTAuthenticationBundle 集成,所以没有地方设置 Swagger 注释,而且似乎 bundle 本身不能处理生成“安全部分” 前一段时间我使用 ApiPlatform 和那里是由“装饰者”完成的

任何人都知道有没有办法(注释?)来生成文档的安全部分,或者我必须从头开始创建身份验证保护(?)

标签: symfonyauthenticationswaggerlexikjwtauthbundlenelmioapidocbundle

解决方案


没关系。分钟我发布它我找到了一个解决方案。在 packages/nelmio_bundle_api.yaml 中,您可以配置不是由注释创建的附加文档(swagger 规范)。基本上,您必须添加一个指向您的身份验证路由的新路径(在我的情况下为 /api/login_check),并在“组件”部分定义凭据和令牌对象。

因此,使用 symfony 授权将是(这只是 yaml 文件的安全部分):

nelmio_api_doc:
    documentation:
        paths:
            /api/login_check:
                post:
                    tags:
                        - Token
                    operationId: postCredentialsItem
                    summary: Get JWT token to login.
                    requestBody:
                        description: Create new JWT Token
                        content:
                            application/json:
                                schema:
                                    $ref: '#/components/schemas/Credentials'
                    responses:
                        '200':
                            description: Get JWT token
                            content:
                                application/json:
                                    schema:
                                        $ref: '#/components/schemas/Token'
    components:
        schemas:
            Token:
                type: object
                properties:
                    token:
                        type: string
                        readOnly: true
            Credentials:
                type: object
                properties:
                    username:
                        type: string
                    password:
                        type: string
        securitySchemes:
            bearerAuth:            
                type: apiKey
                scheme: bearer
                bearerFormat: JWT   
    security:
        - bearerAuth: []

推荐阅读