expressjs、nginx 代理、csurf 和安全 cookie 不工作

expressjs, nginx proxy, csurf and secure cookies not working

我有一个 Express 站点 运行 在 nginx 代理后面,关于使用 csurf 和不安全 cookie 的 csrf 保护,在我的本地开发机器上一切正常。

我已转移到具有 SSL 证书的暂存站点。现在我正在使用 SSL,我想启用安全 cookie。但是,每当我提交表单时,csurf 现在总是会出现无效的 csrf 令牌错误。

我这样设置我的快速会话:

app.set('trust proxy', 1)
app.use(session({secret:'secret' , resave:false,proxy:true, saveUninitialized:false, store:sessionStore, rolling:true, cookie:{secure:true}}))
//...other setup lines
let csrf = csurf()
app.use(csrf)

我的 nginx 设置如下:

        proxy_pass http://localhost:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_set_header x-forwarded-proto https;
        proxy_cache_bypass $http_upgrade;

据我从文档中得知,这应该没问题。我的网络应用程序是来自 GCP 的 运行,但我认为这不会有任何区别。

我已经尝试在我的机器上清除我的 cookie 等,以防某些东西被缓存在某个地方,但它仍然无法工作。回到 secure:false 解决了这个问题。

我有一个 catch all app.post 路由处理程序来验证 csrf 令牌,因为页面上有多个表单,并且在该路由触发后创建新的 csrf 令牌,正如我之前提到的,这一切都有效没有安全 cookie 也很好。我也尝试过将我的会话秘密传递给 cookieParser(),但无济于事,Express-session Secure Cookies not working 的解决方案也不起作用(例如设置 resave:true)。没有 AJAX 请求,要么是直接的 POST 并且令牌在表单中正确呈现。

我在这里明显遗漏了什么吗?

我只是做了类似的事情,至少在我的设置中我必须在我的 trust proxy in express 中指定以下数组。

app.set('trust proxy', ['loopback', 'linklocal', 'uniquelocal']);

我也相信 express 希望看到所有标准 x-forwarded headers,而不仅仅是 -proto。这是我为他们使用的配置:

proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Proto $scheme;