如何连接到需要使用基于节点Opcua的客户端进行基于证书的用户身份验证的OPC-UA服务器

问题描述

我正在使用node-opcua库来构建OPC UA客户端。我已经使用基本示例连接到OPC-UA服务器(prosys OPC-UA模拟服务器),但是现在我想使我的客户端支持各种身份验证方法。

我可以使用以下代码获得基于用户名+密码的身份验证:

const client = OPCUAClient.create(options);
await client.connect(endpointUrl);
let userIdentity = {type: opcua.UserTokenType.UserName,userName: "bruce",password: "test" };
const session = await client.createSession(userIdentity); 

在prosys OPC-UA模拟服务器上,我检查了“用户名+密码”身份验证方法并创建了匹配的用户。

现在,但是我想使基于X.509证书的用户身份验证正常工作。是否有人在node-opcua中有一个可行的示例,以及在使用OpenSSL生成证书方面的指导?

解决方法

所以我想通了!这是其他可能想要的人(或我未来的自我)的答案

首先,看来证书需要具有正确的用法和扩展名。当我生成没有这些证书的证书时,它不起作用。创建一个名为user-key.conf的文件,其内容类似于:

[ req ]
default_bits = 2048
default_md = sha256
distinguished_name = subject
req_extensions = req_ext
x509_extensions = req_ext
string_mask = utf8only
prompt = no

[ req_ext ]
basicConstraints = CA:FALSE
nsCertType = client,server
keyUsage = nonRepudiation,digitalSignature,keyEncipherment,dataEncipherment,keyCertSign
extendedKeyUsage= serverAuth,clientAuth
nsComment = "Bruces User Cert"
subjectKeyIdentifier=hash
authorityKeyIdentifier=keyid,issuer
subjectAltName = URI:urn:opcua:user:bruce,IP: 127.0.0.1

[ subject ]
countryName = US
stateOrProvinceName = TX
localityName = Houston
organizationName = AL
commonName = bruce

注意,在此示例中,我正在生成一个自签名证书。我不是安全专家,所以我不知道所有这些声明的含义,也没有测试过哪些声明绝对必要。我发现一些信息似乎表明commonName应该与OPC服务器中的用户名相对应,但这是我在研究中了解到的唯一细节。

接下来,将openssl与该配置文件一起使用以创建证书和私钥对:

> openssl.exe req -x509 -days 365 -new -out bruce1.pem -keyout bruce1_key.pem -config user-key.conf

出于某些(可能是与安全性相关的良好原因),openssl会强制您指定密码短语以保护私钥。到目前为止,我还没有弄清楚如何在node.js中对其进行解密,因此我发现可以使用以下命令将其删除:

> openssl.exe rsa -in bruce1_key.pem -out bruce1_key_nopass.pem

然后,至少使用我正在测试的OPC-UA服务器(prosys OPC-UA模拟服务器),必须以.der格式获取证书:

> openssl.exe x509 -inform PEM -outform DER -in bruce1.pem -out bruce1.der

此.der文件需要加载到OPC-UA服务器中。对于prosys,这是通过将其复制到.\prosys-opc-ua-simulation-server\USERS_PKI\CA\certs文件夹中完成的。

在node.js中,以下代码将使用生成的证书文件进行连接:

const client = OPCUAClient.create(options);
await client.connect(endpointUrl);
let userIdentity = {
    type: UserTokenType.Certificate,certificateData: fs.readFileSync('./user-certificates/bruce1.pem'),privateKey: fs.readFileSync('./user-certificates/bruce1_key_nopass.pem','utf8')
}

const session = await client.createSession(userIdentity); 

这将导致成功连接到prosys OPC-UA客户端。我确信将来可以做一些改进,例如在node.js中进行密码解密。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...