所有路由的HTTPS重定向node.js/express - 安全问题

los*_*rld 17 https node.js express

我最近在节点/快速服务器上设置了HTTPS.我已成功设法使用以下代码重定向所有路由以使用https:

// force https redirect
var https_redirect = function(req, res, next) {
  if (req.secure) {
    if(env === 'development') {
      return res.redirect('https://localhost:3000' + req.url);
    } else {
      return res.redirect('https://' + req.headers.host + req.url);
    }
  } else {
    return next();
  }
};

app.get('*', function(req, res, next) {
  https_redirect(req, res, next);
});
Run Code Online (Sandbox Code Playgroud)

这似乎工作正常.但是,因为在我有几个问题之前我还没有涉足过这个问题:

  1. 这是从http重定向到https的理想方式吗?
  2. 如果用户使用http路由,则在重定向之前,任何人都可以使用sslstrip之类的东西来嗅出会话信息.

节点:v0.8.2; 表达:v3.05

Pet*_*ons 43

function requireHTTPS(req, res, next) {
    if (!req.secure) {
        //FYI this should work for local development as well
        return res.redirect('https://' + req.get('host') + req.url);
    }
    next();
}

app.use(requireHTTPS);
app.get('/', routeHandlerHome);
Run Code Online (Sandbox Code Playgroud)

中间件方法将起作用,因为Express将在添加的顺序中运行中间件,然后运行路由器,并且通常这种站点范围的策略比中间件与通配符路由更清晰.

关于有关嗅探会话cookie的问题2,必须通过将cookie标记为secure您设置它们来解决.如果它们没有被标记为安全,浏览器也将使用HTTP请求传输它们,从而使它们暴露于嗅探.

  • 这是伟大的,但它的发展稍有问题,如果你使用非标准(80 HTTP,443 HTTPS),因为它试图重定向到`的https://本地主机:[PORT]`.解决方法是在`development`环境中设置`SSL_PORT`环境变量,如果已定义,则替换端口.参见[这里](https://gist.github.com/gingi/47df42a45bb1653002ee#file-gistfile1-js-L5-L8),用于经修改的段. (2认同)