HTTPS redirection for all routes node.js/express - Security concerns

后端 未结 3 901
遇见更好的自我
遇见更好的自我 2020-12-31 03:52

I recently took a stab at setting up HTTPS on a node/express server. I have successfully managed to redirect all the routes to use https using the code below:



        
相关标签:
3条回答
  • 2020-12-31 04:09

    I use this simple code to redirect requests depending on whether the application is in development or production.

    // force https redirect
    var forceHTTPS = function () {
      return function(req, res, next) {
        if (!req.secure) {
          if (app.get('env') === 'development') {
             return res.redirect('https://localhost:3001' + req.url);
          } else {
            return res.redirect('https://' + req.headers.host + req.url);
          }
        } else {
          return next();
        }
      };
    };
    
    0 讨论(0)
  • 2020-12-31 04:24
    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);
    

    The middleware approach will work because express will run the middleware in the order added, before it runs the router, and in general this kind of site-wide policy is cleaner as middleware vs. a wildcard route.

    Regarding question 2 about sniffing session cookies, that must be addressed by marking the cookies as secure when you set them. If they haven't been marked secure, the browser will transmit them with HTTP requests as well, thus exposing them to sniffing.

    0 讨论(0)
  • 2020-12-31 04:24

    You can simply use your https_redirect function (though a bit modified) as a to automatically redirect all of your secure requests:

    // force https redirect
    var https_redirect = function () {
      return 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.use(https_redirect());
    
    app.get('/', routeHandlerHome);
    
    0 讨论(0)
提交回复
热议问题