Encrypting Connections with TLS
Using TLS to connect to a server that verifies the client’s identity is straightforward. The client has to provide a certificate and private key. The NATS client will use these to prove it’s identity to the server. For the client to verify the server’s identity, the CA certificate is provided as well.
Use example certificates created in self signed certificates for testing.
nc, err := nats.Connect("localhost",
nats.ClientCert("client-cert.pem", "client-key.pem"),
nats.RootCAs("rootCA.pem"))
if err != nil {
log.Fatal(err)
}
defer nc.Close()
// Do something with the connection
Java
JavaScript
let caCert = fs.readFileSync("rootCA.pem");
let clientCert = fs.readFileSync("client-cert.pem");
let clientKey = fs.readFileSync("client-key.pem");
let nc = NATS.connect({
url: url,
tls: {
ca: [caCert],
key: [clientKey],
cert: [clientCert]
}
});
Ruby
EM.run do
options = {
:servers => [
'nats://localhost:4222',
],
:private_key_file => 'client-key.pem',
:ca_file => 'rootCA.pem'
}
}
NATS.connect(options) do |nc|
puts "#{Time.now.to_f} - Connected to NATS at #{nc.connected_server}"
nc.subscribe("hello") do |msg|
puts "#{Time.now.to_f} - Received: #{msg}"
end
nc.flush do
nc.publish("hello", "world")
end
EM.add_periodic_timer(0.1) do
next unless nc.connected?
nc.publish("hello", "hello")
end
# Set default callbacks
nc.on_error do |e|
puts "#{Time.now.to_f } - Error: #{e}"
end
nc.on_disconnect do |reason|
end
nc.on_reconnect do |nc|
puts "#{Time.now.to_f} - Reconnected to NATS server at #{nc.connected_server}"
end
nc.on_close do
puts "#{Time.now.to_f} - Connection to NATS closed"
EM.stop
end
end
end
TypeScript
natsConnection *conn = NULL;
natsOptions *opts = NULL;
natsStatus s = NATS_OK;
s = natsOptions_Create(&opts);
if (s == NATS_OK)
s = natsOptions_LoadCertificatesChain(opts, "client-cert.pem", "client-key.pem");
if (s == NATS_OK)
s = natsOptions_LoadCATrustedCertificates(opts, "rootCA.pem");
if (s == NATS_OK)
s = natsConnection_Connect(&conn, opts);
(...)
// Destroy objects that were created
natsConnection_Destroy(conn);
Connecting with the TLS Protocol
Clients (such as Go, Java, Javascript, Ruby and Type Script) support providing a URL containing the tls
protocol to the NATS connect call. This will turn on TLS without the need for further code changes. However, in that case there is likely some form of default or environmental settings to allow the TLS libraries of your programming language to find certificate and trusted CAs. Unless these settings are taken into accounts or otherwise modified, this way of connecting is very likely to fail.