Determine if request is https

282 views
Skip to first unread message

Ryan Schmidt

unread,
Sep 21, 2011, 6:11:53 PM9/21/11
to expre...@googlegroups.com
Hello,

I'm writing an app that's listening on both http and https using this technique described by TJ:

https://gist.github.com/1051583

I'm trying to write a middleware that determines whether the current request is http or https and acts accordingly. What's the best way to do that?

I came up with this but it doesn't seem very intuitive:

var foo = function(req, res, next) {
var isSSL = req.connection.socket && req.connection.socket.server && req.connection.socket.server.key;
if (isSSL) {
...
} else {
...
}
}

I have my app's http and https ports stored in the app like this:

app.configure(function() {
app.set('http port', 3000);
app.set('https port', 3001);
...
});

So another possibility that seems to work is:

var https_port = req.app.set('https port');
var isSSL = !req.socket.address || req.socket.address().port == https_port;

But this also seems to work mostly by coincidence. I'm worried that by poking around in the request object like this I'm setting myself up to fail when inevitably things get rearranged in a later version of node or express. Is there a better way? I see other people asking the question and not finding the answer:

http://stackoverflow.com/questions/7181073/is-it-possible-to-check-if-https-is-being-used-by-an-express-js-handler

Thanks for your insight.


TJ Holowaychuk

unread,
Sep 21, 2011, 6:14:51 PM9/21/11
to expre...@googlegroups.com
there's req.connection.encrypted

-- 
TJ Holowaychuk
--
You received this message because you are subscribed to the Google Groups "Express" group.
To post to this group, send email to expre...@googlegroups.com.
To unsubscribe from this group, send email to express-js+...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/express-js?hl=en.

Ryan Schmidt

unread,
Sep 21, 2011, 6:27:45 PM9/21/11
to expre...@googlegroups.com
Thanks! I had looked through:

http://nodejs.org/docs/v0.4.12/api/net.html#net.Socket

but "encrypted" doesn't appear to be documented there. I see that on an http request it's undefined, and on an https request it's an object with a bunch of stuff in it. Is it sufficient to just:

if (req.connection.encrypted)

or do I need to examine the object further?

Reply all
Reply to author
Forward
0 new messages