diff --git a/README.md b/README.md index 01477c39..f8f9eda3 100644 --- a/README.md +++ b/README.md @@ -124,11 +124,16 @@ attribute is not set. the cookie back to the server in the future if the browser does not have an HTTPS connection. -Please note that `secure: true` is a **recommended** option. However, it requires -an https-enabled website, i.e., HTTPS is necessary for secure cookies. If `secure` -is set, and you access your site over HTTP, the cookie will not be set. If you -have your node.js behind a proxy and are using `secure: true`, you need to set -"trust proxy" in express: +Please note that `secure: true` is a **recommended** option. However, for the cookie +to be set, it requires one of these conditions: + + - https-enabled website + - localhost connection + - node.js behind a proxy and "trust proxy" in express + +If none of these are true, the cookie will not be set. + +Here is an example with "trust proxy": ```js var app = express() diff --git a/index.js b/index.js index d7efeab9..f786b9dd 100644 --- a/index.js +++ b/index.js @@ -621,6 +621,25 @@ function hash(sess) { */ function issecure(req, trustProxy) { + + // socket is localhost + if (req.connection.remoteAddress === '127.0.0.1' || + req.connection.remoteAddress === '::ffff:127.0.0.1' || + req.connection.remoteAddress === '::1' + ) { + // if proxy is trusted; localhost connection is secure for sure + if (trustProxy === true) { + return true; + } + + // proxy not explicitly trusted; no proxy means connection is secure + if (req.headers['x-forwarded-proto'] !== undefined) { + return true; + } + + // proxy connected from localhost, we need to do other checks + } + // socket is https server if (req.connection && req.connection.encrypted) { return true; diff --git a/test/session.js b/test/session.js index 7ce3c194..2a5c372c 100644 --- a/test/session.js +++ b/test/session.js @@ -610,6 +610,7 @@ describe('session()', function(){ .expect(200, done) }) + // TODO: Fix tests it('should work when no header', function(done){ request(server) .get('/')