ダメ元エンジニアのお勉強おメモ

ほとんど自分用のメモです。AWS をよく触ります。Web アプリとか作ります。Raspberry Pi も好きです。

Swagger v2.0 で指定できる認証方法を全て試してみる

概要

Swagger v2.0 では下記の認証方法を指定することができる。

  • Basic 認証
  • OAuth 2.0
  • API キー 認証

securityDefinitions にて認証方法の定義を記載して、メソッド内の security にて紐付ける。

今回は試しに各認証方法の定義 & メソッドに紐づけてみた。

ちなみに OAuth 2.0 は、Client Credentials Grant のフローのみを試す。

参考にしたドキュメント

Swagger 2.0 の認証周りに関するドキュメント。

swagger.io

securityDefinitions で指定する各項目の説明。

github.com

Swagger 3.0 の認証周りに関するドキュメント。Swagger 2.0 との差分が記載されている。

swagger.io

サンプル

swagger: "2.0"
info:
  description: "This is a Sample API Spec"
  version: "1.0.0"
  title: "Sample API"
host: "sample.swagger.io"
basePath: "/v1"
schemes:
  - "https"
paths:
  /hello:
    get:
      summary: "GET Hello"
      responses:
        "200":
          description: "OK"
    post:
      summary: "POST Hello"
      responses:
        "200":
          description: "OK"
      security:
        - basicAuth: []
    put:
      summary: "PUT Hello"
      responses:
        "200":
          description: "OK"
      security:
        - OAuth2: ["readwrite"]
    delete:
      summary: "DELETE Hello"
      responses:
        "200":
          description: "OK"
      security:
        - tokenAuth: []
securityDefinitions:
  basicAuth:
    type: "basic"
  OAuth2:
    type: "oauth2"
    flow: "application"
    tokenUrl: "https://auth.swagger.io/oauth2/token"
    scopes:
      readwrite: "Grant read and write"
  tokenAuth:
    type: "apiKey"
    name: "Authorization"
    in: "header

プレビュー

全体はこんな感じ。security が付いてるメソッドには鍵マークが表示される。鍵マークをクリックすると認証方法に応じて異なるダイアログが表示される。

f:id:rkr0314:20210507233702p:plain

Basic 認証の場合。

f:id:rkr0314:20210507233716p:plain

OAuth 2.0 の場合。

f:id:rkr0314:20210507233726p:plain

API Key の場合。

f:id:rkr0314:20210507233743p:plain

おわり。