Table of Contents

Security

NATS has a lot of security features and .NET V2 client supports them all. All you need to do is to pass your credentials to the connection.

NatsOpts opts = new NatsOpts
{
    AuthOpts = NatsAuthOpts.Default with
    {
        Username = "bob",
        Password = "s3cr3t",
    },
};

await using NatsClient nats = new NatsClient(opts);

See also user authentication tests for more examples.

Implicit TLS Connections

As of NATS server version 2.10.4 and later, the server supports implicit TLS connections. This means that the client can connect to the server using the default port of 4222 and the server will automatically upgrade the connection to TLS. This is useful for environments where TLS is required by default.

NatsOpts opts = new NatsOpts
{
    TlsOpts = new NatsTlsOpts
    {
        Mode = TlsMode.Implicit,
    },
};

await using NatsClient nats = new NatsClient(opts);

Mutual TLS Connections

The server can require TLS certificates from a client to validate the client certificate matches a known or trusted CA and to provide authentication.

You can set the TLS options to use your client certificates when connecting to a server which requires TLS Mutual authentication.

NatsOpts opts = new NatsOpts
{
    TlsOpts = new NatsTlsOpts
    {
        CertFile = "path/to/cert.pem",
        KeyFile = "path/to/key.pem",
        CaFile = "path/to/ca.pem",
    },
};

await using NatsClient nats = new NatsClient(opts);
Tip

Intermediate CA Certificates

When connecting using intermediate CA certificates, it might not be possible to validate the client certificate and TLS handshake may fail.

Unfortunately, for .NET client applications it isn't possible to pass additional intermediate certificates and the only solution is to add the certificates to the certificate store manually.

See also .NET documentation on Troubleshooting SslStream authentication issues