基本身份验证
基本身份验证是一种非常简单的身份验证方案,它内置于 HTTP 协议中。客户端发送带有 Authorization 头的 HTTP 请求,该头包含 Basic
单词,后跟一个空格和一个 base64 编码的 username:password
字符串。例如,包含 demo
/ p@55w0rd
凭据的头将被编码为
1Authorization: Basic ZGVtbzpwQDU1dzByZA==
注意:由于 base64 很容易解码,基本身份验证应仅与 HTTPS/SSL 等其他安全机制一起使用。
基本身份验证很容易定义。在全局 securityDefinitions
部分中,添加一个包含 type: basic
和任意名称(在此示例中为 basicAuth)的条目。然后,通过使用 security
部分将安全性应用于整个 API 或特定操作。
1securityDefinitions:2 basicAuth:3 type: basic4
5# To apply Basic auth to the whole API:6security:7 - basicAuth: []8
9paths:10 /something:11 get:12 # To apply Basic auth to an individual operation:13 security:14 - basicAuth: []15 responses:16 200:17 description: OK (successfully authenticated)
401 响应
您还可以定义针对缺少或不正确凭据的请求返回的 401“未授权”响应。此响应包括 WWW-Authenticate
头,您可能需要提及。与其他常见响应一样,401 响应可以在全局 responses
部分中定义,并从多个操作中引用。
1paths:2 /something:3 get:4 ...5 responses:6 ...7 401:8 $ref: '#/responses/UnauthorizedError'9 post:10 ...11 responses:12 ...13 401:14 $ref: '#/responses/UnauthorizedError'15responses:16 UnauthorizedError:17 description: Authentication information is missing or invalid18 headers:19 WWW_Authenticate:20 type: string