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?

Swagger UIのCORSエラーの回避方法

Posted at

はじめに

Swagger UIのCORSエラーの回避方法を紹介する。Swagger UIで参照されるAPIサーバーには、CORS対策がされていない状況で、CORS Anywhereを使うことで回避する。

前提

  • APIサーバーが、既に構築されデプロイされている(自身では変更不可)

要件

  • 上記APIサーバーに対して、Swagger UIからAPIを実行できること

動作確認環境

  • Ubuntu 22.04 x86_64
  • Docker ver.20.10.17
    • Docker Compose v2.11.0

方法

CORS Anywhereサーバーを使うことで、CORSエラーを回避するためにCORSヘッダーを付与することができる。

構成要素 エンドポイント 備考
APIサーバー https://example.com/api 任意のREST APIサーバー
Swagger UIサーバー http://localhost:8080
CORS Anywhereサーバー http://localhost:8081 プロキシサーバー

Swagger UIとCORS AnywhereのDocker Composeファイルは以下のようになる。ここで、openapi.jsonは、APIサーバーのOpenAPI仕様である。

docker-compose.yml
version: "3.9"
services:
  swagger-ui:
    image: swaggerapi/swagger-ui:latest
    ports:
      - 8080:8080
    volumes:
      - ./openapi.json:/openapi.json
    environment:
      SWAGGER_JSON: /openapi.json
      PORT: 8080
      BASE_URL: /docs
    restart: always
    depends_on:
      - cors-anywhere

  cors-anywhere:
    image: testcab/cors-anywhere:latest
    ports:
      - "8081:8080"
    environment:
      - CORSANYWHERE_ALLOW_ORIGINS=*
      - CORSANYWHERE_DISABLE_HOST_CHECK=true
      - CORSANYWHERE_REQUIRE_HEADER_ORIGIN=false
    command: ["node", "server.js", "--origin-whitelist=*"]

次にOpenAPI仕様の例を示す。

  • ポイント
    • CORS Anywhereを経由するには、serversキーを以下のように設定する
      "url": "{cors.anywhere.address}/{api.address}"
      
      • {cors.anywhere.address}: CORS Anywhereサーバーアドレス
      • {api.address}: REST APIサーバーアドレス
      例:
      "url": "http://localhost:8081/https://example.com/api"
      
openapi.json API仕様例
{
  "openapi": "3.0.0",
  "info": {
    "title": "Test API",
    "version": "1.0.0"
  },
  "servers": [
    {
      "url": "http://localhost:8081/https://example.com/api"
    }
  ],
  "paths": {
    ...
  }
}

ダミーのAPIサーバーを利用したサンプルを作成したので動作を確認したい方は下記を参照。

READMEに従い、プログラムを起動して、ブラウザで、http://localhost:8080/docsにアクセスするとSwagger UIでAPIのテストができる。

image.png

Serversに、CORS Anywhereを経由してアクセスする設定となっている。

まとめ

Swagger UIのCORSエラーの回避方法を紹介した。具体的には、Swagger UIで参照されるAPIサーバーには、CORS対策がされていない状況で、CORS Anywhereを使うことで回避する方法を紹介した。今回紹介した方法は、検証環境向けであり、本番利用する場合は APIサーバー側でCORS 設定を行うことを推奨する。

参考

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?