Node.js express.js中代理请求路由的CSRF保护

Node.js express.js中代理请求路由的CSRF保护,node.js,express,csrf,http-proxy,Node.js,Express,Csrf,Http Proxy,我正在使用http代理中间件(并愿意接受建议,但希望坚持使用代理请求的模块,而不是创建新的模块,如request或http)将请求代理到远程主机 有两个问题我看不到解决当前问题的方法: 1) 我有一个受CSRF保护的表单(通过csurf)。我希望中间件首先检查CSRF令牌,如果该令牌有效,则仅将请求代理给另一台主机,获得响应并将其发送给用户。如何实现这样的设置 2) http代理中间件(和一些其他代理模块)利用app。使用设置一个转发规则(将路由附加到主机),但是我希望对路由进行更细粒度的控制-

我正在使用
http代理中间件
(并愿意接受建议,但希望坚持使用代理请求的模块,而不是创建新的模块,如
request
http
)将请求代理到远程主机

有两个问题我看不到解决当前问题的方法:

1) 我有一个受CSRF保护的表单(通过
csurf
)。我希望中间件首先检查CSRF令牌,如果该令牌有效,则仅将请求代理给另一台主机,获得响应并将其发送给用户。如何实现这样的设置

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

守则:

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)

在您的代码中,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'))

在您的代码中,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'))