Reputation: 3451
I've got a simple node proxy app that works exactly as I want when I proxy between to localhost ports with https. That is, https://localhost:5200/jokes to https://localhost:7172/jokes. I call it from with in my JavaScript program using the fetch API as follows:
const res = await fetch(`${fetchBaseUrl}/jokes`, {
method: "GET",
credentials: "include",
});
However, if I make my target of the proxy a real domain like https://example.com/jokes, I don't get the cookie back from that server. In both cases, I set the cookie options as follows: (I have tried sameSite LAX and strict also)
const cookieOptions = {
httpOnly: true,
secure: true,
sameSite: "none", // when set to "none" the react app works, strict does not
};
Here is my simple proxy file. I'd appreciate help in identifying what I am missing to properly handle passing cookies. In my remote server code running on localhost:7172, I do verify the Origin server, and on the remote internet, that code does not even get called.
const fs = require("fs");
const https = require("https");
const express = require("express");
const cookieParser = require("cookie-parser");
const { createProxyMiddleware } = require("http-proxy-middleware");
const options = {
key: fs.readFileSync("localhost5200proxyserver.key"),
cert: fs.readFileSync("localhost5200proxyserver.crt"),
};
const app = express();
app.use(cookieParser());
//const target = "https://example.com"; // Target server (does not work)
const target = "https://localhost:7172"; // Target server
const httpsAgent = new https.Agent({
rejectUnauthorized: false, // Allow self-signed certificates
});
app.use(
"*",
createProxyMiddleware({
target: target,
changeOrigin: true,
secure: false, // Allow self-signed SSL certificates
agent: httpsAgent,
pathRewrite: (path, req) => {
return req.originalUrl;
},
onProxyReq: (proxyReq, req, res) => {
proxyReq.setHeader("Origin", 'https://localhost:7172'); // this presents to remote server
},
onProxyRes: (proxyRes, req, res) => {
console.log("Response from target server:", proxyRes.statusCode);
if (proxyRes.headers["set-cookie"]) {
res.setHeader("Set-Cookie", proxyRes.headers["set-cookie"]);
}
},
logLevel: "debug",
})
);
https.createServer(options, app).listen(5200, () => {
console.log(`Proxy server is running at https://localhost:5200 and proxy to ${target}`);
});
Note: on my real server, it's running with http behind a reverse proxy to get a valid letsencrypt ssl cert. When I access that site, I can get a cookie directly, just not through my proxy, which is important to me.
Upvotes: 0
Views: 73