DEV Community

Daniel Olivares
Daniel Olivares

Posted on • Edited on

Secure Your MQTT Client in C# with Basic Authentication

It’s tempting to use quick examples without credentials, but in a real-world scenario you must authenticate your MQTT client. In this post we’ll show how to add basic authentication in C# and discuss brute-force risks and how to mitigate them.


Basic Authentication Setup

Using the MQTTnet library, simply call .WithCredentials() when building the client options:

using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using System;
using System.Text;
using System.Threading.Tasks;

class Program
{
    static async Task Main()
    {
        var options = new MqttClientOptionsBuilder()
            .WithTcpServer("broker.hivemq.com", 1883)
            .WithClientId("dotnet-iot-secure-demo")
            .WithCredentials("myUser", "myStrongPassword") // ← basic authentication
            .Build();

        var factory = new MqttFactory();
        var client = factory.CreateMqttClient();

        client.UseConnectedHandler(async _ =>
        {
            Console.WriteLine("Connected with basic authentication");
            await client.SubscribeAsync("iot/door/status");
        });

        client.UseApplicationMessageReceivedHandler(e =>
        {
            var payload = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
            Console.WriteLine($"Message received: {payload}");
        });

        await client.ConnectAsync(options);
        Console.WriteLine("Press ENTER to exit...");
        Console.ReadLine();
    }
}
Enter fullscreen mode Exit fullscreen mode

Note: Even with username/password, it’s critical that your broker and client use TLS (port 8883) so credentials aren’t sent in plaintext.

Best Practices to Harden Security Strong Passwords

Use ≥16 characters and mix uppercase, lowercase, numbers, and symbols.

Attempt Limiting
Lock out after N failed attempts (e.g., 5 failures → 5-minute lock).

IP Filtering
Restrict connections to trusted IP ranges (e.g., your corporate network).

Enforce TLS
Never transmit credentials in plaintext; require TLS on both client and broker. .WithTls

Credential Rotation
Change usernames/passwords regularly (every 3–6 months).

Monitoring & Alerts
Log failed logins and set up alerts when thresholds are exceeded.

Top comments (0)