跳到内容

身份验证

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 调用可以使用 API 密钥或 OAuth 2 进行身份验证。ApiKeyAuth 和 OAuth2 名称指的是之前在 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

没有找到您要找的内容?咨询社区
发现错误?告诉我们

© . All rights reserved.