webpack-dev-server 使用 Windows 身份验证(NTLM 身份验证)的热重载代理 IIS Express

webpack-dev-server hot reloading proxy IIS Express with Windows authentication (NTLM Authentication)

我创建了一个新的 ASP.NET Web Application -> Web API 2 项目,使用 Windows 身份验证。这在 IIS Express 中运行良好,但为了让我的 React 前端热重载,我尝试使用 webpack-dev-server 并让它代理我的 IIS Express。我之前使用过 cookie 身份验证和令牌(Bearer)身份验证都没有问题,但是使用 Windows 身份验证(NTLM 身份验证)它不起作用。

查看来自服务器的响应,我得到了预期的 401 Unauthorized (401.2) 响应 header www-authenticate: Negotiate, NTLM,但我不认为客户端 re-sends使用 Authorization: NTLM 请求。

我尝试过的浏览器(Chrome、Firefox 和 IE)也没有给我输入正确凭据的正常提示。

https://blogs.msdn.microsoft.com/chiranth/2013/09/20/ntlm-want-to-know-how-it-works/

我在 webpack.config.js 中的设置如下所示:

var proxy = 'localhost:57263';

devServer: {
    proxy: {
        '*': {
            target: 'http://' + proxy,
            changeOrigin: true,
        },
        port: 8080,
        host: '0.0.0.0',
        hot: true,
    },
}

在查看 webpack-dev-server Proxy 的文档后,我看到他们使用 http-proxy-middleware

https://webpack.github.io/docs/webpack-dev-server.html#proxy

这让我找到了这个话题并回答:

https://github.com/chimurai/http-proxy-middleware/issues/39#issuecomment-330911943

最终解决方案:

运行:

npm install agentkeepalive --save

工作代码:

var proxy = 'localhost:57263';

devServer: {
    proxy: {
        '*': {
            target: 'http://' + proxy,
            changeOrigin: true,
            agent: new agent({
                maxSockets: 100,
                keepAlive: true,
                maxFreeSockets: 10,
                keepAliveMsecs: 100000,
                timeout: 6000000,
                keepAliveTimeout: 90000 // free socket keepalive for 90 seconds
            }),
            onProxyRes: (proxyRes) => {
                var key = 'www-authenticate';
                proxyRes.headers[key] = proxyRes.headers[key] && proxyRes.headers[key].split(',');
            },
        },
        port: 8080,
        host: '0.0.0.0',
        hot: true,
    },
}