由于自定义标头缺失,认证中间件阻止OPTIONS预检请求

时间:2018-01-23 12:54:03

标签: javascript express authentication proxy http-proxy

我有一个使用axios作为HTTP库的React应用程序,express服务器使用包含API的http-proxy-middleware包和API express服务器。

React应用程序应通过代理身份验证服务器与API服务器通信,如下所示:

Communication between client and API server goes through proxy server

在我的React应用程序中,我创建了这个测试方法:

testReq(){
    axios.get('http://localhost:5000/applicationData/checkMe', {
      withCredentials: true,
      headers: {
        'x-access-token': '...'
      }
    })
    .then(response => console.log(response.status))
    .catch(e => console.log(e))
  }

这是我的代理方法的样子:

server.use('/applicationData', authenticate, proxy({
    target: 'http://localhost:4000',
    changeOrigin: false,
    onProxyReq(proxyReq, req) {
      // proxyReq.setHeader('x-access-identity-email', req.decodedToken.email)
    },
  }))

这是上面使用的authenticate中间件函数:

module.exports = (req, res, next) => {
  const token = req.headers['x-access-token']
  console.log('token', token)
  if (token) {
    verifyToken(token, global.config.secret).then((verificationResponse) => {
      const { decoded, message } = verificationResponse
      if (!decoded) return res.status(401).json({ message })
      req.decoded = decoded
      return next()
    })
    .catch((err) => {
      console.error(err)
      res.status(500).json({ message: 'Internal error' })
    })
  } else return res.status(401).json({ message: 'Missing authentication token' })
}

我在API和代理服务器上启用了CORS,如下所示:

server.all('/*', (req, res, next) => {
    res.header('Access-Control-Allow-Origin', 'http://localhost:3000')
    res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, x-access-token')
    res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
    res.header('Access-Control-Allow-Credentials', 'true')
    next()
  })

问题是我在发送请求时收到此响应:

enter image description here

我认为这是由于身份验证中间件试图从x-access-token请求访问OPTIONS标头而不存在因此返回401.如果我从代理方法中删除authentication中间件然后请求经过。

如何在x-access-token次请求中提及OPTIONS?或者,处理这种情况的正确方法是什么?

2 个答案:

答案 0 :(得分:1)

在facebook中不允许粘贴代码不确定,为什么,所以粘贴在这里:

缺少中间件的

(对于您评论的选项部分):

if (req.method == 'OPTIONS') {
  res.send(200);
}
else {
  next();
}

对于错误部分,因为您说在认证之前触发了认证,因此您可能必须在认证之前设置该代码(安全部分我不太确定)

答案 1 :(得分:0)

我认为这一行:

    res.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, x-access-token')

应该是:

    res.header('Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept, x-access-token')