是否可以在 NodeJS 中动态返回 SSL 证书? [英] Is it Possible to Dynamically Return an SSL Certificate in NodeJS?

查看:23
本文介绍了是否可以在 NodeJS 中动态返回 SSL 证书?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的 NodeJS 应用程序中动态返回一个 ssl 证书信息.我有两个域名链接到同一个节点应用程序.我只看到创建服务器时可以指定ssl设置.是否可以根据请求的url动态返回ssl证书?

I want to dynamically return an ssl certificate info in my NodeJS application. I have two domain names linked to the same node application. I only see that the ssl settings can be specified when the server is created. Is it possible to dynamically return ssl certificates based on the requested url?

否则,如果我必须在另一个端口上创建第二个服务器实例,我是否能够透明地将每个请求通过管道传输到原始端口?我可以让它看起来好像没有在第二个端口上运行吗?

Otherwise, if I must instead create a second sever instance on another port, will I be able to transparently pipe each request to the original port? Can I make it appear like it's not running on a second port?

谢谢,杰夫

推荐答案

是的,可以在一台服务器上完成.但需要注意的是,它适用于支持 SNI 的客户端 - 这是大多数现代浏览器.

Yes, it is possible to do it with one server. But the caveat is that it works on clients that support SNI - which is most modern browsers.

这就是你的做法:

//function to pick out the key + certs dynamically based on the domain name
function getSecureContext (domain) {
    return crypto.createCredentials({
        key:  fs.readFileSync('/path/to/domain.key'),
        cert: fs.readFileSync('/path/to/domain.crt'),
        ca: [fs.readFileSync('/path/to/CA_cert_1.crt'), fs.readFileSync('/path/to/CA_cert_2.crt'), <include all CA certs that you have to> ... ]
      }).context;
}

//read them into memory
var secureContext = {
    'domain1': getSecureContext('domain1'),
    'domain2': getSecureContext('domain2'),
    .
    .
}

//provide a SNICallback when you create the options for the https server
var options = {
    SNICallback: function (domain) {
        return secureContext[domain];
    }, //SNICallback is passed the domain name, see NodeJS docs on TLS
    cert: fs.readFileSync('/path/to/server.crt'),
    key: fs.readFileSync('/path/to/server.key'),                
    }
}

//create your https server
var server = require('https').createServer(options, [requestListener]);
//using Express
var server = require('https').createServer(options, require('express')());
server.listen(<someport>);

这是因为 https 的选项 类似于 tls.createServer().确保在 crypto.createCredentials 调用中包含所有必需的 CA 中间证书和根证书.此外,如果您有 CA 捆绑包,请在使用它们之前将它们拆分为多个单个 crt 文件,因为ca"接受证书数组.

This works because the options for https is similar to tls.createServer(). Make sure you include all required CA intermediate and root certificates in the crypto.createCredentials call. Also if you have a CA bundle, split them up into multiple single crt files before using them as 'ca' accepts an array of certificates.

这篇关于是否可以在 NodeJS 中动态返回 SSL 证书?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆