简体   繁体   English

http-proxy-middleware,如何复制所有/cookie 标头

[英]http-proxy-middleware, how to copy all/cookie headers

I am using lite server by John Papa with HTTP proxy middleware by chimurai as a dev server.我正在使用 John Papa 的 lite 服务器和 chimurai 的 HTTP 代理中间件作为开发服务器。 the problem is with my session cookie, I cannot persist the session cookie that comes from the real server.问题出在我的会话 cookie 上,我无法保留来自真实服务器的会话 cookie。 I saw this solution: https://github.com/chimurai/http-proxy-middleware/issues/78我看到了这个解决方案: https : //github.com/chimurai/http-proxy-middleware/issues/78

but I see no resemblance to my bs-config.js:但我发现与我的 bs-config.js 没有相似之处:

var proxy = require('http-proxy-middleware');

module.exports = {
    port: 3003,
    server: {
        middleware: {
            1: proxy('demo/webservice/jaxrs', {
                target: 'https://localhost:8443',
                secure: false, // disable SSL verification
                changeOrigin: true   // for vhosted sites, changes host header to match to target's host
            }),
            2: require('connect-history-api-fallback')({index: '/index.html', verbose: true})
        }
    }
};

Does someone knows how to merge this two?有人知道如何合并这两个吗?

UPDATE: this is part of the response headers:更新:这是响应标头的一部分:

set-cookie:JSESSIONID=620083CD7AEB7A6CC5772AC800E673E3; Path=/appServer/webservice/jaxrs; Secure
strict-transport-security:max-age=31622400; includeSubDomains
Transfer-Encoding:chunked

UPDATE2: I think my config should look like this: UPDATE2:我认为我的配置应该是这样的:

var proxy = require('http-proxy-middleware');

function relayRequestHeaders(proxyReq, req) {
    Object.keys(req.headers).forEach(function (key) {
        proxyReq.setHeader(key, req.headers[key]);
    });
};

function relayResponseHeaders(proxyRes, req, res) {
    Object.keys(proxyRes.headers).forEach(function (key) {
            res.append(key, proxyRes.headers[key]);
        });
};

module.exports = {
    port: 3003,
    server: {
        middleware: {
            1: proxy('/skybox', {
                target: 'https://localhost:8443',
                secure: false, // disable SSL verification
                changeOrigin: true,   // for vhosted sites, changes host header to match to target's host
                onProxyReq: relayRequestHeaders,
                onProxyRes: relayResponseHeaders
            }),
            2: require('connect-history-api-fallback')({index: '/index.html', verbose: true})
        }
    }
};

but now res.append is undefined :(但现在 res.append 是未定义的 :(

try it:试试看:

var cookie;
function relayRequestHeaders(proxyReq, req) {
  if (cookie) {
    proxyReq.setHeader('cookie', cookie);
  }
};

function relayResponseHeaders(proxyRes, req, res) {
  var proxyCookie = proxyRes.headers["set-cookie"];
  if (proxyCookie) {
    cookie = proxyCookie;
  }
};

It's working with lite-server它与精简服务器一起工作

Not sure how your localhost:3003 is configured;不确定您的 localhost:3003 是如何配置的; With or without https: ...有或没有https: ...

Say you are using http://localhost:3000 (not https:);假设您使用的是http://localhost:3000 (不是 https:); The Secure cookie attribute from your target might be the cause for your browser to omit the cookie.目标的Secure cookie 属性可能是浏览器忽略 cookie 的原因。

4.1.2.5. 4.1.2.5. The Secure Attribute安全属性

The Secure attribute limits the scope of the cookie to "secure" Secure 属性将 cookie 的范围限制为“安全”
channels (where "secure" is defined by the user agent).通道(其中“安全”由用户代理定义)。 When a当一个
cookie has the Secure attribute, the user agent will include the cookie 具有 Secure 属性,用户代理将包括
cookie in an HTTP request only if the request is transmitted over a仅当请求通过
secure channel (typically HTTP over Transport Layer Security (TLS)安全通道(通常是 HTTP over Transport Layer Security (TLS))

source: https://tools.ietf.org/html/rfc6265#section-4.1.2.5来源: https : //tools.ietf.org/html/rfc6265#section-4.1.2.5

Browsers may omit cookies based on the algorithm described in: https://tools.ietf.org/html/rfc6265#section-5.4浏览器可能会根据以下所述的算法省略 cookie: https : //tools.ietf.org/html/rfc6265#section-5.4

Try removing the Secure Attribute and see if that helps尝试删除Secure Attribute ,看看是否有帮助

B.Ma's answer give me a hint to solve my problem with the webpack-dev-server which probably uses the http-proxy-middleware under the hood to proxy the request. B.Ma 的回答给了我一个提示来解决我的 webpack-dev-server 问题,它可能在引擎盖下使用 http-proxy-middleware 来代理请求。 The problem comes with the httpOnly cookies and this approach solved it.问题来自 httpOnly cookie,这种方法解决了它。 Here is my config that I used in the webpack.conf.js:这是我在 webpack.conf.js 中使用的配置:

let myappSessionValidationCookie = '';

module.exports = {
    ...
    devServer: {
        publicPath: 'http://localhost:9000/',
        ...
        proxy: {
            '/api': {
                target: 'http://localhost/myapp',
                changeOrigin: true,
                onProxyReq: function (proxyReq) {
                    if (myappSessionValidationCookie) {
                        proxyReq.setHeader('cookie', myappSessionValidationCookie);
                    }
                },
                onProxyRes: function (proxyRes) {
                    const proxyCookie = proxyRes.headers['set-cookie'];
                    if (proxyCookie) {
                        myappSessionValidationCookie = proxyCookie;
                    }
                },
            },
        },
    },
});

Some explanation for the configuration.配置的一些解释。 I have a backend that is serving the app's api under the localhost/myapp/api/* and sets a httpOnly cookie that is for authentication purposes.我有一个后端,它在 localhost/myapp/api/* 下为应用程序的 api 提供服务,并设置了一个用于身份验证的 httpOnly cookie。 That header (set-cookie) was not transferred by the proxy to the new location (localhost:9000/myapp/api/*) so the browser is not keeping it and all following requests were without this cookie and failed.该标头 (set-cookie) 没有被代理传输到新位置 (localhost:9000/myapp/api/*),因此浏览器没有保留它,并且所有后续请求都没有这个 cookie 并且失败了。 All the credits goes to B.Ma.所有的学分都归于 B.Ma。 Many thanks for the post!!!非常感谢你的帖子!!!

In my case setting "cookieDomainRewrite": "localhost", works.在我的情况下,设置"cookieDomainRewrite": "localhost",有效。 This allows the browser to setup correctly the cookies since the domain would match这允许浏览器正确设置 cookie,因为域将匹配

Below complete config for setupProxy.js in React:下面是 React 中setupProxy.js完整配置:

const {createProxyMiddleware} = require('http-proxy-middleware');

module.exports = function (app) {
    app.use(
        '/api',
        createProxyMiddleware({
            target: 'http://localhost:8000',
            changeOrigin: true,
            cookieDomainRewrite: "localhost",
        })
    );
};
// Set up the proxy.
if (dev) {
  const { createProxyMiddleware } = require('http-proxy-middleware')
  server.use(
    '/api',
    createProxyMiddleware({
      target: 'https://api.example.com/',
      changeOrigin: true,
      cookieDomainRewrite: 'localhost',
      // logLevel: 'debug',
    })
  )
}

This is my configuration.这是我的配置。 I think the point is with我认为重点是

cookieDomainRewrite: 'localhost',

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM