2
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?

CORSの同一オリジンと異なるオリジンについて

Posted at

はじめに

CORSのオリジンについて簡単にまとめることにしました。

CORSとは

CORSは「Cross-Origin Resource Sharing」の略です。

ブラウザにはセキュリティ機能として同一オリジンポリシーがあり、あるオリジン(例:http:// example.com)から別のオリジン(例:http:// api.example.com)にアクセスすることを、デフォルトでは禁止しています。

CORS は この制限を安全に緩和する仕組みになります。

オリジンとは

オリジンとは、ブラウザが「安全かどうか」を判断するための単位です。
具体的には プロトコル + ドメイン + ポート の組み合わせで決まります。

URL プロトコル ドメイン ポート オリジン
http://example.com/app1/index.html http example.com 80 http://example.com:80
http://example.com/app2/index.html http example.com 80 http://example.com:80
https://example.com https example.com 443 https://example.com:443
http://example.com:8080 http example.com 8080 http://example.com:8080

同一オリジン

プロトコル・ドメイン・ポートがすべて同じ

例:

http://example.com/app1/index.html
http://example.com/app2/index.html
http://example.com:80

※パスが違っても同一オリジンとみなされる
※80や443といった数値は省略されているデフォルトポートというもので下記は一緒の扱いになります。
http://example.com
http://example.com:80

異なるオリジン

同一オリジンと比べた際下記は異なるオリジンとなります。

https://example.com → プロトコルが違う
http://example.com:8080 → ポートが違う

CORSとオリジンの関係

下記はサーバー側の設定方法になります

import express from "express";
import cors from "cors";

const app = express();

// 全てのオリジンを許可
app.use(cors());

// 特定オリジンのみ許可
app.use(cors({
  origin: "http://localhost:3000"
}));

app.listen(5000);

フロント バックエンド 同一オリジン
http://localhost:3000 http://localhost:3000 ✅ 同一

同一オリジン(プロトコル・ドメイン・ポートがすべて同じ)なら制限なし

フロント バックエンド 異なるオリジン
http://localhost:3000 http://localhost:5000 ❌ 別オリジン

別オリジンだと、JavaScript からの fetch や XHR でデータを読み込めません

まとめ

CORSを使用することで簡単にサーバーへのアクセスを管理することを理解しました。
オリジンを知っているだけけでも、制御をすることによりアクセスを防げることが今回学んだ中で一番重要だと感じました。

JISOUのメンバー募集中!

プログラミングコーチングJISOUでは、新たなメンバーを募集しています。
日本一のアウトプットコミュニティでキャリアアップしませんか?
興味のある方は、ぜひホームページをのぞいてみてください!

2
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
2
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?