仅在某些path上使用Node.js客户端证书身份validation

我有一个基于node.js的web应用程序,需要来自客户端的安全( https )连接。 我想要的是,在某些path上,客户端证书身份validation是必需的,而不是其他path。

所以例如。 如果用户转到https://www.example.com/main,则服务器不需要客户端证书身份validation(因此浏览器不会询问任何内容)。 但是,如果用户导航到https://www.example.com/secure ,那么将需要客户端证书authentication(因此浏览器将popup一个对话框来select使用哪个证书)。

我怎么能做到这一点。 我能够强制客户端证书身份validation,如果我通过requestCert:truerejectUnauthorized:truehttps.createServer选项。 这种方法的问题是每个path都需要客户端证书。

我在这里降落是因为我在同一个问题上工作,将分享我正在采取的方法。 对于要求用户使用有效证书进行身份validation的端点,我使用附加到需要证书的端点的自定义path,并validation用户是否使用证书进行身份validation(如果他们正在访问遵循该path的任何端点)。 即:

 app.use('/api/cert', function(req, res, next){ //validate that any token passed in the request was generated for a valid //cert login, otherwise reject request //pseudo-code if(isValidCertToken(req.authentication.token)) { next(); //this will pass it on to the correct endpoint in the /api/cert/[whatever] chain } else { req.status(401).send({error: 'invalid login, cert required'}); } }); 

这将要求您允许用户通过将requestCert标志设置为true来使用证书进行身份validation,但是,只要设置rejectUnauthorized ,用户不希望使用“需要证书”端点,也将允许其他身份validation方法设置https连接时为false。

我不知道如果我完全明白你想要什么..但根据我的理解,如果你使用快递,你可以通过一个简单的中间件pipe理这件事情。在该中间件,你可以跟踪任何请求来自http或https通过这个

HTTPS连接具有req.connection.encrypted(一个包含有关SSL连接信息的对象)。 HTTP连接没有req.connection.encrypted。

另外(从文档):

通过HTTPS支持,使用request.connection.verifyPeer()和request.connection.getPeerCertificate()来获取客户端的authentication细节。

我希望这有帮助..