设置 CORS 代理服务器以管理本机身份验证 JavaScript SDK 的 CORS 标头

适用于绿色圆圈,带有白色复选标记符号,指示以下内容适用于外部租户。 外部租户(了解详细信息

本指南介绍如何设置本地 CORS 代理服务器以管理 CORS 标头,同时从单页应用(SPA)与本机身份验证 API 交互。 如果本机身份验证 API 无法支持 跨源资源共享 (CORS),解决方案是 CORS 代理服务器。

可以使用本文中设置的 CORS 服务器进行本地应用开发。 另一方面:

创建 CORS 代理服务器

  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,并将其替换为 Directory (tenant) 子域。 例如,如果租户主域名是 contoso.onmicrosoft.com,请使用 contoso。 如果没有租户子域,请了解如何 阅读租户详细信息

    • tenantId 并将其替换为目录(租户)ID。 如果没有租户 ID,请了解如何读取租户详细信息

  3. 打开 SPA 的package.json 文件,然后在 脚本 对象中添加以下命令:

    "cors": "node cors.js",
    

此时,CORS 代理服务器已准备好运行。

运行 CORS 服务器

若要启动 CORS 代理服务器,请在终端中运行以下命令:

npm run cors