【问题标题】:expressjs, nginx proxy, csurf and secure cookies not workingexpressjs、nginx 代理、csurf 和安全 cookie 不起作用
【发布时间】:2018-06-20 05:37:03
【问题描述】:

我有一个 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;

据我从文档中可以看出,这应该没问题。我的 webapp 是从 GCP 运行的,但我认为这不会有什么不同。

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

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

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

【问题讨论】:

    标签: node.js express nginx express-session


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 我会将您的答案标记为正确,但看起来我的问题更愚蠢,即使我重新启动了节点应用程序,我也忘记在配置更改后重新启动 nginx。哇!
    猜你喜欢
    • 1970-01-01
    • 2020-02-02
    • 1970-01-01
    • 1970-01-01
    • 2018-07-20
    • 1970-01-01
    • 2018-04-02
    • 2017-10-17
    • 2015-07-08
    相关资源
    最近更新 更多