在OpenAPI 3.0時代,在對於私有API保護方面有如下幾個security shcemes:api
首先你得肯定一個事情那就是全部API使用到的security schemes必須在swagger.yaml文件中全局的components->securitySchemes
部分進行定義。components->securitySchemes
中包含了全部命名的security schemes
列表,每個scheme
必定符合下列類型中的其中之一:數組
具體請看下面這段樣本代碼:安全
components:
securitySchemes:
BasicAuth:
type: http
sheme: basic
BearerAuth:
type: http
sheme: bearer
ApiKeyAuth:
type: apiKey
in: header
name: X-API-Key
OpenID:
type: openIdConnect
openIdConnectUrl: https://xxxxx/xxxx
OAuth2:
type: oauth2
flow:
authorizationCode:
authorizationUrl: https://xxxx/xxxxx
tokenUrl: https://xxxx/xxxx
scopes:
read: Grants read accesss
write: Grants write access
admin: Grants access to admin operations
複製代碼
Basic Authentication 是內置在HTTP協議中的簡單的認證scheme. 客戶端在發送請求的時候會攜帶Authorization(受權)header,在這個header中會包含關鍵字Basic
,好比咱們在發送一個http請求的時候在header中帶有demo/p@550rd
這樣的用戶名和密碼的base64-encoded 字符串,在Header中它就是Authorization:Basic ZGVtbzpwQDU1zbyza==
bash
注: 因爲Base64很是容易被decoded, 因此通常不單獨使用,而是和其餘安全機制一塊兒使用,好比: HTTPS/SSL服務器
接下來咱們能夠編寫Basic Authentication
的swagger.yaml
.cookie
components:
securitySchemes:
basicAuth:
type: http
scheme: basic
security:
- basicAuth:[]
複製代碼
在上面的這段代碼中,type:http scheme:basic是必填項。 至於basicAuth爲什麼是一個空數組,是由於Basic authentication 並不存在scopes。網絡
在私有路由在被調用時,時常會遇到unauthorized的非受權狀況,這個時候返回碼爲401,同時使用WWW-Authenticate header, 來告知客戶端沒有權限訪問。post
paths:
/something:
get:
...
responses:
...
'401':
$ref: '#/components/responses/UnauthorizedError'
post:
...
responses:
...
'401':
$ref: '#/components/responses/UnauthorizedError'
...
components:
responses:
UnauthorizedError:
description: Authentication information is missing or invalid
headers:
WWW_Authenticate:
schema:
type: string
複製代碼
所謂Bearer Authentication 又稱爲token Authentication,和Basic authentication同樣,Bearer Authentication只能用於HTTPS.所謂token就是服務器生成的一個令牌,客戶端在發送網絡請求時必須在Authorization header中包含token:spa
Authorization: Bearer <token>
複製代碼
components:
securitySchemes:
bearerAuth:
type: http
scheme: bearer
bearerFormat:JWT
security:
- bearerAuth:[]
複製代碼
原文連接code