次の方法で共有


チュートリアル: ネイティブ認証用の CORS ヘッダーを管理するように CORS プロキシ サーバーを設定する (プレビュー)

適用対象: 灰色の X 記号がある白い円。 従業員テナント 白いチェック マーク記号がある緑の円。 外部テナント (詳細情報)

このチュートリアルでは、React シングルページ アプリ (SPA) からネイティブ認証 API と対話しながら CORS ヘッダーを管理するように CORS プロキシ サーバーを設定する方法について説明します。 CORS プロキシ サーバーは、ネイティブ認証 API がクロスオリジン リソース共有 (CORS) サポートできないことを解決するソリューションです。

このチュートリアルでは、次の操作を行います。

  • CORS プロキシ サーバーを作成します。
  • ネイティブ認証 API を呼び出す CORS プロキシ サーバーを設定します。
  • React アプリを実行してテストします。

[前提条件]

CORS プロキシ サーバーを作成する

  1. React アプリのルート フォルダーに、cors.jsという名前のファイルを作成し、次のコードを追加します。

    const http = require("http");
    const https = require("https");
    const url = require("url");
    const proxyConfig = require("./proxy.config.js");
    
    http
    .createServer((req, res) => {
        const reqUrl = url.parse(req.url);
        const domain = url.parse(proxyConfig.proxy).hostname;
        if (reqUrl.pathname.startsWith(proxyConfig.localApiPath)) {
    
            const targetUrl = proxyConfig.proxy + reqUrl.pathname?.replace(proxyConfig.localApiPath, "") + (reqUrl.search || "");
    
            console.log("Incoming request -> " + req.url + " ===> " + reqUrl.pathname);
    
            const proxyReq = https.request(
                targetUrl,
                {
                    method: req.method,
                    headers: {
                        ...req.headers,
                        host: domain,
                    },
                },
                (proxyRes) => {
                    res.writeHead(proxyRes.statusCode, {
                        ...proxyRes.headers,
                        "Access-Control-Allow-Origin": "*",
                        "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
                        "Access-Control-Allow-Headers": "Content-Type, Authorization",
                    });
    
                    proxyRes.pipe(res);
                }
            );
    
            proxyReq.on("error", (err) => {
                console.error("Error with the proxy request:", err);
                res.writeHead(500, { "Content-Type": "text/plain" });
                res.end("Proxy error.");
            });
    
            req.pipe(proxyReq);
        } else {
            res.writeHead(404, { "Content-Type": "text/plain" });
            res.end("Not Found");
        }
    })
    .listen(proxyConfig.port, () => {
        console.log("CORS proxy running on http://localhost:3001");
        console.log("Proxying from " + proxyConfig.localApiPath + " ===> " + proxyConfig.proxy);
    });
    
  2. React アプリのルート フォルダーに、proxy.config.jsという名前のファイルを作成し、次のコードを追加します。

        const tenantSubdomain = "Enter_the_Tenant_Subdomain_Here";
        const tenantId = "Enter_the_Tenant_Id_Here";
    
        const config = {
            localApiPath: "/api",
            port: 3001,
            proxy: `https://${tenantSubdomain}.ciamlogin.com/${tenantId}`,
        };
        module.exports = config;
    
    • プレースホルダー Enter_the_Tenant_Subdomain_Here を見つけて、ディレクトリ (テナント) サブドメインに置き換えます。 たとえば、テナントのプライマリ ドメインが contoso.onmicrosoft.com の場合は、contoso を使用します。 テナント サブドメインがない場合は、テナントの詳細を 読み取る方法について説明します。

    • tenantId をディレクトリ (テナント) ID に置き換えます。 テナント ID がわからない場合は、テナントの詳細を読み取る方法を確認してください。

  3. package.json ファイルを開いて、次のコマンドを スクリプト オブジェクトに追加します。

    "cors": "node cors.js",
    

この時点で、React アプリと CORS プロキシ サーバーを実行する準備ができました。

アプリを実行してテストする

  1. ターミナル ウィンドウを開き、アプリのルート フォルダーに移動します。

    cd reactspa
    
  2. CORS プロキシ サーバーを起動するには、ターミナルで次のコマンドを実行します。

    npm run cors
    
  3. React アプリを起動するには、別のターミナル ウィンドウを開き、次のコマンドを実行します。

    cd reactspa
    npm start
    
  4. Web ブラウザーを開き、http://localhost:3000/に移動します。 サインアップ フォームが表示されます。

  5. アカウントにサインアップするには、詳細を入力し、サインアップ ボタンを選択し、プロンプトに従います。

この時点で、ネイティブ認証 API を使用してユーザーをサインアップできる React アプリが正常に作成されました。 次に、React アプリを更新してユーザーをサインインさせたり、ユーザーのパスワードをリセットしたりできます。

CORS プロキシ サーバーに関する追加情報

このチュートリアルでは、ローカル CORS サーバーを設定します。 ただし、テスト環境で説明されているように、Azure 関数アプリを使用することで CORS ヘッダーを管理するようにリバース プロキシ サーバーを設定できます。

運用環境では、「Azure Function App を使用して CORS プロキシ サーバーを設定することで、ネイティブ認証 API を使用するシングルページ アプリのリバース プロキシを設定する」の手順を使用できます。