【问题标题】:CSRF-protection for routes of proxied requests in express.jsexpress.js 中代理请求路由的 CSRF 保护
【发布时间】:2019-09-18 21:51:39
【问题描述】:

我正在使用http-proxy-middleware(并愿意接受建议,但希望坚持使用代理请求的模块,而不是创建新的模块,例如requesthttp)来代理对远程主机的请求。

我没有看到当前解决方案的两个问题:

1) 我有一个受 CSRF 保护的表单(通过 csurf)。我希望中间件首先检查 CSRF-token,如果它是有效的,然后将请求代理到另一台主机,获取响应并将其发送给用户。如何实现这样的设置?

2) http-proxy-middleware(和其他一些代理模块)利用app.use 设置一个转发规则(将路由附加到主机),但是我希望对路由进行更细粒度的控制 - 每个我的路由必须在远程主机上有自己的端点。

代码:

const express = require('express')
const csrf = require('csurf')
const cookieParser = require('cookie-parser')
const proxy = require('http-proxy-middleware')

var app = express()
var csrfProtection = csrf({ cookie: true })
app.use(cookieParser())

// not quite what I need, since different 
// routes would utilize different endpoints
app.use('/api', proxy('http://example.com'))

app.get('/forms', (req, res) => {
  res.send(
    res.render('csrf-protected-forms.html', { csrfToken: req.csrfToken() })
  )
})

app.post('/api/one', csrfProtection, (req, res) => {
  response = // proxies to 'http://example.com/something/one' 
             // and obtains response
  res.send(response)
})

app.post('/api/two', csrfProtection, (req, res) => {
  response = // proxies to 'http://example.com/somethingelse/and/here/two' 
             // and obtains response
  res.send(response)
})

app.listen(3000)

【问题讨论】:

    标签: node.js express csrf http-proxy


    【解决方案1】:

    在您的代码csrf 中,保护在代理中间件之后运行。如果您只想保护这两条路线'/api/one','/api/two'

    app.use(['/api/one','/api/two'], csrfProtection, proxy('http://example.com'))
    app.use('/api', proxy('http://example.com'))
    

    或者,如果您想保护对 API 的所有 POST 请求,您需要这样的东西:

    app.use('/api', csrfProtection, proxy('http://example.com'))
    

    【讨论】:

      猜你喜欢
      • 2016-06-07
      • 2015-10-15
      • 2019-01-25
      • 2015-03-11
      • 2014-02-19
      • 2022-10-17
      • 2015-01-17
      • 2011-01-21
      • 2013-12-24
      相关资源
      最近更新 更多