什么是'范围'用于招摇安全方案对象的领域?

时间:2016-07-14 10:09:20

标签: swagger openapi

petstore_auth:
  type: oauth2
  authorizationUrl: http://swagger.io/api/oauth/dialog
  flow: implicit
  scopes:
    write:pets: modify pets in your account
    read:pets: read your pets

这是来自the Swagger Specification的securityDefinitions示例。 写:宠物读取:ptes 的目的是什么?是路径的一些类别吗?

1 个答案:

答案 0 :(得分:10)

写:宠物读取:宠物Oauth2 scopes且与OpenAPI(fka.Swagger)operations categorization无关。

Oauth2范围

当使用Oauth保护API时,范围用于为API使用者提供不同的权限/特权。范围由名称定义(您可以随意使用)。

Oauth范围SwaggerUI中的授权可以充当API使用者: enter image description here

在这种情况下,这个oauth2安全API提出了2个范围:

  • 阅读:宠物:在您的帐户中修改宠物
  • 写:宠物:读你的宠物

在使用OpenAPI(fka.Swagger)规范描述API时,您可以定义这些范围,如问题所示。

但是,如果您未声明这些范围涵盖哪些操作,则仅定义这些范围是无用的。 这是通过将其添加到操作来完成的:

     security:
        - petstore_auth:
          - read:pets

在此示例中,仅当允许API使用read:pets范围时,API操作员才能访问该操作。 请注意,单个操作可以属于多个oauth2范围,也可以属于多个安全定义。

您可以在此处详细了解OpenAPI(fka.Swagger)中的安全性

OpenAPI(fka.Swagger)操作分类

无论OAuth2范围如何,如果您需要对API的操作进行分类,您可以使用tags

      tags:
        - pets

通过将此添加到操作中,它将被放入类别pets中。 单个操作可以属于多个类别。

SwaggerUI使用这些类别重新组合操作。在下面的屏幕截图中,我们可以看到3个类别(宠物,商店和用户): enter image description here 您可以在此处阅读有关类别的更多信息:

以下是使用Oauth2范围和类别的完整示例

swagger: "2.0"
info:
  version: "1.0.0"
  title: Swagger Petstore

securityDefinitions:
  petstore_auth:
    type: oauth2
    authorizationUrl: http://petstore.swagger.io/api/oauth/dialog
    flow: implicit
    scopes:
      write:pets: modify pets in your account
      read:pets: read your pets

paths:
  /pets/{petId}:
    parameters:
      - in: path
        name: petId
        description: ID of pet that needs to be fetched
        required: true
        type: integer
        format: int64
    get:
      tags:
        - pets
      summary: Find pet by ID
      responses:
        "404":
          description: Pet not found
        "200":
          description: A pet
          schema:
            $ref: "#/definitions/Pet"
      security:
        - petstore_auth:
          - read:pets
    delete:
      tags:
        - pets
      summary: Deletes a pet
      responses:
        "404":
          description: Pet not found
        "204":
          description: Pet deleted
      security:
        - petstore_auth:
          - write:pets

definitions:
  Pet:
    type: object
    properties:
      id:
        type: integer
        format: int64
      name:
        type: string
        example: doggie