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 .
{% tabs %} {% tab title=”Go” %}
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
{% endtab %}
{% endtab %}
{% tab title=”JavaScript” %}
// tls options available depend on the javascript
// runtime, please verify the readme for the
// client you are using for specific details
// this example showing the node library
const nc = await connect({
port: ns.port,
debug: true,
tls: {
caFile: caCertPath,
keyFile: clientKeyPath,
certFile: clientCertPath,
},
{% endtab %}
{% tab title=”Python” %}
{% tab title=”Ruby” %}
EM.run do
options = {
:servers => [
'nats://localhost:4222',
],
:tls => {
:private_key_file => 'client-key.pem',
:cert_chain_file => 'client-cert.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
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|
puts "#{Time.now.to_f} - Disconnected: #{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
{% endtab %}
{% tab title=”C” %}
{% endtab %} {% endtabs %}