Detect SSL connection whether or not behind a proxy

closes #1836
- adding server.enable('trust proxy') to let connect framework do the work
  of detecting X-Forwarded-Proto header
- replacing explicit checking for the X-Forwarded-Proto header with just
  'req.secure' boolean check
This commit is contained in:
Lev Gimelfarb 2014-01-26 17:00:50 -05:00 committed by Hannah Wolfe
parent ffc5655705
commit 1df6ac3b94

View File

@ -183,11 +183,7 @@ function isSSLrequired(isAdmin) {
// and redirect if needed
function checkSSL(req, res, next) {
if (isSSLrequired(res.isAdmin)) {
// Check if X-Forarded-Proto headers are sent, if they are check for https.
// If they are not assume true to avoid infinite redirect loop.
// If the X-Forwarded-Proto header is missing and Express cannot automatically sense HTTPS the redirect will not be made.
var httpsHeader = req.header('X-Forwarded-Proto') !== undefined ? req.header('X-Forwarded-Proto').toLowerCase() === 'https' ? true : false : true;
if (!req.secure && !httpsHeader) {
if (!req.secure) {
return res.redirect(301, url.format({
protocol: 'https:',
hostname: url.parse(config().url).hostname,
@ -208,6 +204,10 @@ module.exports = function (server, dbHash) {
expressServer = server;
middleware.cacheServer(expressServer);
// Make sure 'req.secure' is valid for proxied requests
// (X-Forwarded-Proto header will be checked, if present)
expressServer.enable('trust proxy');
// Logging configuration
if (expressServer.get('env') !== 'development') {
expressServer.use(express.logger());