OpenAPI 的受权与认证——swagger2.0的使用

在OpenAPI 3.0时代,在对于私有API保护方面有如下几个security shcemes:api

  • HTTP authentication schemes (使用Authorization header):
    1. 基础方式
    2. Bearer
  • 在headers中添加API keys
  • OAuth2
  • OpenID Connect Discovery

第一步. 定义securitySchemes

首先你得肯定一个事情那就是全部API使用到的security schemes必须在swagger.yaml文件中全局的components->securitySchemes 部分进行定义。components->securitySchemes 中包含了全部命名的security schemes 列表,每个scheme必定符合下列类型中的其中之一:数组

  • http - 涉及HTTP的认证shemes,如:Basic, Bearer.
  • apiKey - 普通的API keys和 cookies 认证
  • oauth2 - OAuth 2
  • openIdConnect - OpenID Connect Discovery

具体请看下面这段样本代码:安全

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
复制代码

第二步. security 的使用

基础认证

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 Authenticationswagger.yaml.cookie

components:
 securitySchemes:
 basicAuth:
 type: http
 scheme: basic
    
 security:
 - basicAuth:[]

复制代码

在上面的这段代码中,type:http scheme:basic是必填项。 至于basicAuth为什么是一个空数组,是由于Basic authentication 并不存在scopes。网络

401

在私有路由在被调用时,时常会遇到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

所谓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

相关文章
相关标签/搜索