身份验证
Swagger 2.0 允许您为 API 定义以下身份验证类型:
请点击上方链接查看这些身份验证类型的具体示例,或继续阅读以了解如何一般性地描述身份验证。
身份验证通过使用 securityDefinitions
和 security
关键字来描述。您使用 securityDefinitions
定义 API 支持的所有身份验证类型,然后使用 security
将特定身份验证类型应用于整个 API 或单个操作。
securityDefinitions
部分用于定义 API 支持的所有安全方案(身份验证类型)。它是一个名称->定义映射,将任意名称映射到安全方案定义。在这里,API 支持三个名为 BasicAuth、ApiKeyAuth 和 OAuth2 的安全方案,这些名称将用于在其他地方引用这些安全方案
1securityDefinitions:2 BasicAuth:3 type: basic4 ApiKeyAuth:5 type: apiKey6 in: header7 name: X-API-Key8 OAuth2:9 type: oauth210 flow: accessCode11 authorizationUrl: https://example.com/oauth/authorize12 tokenUrl: https://example.com/oauth/token13 scopes:14 read: Grants read access15 write: Grants write access16 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 中定义的安全方案。
1security:2 - ApiKeyAuth: []3 - OAuth2: [read, write]
全局 security
可以在单个操作中被覆盖,以使用不同的身份验证类型、不同的 OAuth 2 范围或完全不使用身份验证
1paths:2/billing_info:3 get:4 summary: Gets the account billing info5 security:6 - OAuth2: [admin] # Use OAuth with a different scope7 responses:8 200:9 description: OK10 401:11 description: Not authenticated12 403:13 description: Access token does not have the required scope14
15/ping:16 get:17 summary: Checks if the server is running18 security: [] # No security19 responses:20 200:21 description: Server is up and running22 default:23 description: Something is wrong
使用多种身份验证类型
某些 REST API 支持多种身份验证类型。security
部分允许您使用逻辑 OR 和 AND 组合安全要求以达到所需结果。security
使用以下逻辑:
1security: # A OR B2 - A3 - B4
5security: # A AND B6 - A7 B8
9security: # (A AND B) OR (C AND D)10 - A11 B12 - C13 D
也就是说,security
是一个哈希映射数组,其中每个哈希映射包含一个或多个命名安全方案。哈希映射中的项目使用逻辑 AND 组合,数组中的项目使用逻辑 OR 组合。通过 OR 组合的安全方案是替代方案——在给定上下文中可以使用其中任何一个。通过 AND 组合的安全方案必须在同一请求中同时使用。在这里,我们可以使用基本身份验证或 API 密钥
1security:2 - basicAuth: []3 - apiKey: []
在这里,API 要求请求中包含一对 API 密钥。
1security:2 - apiKey1: []3 apiKey2: []
在这里,我们可以使用 OAuth 2 或一对 API 密钥。
1security:2 - oauth2: [scope1, scope2]3 - apiKey1: []4 apiKey2: []
常见问题
“securitySchemeName: [ ]”中的 [ ] 是什么意思?
[]
是 YAML/JSON 中空数组的语法。Swagger 规范要求 security
数组中的项目指定所需范围的列表,例如:
1security:2 - securityA: [scopeA1, scopeA2]3 - securityB: [scopeB1, scopeB2]
范围仅与 OAuth 2 一起使用,因此基本和 API 密钥 security
项使用空数组代替。
1security:2 - oauth2: [scope1, scope2]3 - BasicAuth: []4 - ApiKeyAuth: []