openapi swagger连接中具有apikey安全性的基于角色的令牌认证

问题描述

描述问题

最近几天,我一直在努力寻找如何在openapi,swagger,connexion中使用apikey安全性进行基于角色的令牌身份验证。以下OpenAPI 3.0端点定义:

/lab/samples/list:
    get:
      tags:
      - lab
      summary: get a list of all registered samples
      operationId: list_samples
      responses:
        "200":
          description: successfully returned all available samples and their notification status
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/Sample-For-Lab'
                x-content-type: application/json
        "400":
          description: invalid request
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/inline_response'
      security:
      - bearerAuth: ['labuser']

具有相应的安全性定义

securitySchemes:
    bearerAuth:
      type: apiKey
      name: Authorization
      in: header
      x-apikeyInfoFunc: swagger_server.controllers.authorization_controller.check_bearerAuth

到目前为止一切顺利。我使用swagger-codegen构建了相应的服务器存根,其后跟connexion security model并提供了两个字段api_key,即不记名令牌和'required_scopes',即应包含'labuser'。访问端点时,控制器功能称为:

def check_adminuserAuth(api_key,required_scopes):
    return {'sample_key' : 'sample_value}

虽然正确传递了承载令牌,但 required_scopesNone 。因此,无法实际验证提供的令牌中显示的凭据和权限是否确实与授权控制器中端点的labuser的必需范围相匹配。我考虑过在被调用的端点list_systemusers()中处理验证,但是令牌没有通过连接传递。

OpenAPI 3.0中不支持

进行一些挖掘之后,我发现OpenAPI 3.0在全局API级别(即是否通过身份验证)上提供apiKey验证,但不提供对每个端点的单个作用域的支持。如果要使用单个作用域,则需要切换到OAuth安全性。但是,OpenAPI 3.1中提供了通过apiKey安全性对安全范围的支持

解决方法

解决方法

因此,就目前而言,使单个作用域的承载令牌安全性起作用的唯一方法是为每个作用域实际定义安全方案,例如

securitySchemes:
    adminuserAuth:
      type: apiKey
      description: Provide your bearer token in the format **Bearer <token>**
      name: Authorization
      in: header
      x-apikeyInfoFunc: swagger_server.controllers.authorization_controller.check_adminuserAuth
    statsuserAuth:
      type: apiKey
      description: Provide your bearer token in the format **Bearer <token>**
      name: Authorization
      in: header
      x-apikeyInfoFunc: swagger_server.controllers.authorization_controller.check_statsuserAuth
    labuserAuth:
      type: apiKey
      description: Provide your bearer token in the format **Bearer <token>** 
      name: Authorization
      in: header
      x-apikeyInfoFunc: swagger_server.controllers.authorization_controller.check_labuserAuth

然后在路径定义上添加所需的安全认证方案

security:
- labuserAuth: []
- adminuserAuth: []
x-openapi-router-controller: swagger_server.controllers.lab_controller

现在,我知道哪种授权控制器方法称为用户需要显示的必需范围,因此可以针对令牌中显示的范围进行验证。