joyent/node — Issue #1955: Dynamically set SSL certificate before the SSL handshake
Author: thefosk
Created: 2011-10-28 06:25:48+00:00
State: open

I'm not sure this is a common issue, but I post it here anyways just in case.

I had the need to intercept something like a `beforeHandshake` event into an HTTPS server, to dynamically load an SSL certificate stored in memory before the SSL handshake with the client.

Right now the only way to load a certificate is to set the `key` and `cert` fields in an object and pass this object into the constructor of the HTTPS server.

```javascript
var options = {
key: ssl_config.key,
cert: ssl_config.cert
};

https.createServer(options, function (request, response) {
// Do something
}).listen(443);
```

In my case, I needed to inject different certificates based upon specific conditions met by the `request` object. I'm not sure which is the right way to do this, but something like:

```javascript
var options = {
key: ssl_config.key,
cert: ssl_config.cert
};

var server = https.createServer(options, function (request, response) {
request.addListener('beforeHandshake', function(context) {
if (request.headers["host"] == "somedomain.com") {
// Load a new certificate, overriding the default one, just for this request
var newoptions = {
key: loadKey(request),
cert: loadCert(request)
};
context.options = newoptions;
}
});
// Do something
}).listen(443);

function loadKey(request) {
// ...
}

function loadCert(request) {
// ...
}
```