0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Swagger UIでOAuth認証をする時にauthorizationUrlを環境ごとに切り替える

Posted at

OpenAPI3.0ではserversに複数のURLを設定することで、Swagger UIでローカル/開発/本番環などリクエスト先を切り替えることができます。

openapi: 3.0.0
info:
  description: サンプルAPI
  version: 1.0.0
  title: Sample API
servers:
  - url: http://localhost:8000
    description: ローカル開発環境
  - url: https://dev.api.com
    description: 開発環境
  - url: https://api.com
    description: 本番環境

Screen Shot 2022-01-14 at 15.38.30.png

また、OAuth2.0で認証が必要な場合はauthorizationCodeに認可エンドポイントとトークンエンドポイントを設定することで、Swagger UIがOAuth認証のメニューを生成してくれます。
(次のコードは認可コードフローの例です。)

components:
  securitySchemes:
    OAuth2:
      type: oauth2
      flows:
        authorizationCode:
          authorizationUrl: https://api.com/auth
          tokenUrl: https://api.com/token

Screen Shot 2022-01-14 at 15.51.33.png

authorizationCodeについてもserversと同じように複数環境分を設定し、それがserversと一緒に切り替わってくれることを期待したのですが、authorizationCodeは複数の環境に対応しておらず、単に次のように列挙するだけではエラーになってしまいます。

components:
  securitySchemes:
    OAuth2:
      type: oauth2
      flows:
        authorizationCode:
          authorizationUrl: http://localhost:8000/auth
          tokenUrl: https://localhost:8000/token
        authorizationCode:
          authorizationUrl: https://dev.api.com/auth
          tokenUrl: https://dev.api.com/token
        authorizationCode:
          authorizationUrl: https://api.com/auth
          tokenUrl: https://api.com/token

このような場合は、authorizationCodeをドメインからの相対パスで書くことで解決できます。

components:
  securitySchemes:
    OAuth2:
      type: oauth2
      flows:
        authorizationCode:
          authorizationUrl: /auth
          tokenUrl: /token

authorizationCodeはセキュリティ上の問題からパラメータの埋め込みには対応していないようなので(参考)、環境ごとに認可・トークンエンドポイントが異なる場合は現状手立てがなく、authorizationCodeを毎回書き換えるしかなさそうです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?