跳到内容

身份验证

Swagger 2.0 允许您为 API 定义以下身份验证类型

  • 基本身份验证
  • API 密钥(作为标头或查询字符串参数)
  • OAuth 2 常见流程(授权码、隐式、资源所有者密码凭据、客户端凭据)

请点击上面的链接查看这些身份验证类型的具体示例,或继续阅读以了解如何描述身份验证。

通过使用 securityDefinitionssecurity 关键字来描述身份验证。您可以使用 securityDefinitions 定义 API 支持的所有身份验证类型,然后使用 security 将特定的身份验证类型应用于整个 API 或单独的操作。

securityDefinitions 部分用于定义 API 支持的所有安全方案(身份验证类型)。它是一个名称 -> 定义映射,将任意名称映射到安全方案定义。这里,API 支持三种名为 BasicAuthApiKeyAuthOAuth2 的安全方案,这些名称将用于从其他地方引用这些安全方案

1
securityDefinitions:
2
BasicAuth:
3
type: basic
4
ApiKeyAuth:
5
type: apiKey
6
in: header
7
name: X-API-Key
8
OAuth2:
9
type: oauth2
10
flow: accessCode
11
authorizationUrl: https://example.com/oauth/authorize
12
tokenUrl: https://example.com/oauth/token
13
scopes:
14
read: Grants read access
15
write: Grants write access
16
admin: Grants read and write access to administrative information

每个安全方案的 type 可以是

  • basic 用于基本身份验证
  • apiKey 用于 API 密钥
  • oauth2 用于 OAuth 2

其他必需属性取决于安全类型。有关详细信息,请查看Swagger 规范或我们的 基本身份验证API 密钥 示例。

在您在 securityDefinitions 中定义安全方案后,可以通过在根级别或操作级别添加 security 部分,将其应用于整个 API 或单独的操作。当在根级别使用时,security 会将指定的安全方案全局应用于所有 API 操作,除非在操作级别被覆盖。

在以下示例中,可以使用 API 密钥或 OAuth 2 对 API 调用进行身份验证。ApiKeyAuthOAuth2 名称引用之前在 securityDefinitions 中定义的安全方案。

1
security:
2
- ApiKeyAuth: []
3
- OAuth2: [read, write]

全局 security 可以在单独的操作中被覆盖,以使用不同的身份验证类型、不同的 OAuth 2 范围或根本不进行身份验证

1
paths:
2
/billing_info:
3
get:
4
summary: Gets the account billing info
5
security:
6
- OAuth2: [admin] # Use OAuth with a different scope
7
responses:
8
200:
9
description: OK
10
401:
11
description: Not authenticated
12
403:
13
description: Access token does not have the required scope
14
15
/ping:
16
get:
17
summary: Checks if the server is running
18
security: [] # No security
19
responses:
20
200:
21
description: Server is up and running
22
default:
23
description: Something is wrong

使用多种身份验证类型

某些 REST API 支持多种身份验证类型。security 部分允许您使用逻辑 OR 和 AND 组合安全要求,以实现所需的结果。security 使用以下逻辑

1
security: # A OR B
2
- A
3
- B
4
5
security: # A AND B
6
- A
7
B
8
9
security: # (A AND B) OR (C AND D)
10
- A
11
B
12
- C
13
D

也就是说,security 是哈希图数组,其中每个哈希图包含一个或多个命名的安全方案。哈希图中的项目使用逻辑 AND 组合,数组项目使用逻辑 OR 组合。通过 OR 组合的安全方案是备选项,在给定上下文中可以使用任何一个。通过 AND 组合的安全方案必须在同一请求中同时使用。这里,我们可以使用基本身份验证或 API 密钥

1
security:
2
- basicAuth: []
3
- apiKey: []

这里,API 要求在请求中包含一对 API 密钥

1
security:
2
- apiKey1: []
3
apiKey2: []

这里,我们可以使用 OAuth 2 或一对 API 密钥

1
security:
2
- oauth2: [scope1, scope2]
3
- apiKey1: []
4
apiKey2: []

常见问题解答

“securitySchemeName: [ ]” 中的 [ ] 是什么意思?

[] 是 YAML/JSON 中空数组的语法。Swagger 规范要求 security 数组中的项目指定所需范围的列表,如下所示

1
security:
2
- securityA: [scopeA1, scopeA2]
3
- securityB: [scopeB1, scopeB2]

范围仅与 OAuth 2 一起使用,因此基本和 API 密钥 security 项目改为空数组。

1
security:
2
- oauth2: [scope1, scope2]
3
- BasicAuth: []
4
- ApiKeyAuth: []

参考

securityDefinitions

security

没有找到你要找的东西?咨询社区
发现错误?请告诉我们