代码之家  ›  专栏  ›  技术社区  ›  TommyBs

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

  •  0
  • TommyBs  · 技术社区  · 8 年前

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

    我已经转移到一个有ssl证书的登台站点。现在我正在使用ssl,我想启用安全cookies。但是现在每当我提交表单时,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运行的,但我不认为这会有什么不同。

    我试着在我的机器上清理我的饼干等,以防某处被缓存,但它仍然无法工作。移回 secure:false 解决了这个问题。

    我有一套 app.post 路由处理程序来验证csrf令牌,因为页面上有多个表单,并且新的csrf令牌是在触发此路由之后创建的,正如我前面提到的,这一切都在没有安全cookie的情况下正常工作。我也试着把我的会话秘密传递给 cookieParser() 但也无济于事 Express-session Secure Cookies not working 也不工作(例如设置 resave:true )没有ajax请求,也没有 POST 令牌在表单中正确呈现。

    有什么明显的我遗漏了吗?

    1 回复  |  直到 8 年前
        1
  •  1
  •   David784    8 年前

    我做了一些类似的事情,至少在我的设置中,我必须在 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;
    
    推荐文章