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” %}

    1. nc, err := nats.Connect("localhost",
    2. nats.ClientCert("client-cert.pem", "client-key.pem"),
    3. nats.RootCAs("rootCA.pem"))
    4. if err != nil {
    5. log.Fatal(err)
    6. }
    7. defer nc.Close()
    8. // Do something with the connection

    {% endtab %}

    {% endtab %}

    {% tab title=”JavaScript” %}

    1. // tls options available depend on the javascript
    2. // runtime, please verify the readme for the
    3. // client you are using for specific details
    4. // this example showing the node library
    5. const nc = await connect({
    6. port: ns.port,
    7. debug: true,
    8. tls: {
    9. caFile: caCertPath,
    10. keyFile: clientKeyPath,
    11. certFile: clientCertPath,
    12. },

    {% endtab %}

    {% tab title=”Python” %}

    {% tab title=”Ruby” %}

    1. EM.run do
    2. options = {
    3. :servers => [
    4. 'nats://localhost:4222',
    5. ],
    6. :tls => {
    7. :private_key_file => 'client-key.pem',
    8. :cert_chain_file => 'client-cert.pem',
    9. :ca_file => 'rootCA.pem'
    10. }
    11. }
    12. NATS.connect(options) do |nc|
    13. puts "#{Time.now.to_f} - Connected to NATS at #{nc.connected_server}"
    14. nc.subscribe("hello") do |msg|
    15. puts "#{Time.now.to_f} - Received: #{msg}"
    16. end
    17. nc.flush do
    18. nc.publish("hello", "world")
    19. end
    20. nc.publish("hello", "hello")
    21. end
    22. # Set default callbacks
    23. nc.on_error do |e|
    24. puts "#{Time.now.to_f } - Error: #{e}"
    25. end
    26. nc.on_disconnect do |reason|
    27. puts "#{Time.now.to_f} - Disconnected: #{reason}"
    28. end
    29. nc.on_reconnect do |nc|
    30. puts "#{Time.now.to_f} - Reconnected to NATS server at #{nc.connected_server}"
    31. end
    32. nc.on_close do
    33. puts "#{Time.now.to_f} - Connection to NATS closed"
    34. EM.stop
    35. end
    36. end
    37. end

    {% endtab %}

    {% tab title=”C” %}

    {% endtab %} {% endtabs %}

    Connecting with the TLS Protocol

    See Also