question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Use proxy response cookie for further proxy request

See original GitHub issue

Expected behavior

Not able to save cookies from proxy response to the session.

Actual behavior

Setup

  • http-proxy-middleware: 0.15.0
  • server: express + 4.13.3

proxy middleware configuration


const proxyOptions = {
  target: targetUrl,                // target host
  pathRewrite: function (path) {
    return path.replace('/api', '')
  },
  logLevel: 'debug',
  onProxyReq: function (proxyReq, req, rsp) {
    proxyReq.path = req.path + '?ticket=' + req.session.pt[targetUrl]
    if(req.session.cookie.pt_session_id && req.session.cookie.pt_session_id[targetUrl]) {
      proxyReq.writeHead(req.session.cookie.pt_session_id[targetUrl])
    }
  },
  onProxyRes: function onProxyRes(proxyRes, req, res) {
    console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2))
    req.session.cookie.pt_session_id = req.session.cookie.pt_session_id || {}
    req.session.cookie.pt_session_id[targetUrl] = proxyRes.headers['set-cookie']
  }
}
var apiProxy = proxy('/api', proxyOptions);

server mounting

var app = express();

app.use(apiProxy);
app.listen(3000);

Hi,

Thanks guys for the awesome middleware which made my life very easy. We need minor information regarding my usecase. We are implementing CAS proxy using then middleware. Our cas server behaviour is it, first time it accept the proxy ticket and provides the _session_id, it expects that _session_id in further request. I am not able to save it to session and use it. Have I missed something. ?

proxy response looks like below:

RAW Response from the target {
   "server": "nginx/1.6.2",
   "date": "Fri, 13 May 2016 06:38:26 GMT",
   "content-type": "application/json;charset=utf-8",
   "content-length": "2071",
   "connection": "close",
   "status": "200 OK",
   "set-cookie": [
     "_session_id=randombignumber; path=/; HttpOnly"
   ]
}

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Comments:14 (6 by maintainers)

github_iconTop GitHub Comments

2reactions
olalondecommented, Sep 2, 2016

I had a similar problem with front end rewriting /api path to /. e.g. http://www.website.com/api/whoami would be forwarded to http://api.website.com/whoami, but api.website.com would set cookies with the path param not prefixed with /api.

Solved with the following code (reads set-cookie from incoming target response and prefixes cookie path params with /api:

import cookiejar from 'cookiejar'

app.use('/api', proxy({
  target: 'http://api.domain.com',
  pathRewrite: { '^/api': '' },
  onProxyRes: (proxyRes) => {
    // prepend /api to cookie paths
    const setCookieHeaders = proxyRes.headers['set-cookie'] || []
    const modifiedSetCookieHeaders = setCookieHeaders
      .map(str => new cookiejar.Cookie(str))
      .map(cookie => {
        if (cookie.path && cookie.path[0] === '/') {
          cookie.path = `/api${cookie.path}`
        }
        return cookie
      })
      .map(cookie => cookie.toString())
    proxyRes.headers['set-cookie'] = modifiedSetCookieHeaders
  },
  changeOrigin: true,
}))

Would be nice if this was a configurable option for http-proxy-middleware since it is probably a fairly common scenario.

1reaction
chimuraicommented, May 13, 2016

You can try to relay all headers back and forth. Hopefully this will take care of you cookie issue.

const proxyOptions = {
  onProxyReq: relayRequestHeaders,
  onProxyRes: relayResponseHeaders
}

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]);
  });
}

Please use StackOverflow to troubleshoot your setup if you need further assistance.

Thanks.

Read more comments on GitHub >

github_iconTop Results From Across the Web

http-proxy-middleware "set-cookie" response does not set in ...
My proxy setup returns the correct Response Headers with cookies to be set: set-cookie: JSESSIONID=yElsHUaPE8Ip_AAD_oIfTQ; Path=/; Secure; ...
Read more >
Apache Reverse Proxy - HTTP requests with a Cookie
Now we have the need to forward a few requests to another server (server3.domain.com) and check that a cookie named "LtpaToken" exists in...
Read more >
Application Proxy cookie settings - Azure Active Directory
Click Application Proxy. Under Additional Settings, set the cookie setting to Yes or No. Click Save to apply your changes.
Read more >
Cookies Overview and HTTP Proxies - Computer Science
Step 3: Server returns home page plus a cookie set to the unique ID. ... Proxy server client http request http request http...
Read more >
Set-Cookie - HTTP - MDN Web Docs
Indicates that the cookie is sent to the server only when a request is made with the https: scheme (except on localhost), and...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found