教程:设置 CORS 代理服务器以管理本机身份验证的 CORS 标头(预览版)

适用于:带灰色 X 号的白色圆圈。 员工租户 带白色对号的绿色圆圈。 外部租户(了解详细信息

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

在本教程中,你将:

  • 创建 CORS 代理服务器。
  • 设置 CORS 代理服务器以调用本机身份验证 API。
  • 运行并测试 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,并将其替换为 Directory (tenant) 子域。 例如,如果租户主域名是 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. 若要注册帐户,请输入详细信息,选择 注册 按钮,然后按照提示作。

此时,你已成功创建了一个 React 应用,该应用可以使用本机身份验证 API 注册用户。 接下来,可以更新 React 应用以登录用户或重置用户的密码。

有关 CORS 代理服务器的其他信息

在本教程中,将设置本地 CORS 服务器。 但是,可以使用 Azure 函数应用设置反向代理服务器来管理 CORS 标头,如测试环境中所述

在生产环境中,您可以使用 中的步骤,通过 Azure Function App 为使用本机身份验证 API 的单页应用设置反向代理,从而配置您的 CORS 代理服务器。