共用方式為


設定 CORS Proxy 伺服器來管理原生驗證 JavaScript SDK 的 CORS 標頭

適用於帶有白色核取記號符號的綠色圓圈,表示下列內容適用於外部租用戶。 外部租用戶 (深入瞭解

在本指南中,您將瞭解如何設定本機 CORS Proxy 伺服器來管理 CORS 標頭,同時從單頁應用程式與原生驗證 API 互動(SPA)。 CORS Proxy 伺服器是原生驗證 API 無法支援 跨原始來源資源分享 (CORS)的解決方案。

您可以使用本文中設定的 CORS 伺服器進行本機應用程式開發。 或者:

建立 CORS Proxy 伺服器

  1. 在 SPA 的根資料夾中,建立名為 cors.js的檔案,然後新增下列程式代碼:

    const http = require("http");
    const https = require("https");
    const url = require("url");
    const proxyConfig = require("./proxy.config");
    
    const extraHeaders = [
        "x-client-SKU",
        "x-client-VER",
        "x-client-OS",
        "x-client-CPU",
        "x-client-current-telemetry",
        "x-client-last-telemetry",
        "client-request-id",
    ];
    http.createServer((req, res) => {
        const reqUrl = url.parse(req.url);
        const domain = url.parse(proxyConfig.proxy).hostname;
    
        // Set CORS headers for all responses including OPTIONS
        const corsHeaders = {
            "Access-Control-Allow-Origin": "*",
            "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
            "Access-Control-Allow-Headers": "Content-Type, Authorization, " + extraHeaders.join(", "),
            "Access-Control-Allow-Credentials": "true",
            "Access-Control-Max-Age": "86400", // 24 hours
        };
    
        // Handle preflight OPTIONS request
        if (req.method === "OPTIONS") {
            res.writeHead(204, corsHeaders);
            res.end();
            return;
        }
    
        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 newHeaders = {};
            for (let [key, value] of Object.entries(req.headers)) {
                if (key !== 'origin') {
                    newHeaders[key] = value;
                }
            }
    
            const proxyReq = https.request(
                targetUrl,
                {
                    method: req.method,
                    headers: {
                        ...newHeaders,
                        host: domain,
                    },
                },
                (proxyRes) => {
                    res.writeHead(proxyRes.statusCode, {
                        ...proxyRes.headers,
                        ...corsHeaders,
                    });
    
                    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. 在 SPA 的根資料夾中,建立名為 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替換它。 如果您沒有租用戶識別碼,請了解如何讀取租用戶詳細資料

  3. 開啟 SPA 的package.json 檔案,然後在 scripts 物件中新增下列命令:

    "cors": "node cors.js",
    

此時,CORS Proxy 伺服器已準備好執行。

執行 CORS 伺服器

若要啟動 CORS Proxy 伺服器,請在終端機中執行下列命令:

npm run cors