Persisting a cookie based session over node-http-proxy

这一生的挚爱 提交于 2019-12-03 06:32:00

I did what you are asking by manually looking at the response, seeing if it is a set-cookie, snipping off the JSESSSIONID, storing it in a variable, and passing it on all subsequent requests as a header. This way the reverse proxy acts as a cookie.

enter code on('proxyReq', function(proxyReq){ proxyReq.setHeader('cookie', 'sessionid=' + cookieSnippedValue) 

Hi @tomswift does your local server run on http protocol, but the session cookie receive from the remote server carry with Secure; like:

'set-cookie':
[ 'JSESSIONID=COOKIEWITHSECURE98123; Path=/;HttpOnly;Secure;']

If so, before your local server response to the client, extract set-cookie from the original response(response from remote server to local server) header, remove the Secure; and put the rest of it into the proxy response (response from local server to client ) header like:

'set-cookie':
[ 'JSESSIONID=COOKIEWITHSECURE98123; Path=/;HttpOnly;']

then the client will take the session cookie automatically.

Hope it may help.

Ideally the job of a proxy is to just forward a request to the destination, and should not strip off critical headers like cookies, But if it is, i think you should file a issue against them here https://github.com/nodejitsu/node-http-proxy/issues.

Also you said the request headers never include the cookie, Is it possible the client never received it?

I found a way to implement this by forking and modifying node-http-proxy. It serves my current purpose which is a development environment. For any sort of serious consideration it needs to be fleshed out into a more legitimate solution.

The details can be found in the issue I filed in GitHub: https://github.com/nodejitsu/node-http-proxy/issues/236#issuecomment-5334457

I would love some input on this solution, especially if I'm going completely in the wrong direction.

I had similar problems that cookies were not passed forward to the client. Solution:

  1. get cookie from proxy response
  2. set it in proxy request, with slightly modified value
let cookie;
const webpackConfig = {
  proxy: {
    '/api': {
        ...
        onProxyReq: (proxyReq) => {
          if(cookie) {
            proxyReq.setHeader('Cookie', cookie);
          }
        },
        onProxyRes: (proxyRes) => {
          const sc = proxyRes.headers['set-cookie'];

          const raw = sc.filter(s => s.startsWith('JSESSIONID'));

          if(raw.length) {
            cookie = raw[0].split(';')[0];
          }
        }

    }
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!