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

7,249 阅读2分钟

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

  • 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==

注: 由于Base64非常容易被decoded, 所以一般不单独使用,而是和其他安全机制一起使用,比如: HTTPS/SSL

接下来我们可以编写Basic Authenticationswagger.yaml.

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

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

401

在私有路由在被调用时,时常会遇到unauthorized的非授权情况,这个时候返回码为401,同时使用WWW-Authenticate header, 来告知客户端没有权限访问。

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:

Authorization: Bearer <token>
components:
    securitySchemes:
        bearerAuth:
            type: http
            scheme: bearer
            bearerFormat:JWT
    
    security:
        - bearerAuth:[]

原文链接