You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何限制Webpack Module Federation中remoteEntry.js的访问权限

限制remoteEntry.js访问权限的解决方案

1. 基于HTTP Referer校验

在微应用的服务器(Nginx、Apache或Node.js服务)上配置Referer校验,仅允许来自壳应用域名的请求访问remoteEntry.js。

  • Nginx配置示例:
    在remoteEntry.js对应的location块中添加规则:

    location /remoteEntry.js {
        valid_referers example-shell.com *.example-shell.com;
        if ($invalid_referer) {
            return 403;
        }
        # 保留原有静态文件服务配置
        root /path/to/app1/static;
    }
    

    把example-shell.com替换为壳应用的实际域名,*.example-shell.com匹配其所有子域名,不符合条件的请求直接返回403禁止访问。

  • Node.js Express示例:
    编写中间件校验请求Referer:

    app.get('/remoteEntry.js', (req, res, next) => {
        const allowedDomains = ['https://example-shell.com', 'https://admin.example-shell.com'];
        const requestReferer = req.get('Referer');
        if (!requestReferer || !allowedDomains.some(domain => requestReferer.startsWith(domain))) {
            return res.status(403).send('Forbidden');
        }
        next();
    });
    

2. 自定义请求头令牌校验

给壳应用的请求添加专属自定义头,微应用服务器校验该头的合法性。

  • 壳应用Module Federation配置:
    在remotes中通过自定义fetch函数添加令牌:
    remotes: {
        app1: {
            url: 'https://app1.example.com/remoteEntry.js',
            format: 'esm',
            fetch: (url) => fetch(url, {
                headers: {
                    'X-MFE-Auth': 'your-unique-secret-token'
                }
            })
        }
    }
    
  • 微应用服务器校验:
    Nginx配置示例:
    location /remoteEntry.js {
        if ($http_x_mfe_auth != 'your-unique-secret-token') {
            return 403;
        }
        root /path/to/app1/static;
    }
    
    注意:令牌需定期更新,若壳应用是纯前端渲染,令牌可能被前端代码暴露,建议搭配其他校验方式使用,或仅用于服务端渲染的壳应用场景。

3. IP白名单限制

如果壳应用的服务器IP固定,可直接在微应用服务器配置IP白名单,仅允许指定IP/IP段访问。

  • Nginx配置示例:
    location /remoteEntry.js {
        allow 192.168.1.100; # 壳应用服务器固定IP
        allow 10.0.0.0/24;    # 壳应用所在IP段
        deny all;
        root /path/to/app1/static;
    }
    
    该方式适合内部部署、IP固定的微前端架构场景。

若壳应用与微应用同域或主域相同,可利用Cookie进行身份校验:

  • 壳应用用户登录后,在主域下设置合法的Session Cookie;
  • 微应用服务器校验请求中是否携带有效Cookie,仅允许符合条件的请求访问。
  • Nginx配置示例(假设Cookie名为mfe_valid_session):
    location /remoteEntry.js {
        if ($cookie_mfe_valid_session = "") {
            return 403;
        }
        # 可选:联动后端接口校验Cookie有效性
        proxy_pass http://your-auth-service/verify-session?session=$cookie_mfe_valid_session;
        root /path/to/app1/static;
    }
    

注意事项

  • 单一校验方式存在风险(比如Referer可被伪造),建议组合使用多种方式(如Referer+令牌校验);
  • 若需开放给多个指定应用,只需扩展允许的域名列表、令牌或IP范围即可;
  • 调试时需确保壳应用请求能正常通过校验,非法请求返回403。

内容的提问来源于stack exchange,提问作者I'm nidhin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 10:30:15