首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >express.js中对代理请求路由的保护

express.js中对代理请求路由的保护
EN

Stack Overflow用户
提问于 2019-09-18 06:48:01
回答 1查看 660关注 0票数 2

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

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

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

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

代码:

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

发布于 2019-09-18 07:07:47

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

代码语言:javascript
复制
app.use(['/api/one','/api/two'], csrfProtection, proxy('http://example.com'))
app.use('/api', proxy('http://example.com'))

或者,如果你想保护对API的所有POST请求,你需要做一些事情:

代码语言:javascript
复制
app.use('/api', csrfProtection, proxy('http://example.com'))
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57982926

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档