身份验证
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 密钥或 OAuth 2 对 API 调用进行身份验证。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: []