Skip to content

MQTT Certificate Authentication Fails — Complete Guide

DodaTech Updated 2026-06-26 1 min read

In this tutorial, you'll learn about MQTT Certificate Authentication Fails. We cover key concepts, practical examples, and best practices.

The Problem

MQTT connection using client certificate authentication is rejected by the broker.

Quick Fix

Wrong

#include <PubSubClient.h>
#include <ESP8266WiFi.h>

PubSubClient client;

void setup() {
  client.connect("device-01");
}```

Connection error: TLS handshake failed. Certificate verification error.


### Right

```cpp
#include <PubSubClient.h>
#include <FS.h>

WiFiClientSecure espClient;
PubSubClient client(espClient);

char ca[2048], cert[2048], key[2048];

void loadFile(const char* path, char* buf, size_t len) {
  File f = SPIFFS.open(path, "r");
  if (!f) return;
  size_t s = f.readBytes(buf, len - 1);
  buf[s] = '\0';
  f.close();
}

void setup() {
  Serial.begin(115200);
  SPIFFS.begin();
  loadFile("/ca.pem", ca, sizeof(ca));
  loadFile("/client.pem", cert, sizeof(cert));
  loadFile("/client.key", key, sizeof(key));

  espClient.setCACert(ca);
  espClient.setCertificate(cert);
  espClient.setPrivateKey(key);
  client.setServer("broker.example.com", 8883);

  if (client.connect("device-01")) {
    Serial.println("Connected with certificate auth");
  }
}```

Connected with certificate auth (Client certificate verified by broker)


## Prevention

MQTT certificate auth uses X.509 certificates. The broker must trust the CA that signed your client cert. Client presents cert+key during TLS handshake on port 8883. Store certs in SPIFFS/LittleFS as PEM (base64). The Common Name (CN) in the client cert can be used for ACL rules on the broker.

DodaTech engineers apply these same patterns across Doda Browser, DodaZIP, and Durga Antivirus Pro for production IoT reliability.

## FAQ

<details style="margin-bottom:12px;border:1px solid #e2e8f0;border-radius:10px;overflow:hidden"><summary style="cursor:pointer;padding:14px 18px;font-weight:600;font-size:1.05rem;background:#f8fafc;border-bottom:1px solid #e2e8f0;color:#1e293b">### What certificate format?</summary><div style="padding:14px 18px;color:#475569;line-height:1.7;background:#fff"><p>PEM format (base64). Include full chain for intermediate CAs. Private key must be in PKCS 1/PKCS 8 PEM without password.</p>
<h3 id="how-to-generate-client-certificates">How to generate client certificates?</h3><p>OpenSSL: create CA, then openssl req -new -key client.key -out client.csr &amp;&amp; openssl x509 -req -in client.csr -CA ca.pem -CAkey ca.key -out client.pem.</p>
<h3 id="can-i-use-self-signed-certs">Can I use self-signed certs?</h3><p>Yes, for development. Both broker and client must trust the self-signed CA. For production, use proper CA or Let's Encrypt.</p>
</div></details>

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro