Skip to content
Stand with Ukraine flag

SCRAM authentication

SCRAM (Salted Challenge Response Authentication Mechanism) is a password-based MQTT authentication method in which the password never travels over the network. The client proves it knows the password, and the broker proves it holds the matching credentials, so both sides are authenticated. TBMQ supports SCRAM-SHA-256 and SCRAM-SHA-512 (RFC 5802, RFC 7677) and runs them over MQTT 5.0 enhanced authentication: the AUTH packet and the Authentication Method and Authentication Data properties.

SCRAM fits deployments that want password authentication without handing the password to the broker on every connection. Compared with the other username-and-password options:

Basic SCRAM
What the client sends The password, in the CONNECT packet A proof derived from the password; the password itself is never sent
Who is verified The client The client, and from TBMQ 2.4.2 also the broker
What TBMQ stores A bcrypt hash of the password A salt and two keys derived from the password
MQTT versions 3.1, 3.1.1 and 5.0 5.0 only
Credentials matched by Client ID, username, password, depending on the authentication strategy Username only
${clientId} in authorization rules Supported Not supported
Execution order Takes part in the provider execution order Outside the execution order
Client tooling Every MQTT client Clients that implement the MQTT 5.0 AUTH exchange

Choose Basic when you need MQTT 3.x devices, per-client-ID credentials or the simplest client setup. Choose SCRAM when the password must not reach the broker, or when clients should verify that they are talking to a broker that holds their credentials.

SCRAM does not replace TLS. It protects the password, not the messages that follow the handshake, and TBMQ does not support SCRAM channel binding. Without TLS, an attacker who records a handshake can still try to guess a weak password offline, and every PUBLISH after the handshake travels in clear text. Use SCRAM over an MQTTS listener in production.

SCRAM bypasses the provider execution order

Section titled “SCRAM bypasses the provider execution order”

The other providers — Basic, X.509, JWT and HTTP — run in the configured execution order. SCRAM does not. The client chooses SCRAM itself, by setting the Authentication Method property in CONNECT:

  • Authentication Method is SCRAM-SHA-256 or SCRAM-SHA-512 → TBMQ runs the SCRAM handshake and nothing else. The User Name and Password fields of CONNECT and any client certificate are not used for authentication. If SCRAM fails, TBMQ does not fall back to another provider.
  • Authentication Method is any other value → TBMQ refuses the connection with 0x8C (Bad authentication method). The value is case-sensitive: scram-sha-256 is refused.
  • Authentication Method is absent → the connection goes through the execution order as usual. SCRAM credentials are never checked on this path. With SCRAM as the only enabled provider, see Accept only SCRAM clients.

To accept only SCRAM clients, enable SCRAM and disable Basic, X.509, JWT and HTTP. From TBMQ 2.4.2, TBMQ then refuses every client that doesn’t send an Authentication Method — every MQTT 3.x client, and every MQTT 5 client that doesn’t use SCRAM. The client gets CONNACK 0x87 (Not authorized) on MQTT 5 or 0x05 (Connection Refused, not authorized) on MQTT 3.x, and the attempt appears on the Unauthorized clients page with the reason Only SCRAM authentication is enabled; the client must use an MQTT 5 Authentication Method. The built-in WebSocket client authenticates with Basic credentials, so it can’t connect in this setup.

TBMQ runs without authentication only when every provider, SCRAM included, is disabled.

While Basic stays enabled next to SCRAM, for example during a migration, any client with valid Basic credentials can connect without SCRAM. That includes TBMQ WebSockets MQTT Credentials, the system credential behind the WebSocket client: username tbmq_websockets_username, no password, access to all topics, and it can’t be deleted or renamed. A Basic credential without a password accepts any password, so set a strong password and narrow rules on it.

A SCRAM connection takes four messages. Each one travels in the Authentication Data property of an MQTT packet:

  1. Client → TBMQ, CONNECT. Authentication Method is SCRAM-SHA-256 or SCRAM-SHA-512. Authentication Data is the client-first message: the username and a random client nonce.
  2. TBMQ → client, AUTH with reason code 0x18 (Continue authentication). The server-first message: the client nonce extended with a server nonce, the salt stored with the credentials, and the iteration count.
  3. Client → TBMQ, AUTH with reason code 0x18. The client-final message: the combined nonce and a proof the client computes from the password, the salt and everything exchanged so far. The Authentication Method must be the same as in CONNECT.
  4. TBMQ → client, CONNACK. TBMQ checks the proof against the stored keys. On success, the reason code is 0x00. From TBMQ 2.4.2, Authentication Data holds the server-final message: a server signature the client checks to confirm that the broker holds its credentials.

This is what the four messages look like for user sensor-01 with SCRAM-SHA-256:

CONNECT n,,n=sensor-01,r=fyko+d2lbbFgONRv9qkxdawL
AUTH r=fyko+d2lbbFgONRv9qkxdawL3kd9v0rq2m8x1z7pbn4c5w6hya,s=QSXCR+Q6sek8bf92QSXCRw==,i=4096
AUTH c=biws,r=fyko+d2lbbFgONRv9qkxdawL3kd9v0rq2m8x1z7pbn4c5w6hya,p=OVa38kTF+vLvJpxHVxvAeTGO7KVCYNddmCCQWNTMxnw=
CONNACK v=MPv+kDTEu8GmVo23mERIM6PnySdyNlXHGRhTqjSBl5s=

Nonces and the salt are random, and the proof changes with them, so a recorded exchange can’t be replayed.

TBMQ never stores the password. When you save SCRAM credentials, it generates a random 16-byte salt, derives a salted password with PBKDF2 (4096 iterations, using the hash of the selected algorithm), and keeps only two keys derived from it: the stored key, which verifies client proofs, and the server key, which signs the server-final message. The iteration count is fixed and can’t be configured.

As a result, nobody — including administrators — can read a SCRAM password back from TBMQ. To change it, enter a new one. Treat the stored keys as secrets anyway: per RFC 5802, someone who obtains them can impersonate the broker to clients that use these credentials.

The SCRAM provider is disabled by default and has no settings beyond its status. Enabling or disabling it takes effect on every TBMQ node immediately, with no restart:

  • On the Home page, in the Broker Settings card, click the button next to SCRAM authentication.
  • Or go to Authentication → Providers and turn on the switch in the SCRAM row.

While the provider is disabled, TBMQ refuses every SCRAM connection with 0x87 (Not authorized). Disabling it doesn’t disconnect clients that are already connected; they are refused on their next connection or re-authentication.

To enable the provider with the REST API, look up its ID and call enable with a system administrator’s token:

Terminal window
SCRAM_PROVIDER_ID=$(curl -s 'http://localhost:8083/api/mqtt/auth/provider/type/SCRAM' \
--header "X-Authorization: Bearer $ACCESS_TOKEN" | jq -r '.id')
curl --request POST "http://localhost:8083/api/mqtt/auth/provider/$SCRAM_PROVIDER_ID/enable" \
--header "X-Authorization: Bearer $ACCESS_TOKEN"

Each SCRAM client needs SCRAM credentials: a username, a password and a hash algorithm, plus the authorization rules the client gets after it connects.

  1. Go to Authentication → Credentials, click Add client credentials, and choose Add client credentials in the menu.

  2. In Client credentials details, enter a Name (it must be unique), choose the Client type, and set Credentials type to SCRAM. Click Next: Authentication and authorization.

  3. Under Authentication, enter the Username and Password, and choose the Secure Hash Algorithm (SHA): SHA-256 (the default) or SHA-512.

  4. Under Authorization rules, set the Publish authorization rule patterns and Subscribe authorization rule patterns, then click Add.

The algorithm must match the client. Credentials saved with SHA-256 work only for clients that send SCRAM-SHA-256, and SHA-512 only for SCRAM-SHA-512. A client that uses the other method fails with 0x87 (Not authorized), the same as a wrong password. The keys depend on the algorithm, so when you change the algorithm of existing credentials, the UI clears the Password field and you must enter the password again.

While the provider is disabled, the credentials table shows SCRAM Auth is disabled next to SCRAM credentials.

TBMQ finds SCRAM credentials by username alone. Their credentialsId is scram|$USERNAME, so:

  • Each username can have one set of SCRAM credentials. Saving a second one fails with Such MQTT Client credentials are already created!.
  • The client ID isn’t checked. Any client ID can connect with the username and password.
  • The same username can also have Basic credentials (username|$USERNAME). The two don’t conflict: a client that sends a SCRAM Authentication Method is checked against the SCRAM credentials, any other client against the Basic ones. This lets you move clients from Basic to SCRAM one at a time. From TBMQ 2.4.2, disabling every other provider when the move is done locks out non-SCRAM clients. On 2.4.1 and earlier, it lets them connect without authentication instead — see Accept only SCRAM clients.

After a successful handshake, the publish and subscribe rule patterns of the matched credentials control which topics the client can use. They work as for Basic credentials — see how rules are evaluated:

  • Each pattern is a regular expression that must match the whole topic. sensors/.* allows every topic under sensors/, and .* (the default) allows any topic.
  • An empty list forbids every topic in that direction.
  • The ${clientId} placeholder is not supported in SCRAM rules: saving credentials that contain it fails with Publish auth rule patterns should be a valid regexes! (or the subscribe equivalent). To give each client its own topics, create one set of SCRAM credentials per client with literal topic prefixes.

The Client type of the credentials decides whether the client connects as a DEVICE or APPLICATION client.

Rules and client type are resolved when the handshake completes. Changes to the credentials apply when the client reconnects.

Many MQTT clients, including mosquitto_pub and mosquitto_sub, can’t run an MQTT 5.0 AUTH exchange. The example below uses MQTT.js in Node.js, which can. It connects with SCRAM, verifies the server signature, then publishes to sensors/temperature and reads the message back.

Install MQTT.js in an empty directory:

Terminal window
npm install mqtt

Save the client as scram-client.js:

scram-client.js
// SCRAM (RFC 5802) over MQTT 5.0 enhanced authentication, using MQTT.js.
// Usage: node scram-client.js <host> <username> <password> [SCRAM-SHA-256|SCRAM-SHA-512] [--no-verify]
// --no-verify skips the server signature check, for TBMQ 2.4.1 and earlier (no server-final message in CONNACK).
const crypto = require('crypto');
const mqtt = require('mqtt');
const args = process.argv.slice(2);
const verifyServer = !args.includes('--no-verify');
const [host = 'localhost', username, password, method = 'SCRAM-SHA-256'] = args.filter((a) => a !== '--no-verify');
const hash = method === 'SCRAM-SHA-512' ? 'sha512' : 'sha256';
const keyLength = hash === 'sha512' ? 64 : 32;
const hmac = (key, data) => crypto.createHmac(hash, key).update(data).digest();
const escape = (name) => name.replace(/=/g, '=3D').replace(/,/g, '=2C');
// 1. client-first-message, sent in CONNECT
const clientNonce = crypto.randomBytes(18).toString('base64');
const clientFirstBare = `n=${escape(username)},r=${clientNonce}`;
let authMessage;
let saltedPassword;
const client = mqtt.connect(`mqtt://${host}:1883`, {
protocolVersion: 5,
clientId: `scram-demo-${crypto.randomBytes(4).toString('hex')}`,
properties: {
authenticationMethod: method,
authenticationData: Buffer.from(`n,,${clientFirstBare}`),
},
reconnectPeriod: 0,
});
// 2. server-first-message arrives in an AUTH packet; answer with client-final-message
client.handleAuth = (packet, callback) => {
const serverFirst = packet.properties.authenticationData.toString();
const attrs = Object.fromEntries(serverFirst.split(',').map((kv) => [kv[0], kv.slice(2)]));
if (!attrs.r.startsWith(clientNonce)) return callback(new Error('Server nonce mismatch'));
saltedPassword = crypto.pbkdf2Sync(password, Buffer.from(attrs.s, 'base64'), Number(attrs.i), keyLength, hash);
const clientKey = hmac(saltedPassword, 'Client Key');
const storedKey = crypto.createHash(hash).update(clientKey).digest();
const clientFinalNoProof = `c=biws,r=${attrs.r}`;
authMessage = `${clientFirstBare},${serverFirst},${clientFinalNoProof}`;
const clientSignature = hmac(storedKey, authMessage);
const proof = Buffer.from(clientKey.map((b, i) => b ^ clientSignature[i])).toString('base64');
callback(null, {
cmd: 'auth',
reasonCode: 0x18, // Continue authentication
properties: {
authenticationMethod: method,
authenticationData: Buffer.from(`${clientFinalNoProof},p=${proof}`),
},
});
};
// 3. CONNACK carries the server-final-message: verify the server's signature
client.on('connect', (connack) => {
if (verifyServer) {
const serverFinal = connack.properties?.authenticationData?.toString();
const expected = hmac(hmac(saltedPassword, 'Server Key'), authMessage).toString('base64');
if (serverFinal !== `v=${expected}`) {
console.error('Server signature mismatch, closing the connection');
return client.end();
}
console.log('Connected and server verified');
} else {
console.log('Connected, server signature not verified');
}
client.subscribe('sensors/#', () => client.publish('sensors/temperature', '21.5'));
});
client.on('message', (topic, payload) => {
console.log(`Received ${payload} on ${topic}`);
client.end();
});
client.on('error', (err) => {
console.error(`Connection failed: ${err.message} (reason code ${err.code})`);
client.end();
});

Run it with the username and password of your SCRAM credentials and the method that matches their algorithm:

Terminal window
node scram-client.js localhost YOUR_USERNAME YOUR_PASSWORD SCRAM-SHA-256

On success, it prints:

Connected and server verified
Received 21.5 on sensors/temperature

TBMQ 2.4.1 and earlier don’t send the server signature in CONNACK, so the check fails with Server signature mismatch, closing the connection. With those versions, add --no-verify:

Terminal window
node scram-client.js localhost YOUR_USERNAME YOUR_PASSWORD SCRAM-SHA-256 --no-verify

The first line then reads Connected, server signature not verified.

The credentials’ publish and subscribe rules must allow sensors/temperature, or the example connects but the round trip fails.

The example connects over plain TCP on port 1883. For MQTTS, change the URL to mqtts:// and the port to 8883; if the broker uses a self-signed certificate, also pass its CA certificate in the ca connection option.

Open Sessions and select the client. In Client info, Auth provider shows SCRAM, and Client type shows the type set in the credentials.

To connect from another MQTT 5.0 library, check that it lets you set the Authentication Method and Authentication Data in CONNECT, answer an incoming AUTH packet with your own, and read the Authentication Data of CONNACK. TBMQ expects standard SCRAM messages (RFC 5802), with these constraints:

  • The client-first message starts with the n channel-binding flag (n,,). A message that starts with y or p= is refused: TBMQ doesn’t support channel binding.
  • The authorization identity (a=) is optional; if present, it must equal the username.
  • The tokenauth extension is not supported.
  • , and = in the username are escaped as =2C and =3D.
  • The password isn’t normalized with SASLprep. Clients that normalize non-ASCII passwords can derive different keys, so prefer ASCII passwords for SCRAM credentials.

The MQTT.js example above is a complete implementation of the client side to compare against.

A connected client can repeat the SCRAM exchange without disconnecting, to prove again that it still knows the password. Re-authentication uses only AUTH packets:

  1. The client sends AUTH with reason code 0x19 (Re-authenticate), the same Authentication Method it used in CONNECT, and a new client-first message.
  2. TBMQ answers with AUTH 0x18 and a new server-first message, and the client sends AUTH 0x18 with its client-final message.
  3. TBMQ answers with AUTH 0x00 (Success) and the server-final message.

The session stays connected throughout. If re-authentication fails — wrong password, a different authentication method, or the provider was disabled — TBMQ disconnects the client with DISCONNECT reason code 0x87 (Not authorized) and records the failure on the Unauthorized clients page. Only a client that connected with SCRAM can re-authenticate.

Re-authentication is not a reliable way to apply changed credentials. New subscribe rules take effect, but TBMQ keeps its earlier publish decision for every topic the client has already published to, and the session keeps the client type it connected with. To apply new rules or a new client type, have the client reconnect.

When SCRAM authentication fails during connection, TBMQ refuses it with one of these CONNACK reason codes. Failures that pass the method check also appear on the Unauthorized clients page with the reason shown below.

Reason code Unauthorized clients reason Cause
0x87 Not authorized Failed to verify the client’s proof of password knowledge! Wrong password, or the client’s method doesn’t match the algorithm saved in the credentials
0x87 Not authorized Failed to evaluate client first message! No SCRAM credentials exist for the username, or the client-first message is malformed or requests channel binding
0x87 Not authorized Enhanced authentication provider is disabled by broker configuration The SCRAM provider is disabled
0x87 Not authorized (0x05 on MQTT 3.x) Only SCRAM authentication is enabled; the client must use an MQTT 5 Authentication Method From TBMQ 2.4.2: SCRAM is the only enabled provider and CONNECT has no Authentication Method
0x8C Bad authentication method — The CONNECT Authentication Method isn’t SCRAM-SHA-256 or SCRAM-SHA-512 (case-sensitive)
0x8C Bad authentication method Received AUTH message while authentication method mismatch with value from the client session ctx! The AUTH packet’s Authentication Method differs from the one in CONNECT
0x80 Unspecified error — CONNECT has an Authentication Method but no Authentication Data
0x8A Banned Enhanced auth blocked client by … The client ID or IP address is on the blocked clients list

Other symptoms:

  • The connection never completes after CONNECT. TBMQ has sent the server-first message in an AUTH packet and is waiting for the client-final message. The client library doesn’t implement the AUTH exchange, or isn’t set up to answer it.
  • The connection is accepted, but the client rejects the server signature. On TBMQ 2.4.1 and earlier, CONNACK carries no server-final message; skip the check for those versions (--no-verify in the example client). From 2.4.2, check that the client computes the signature with the same hash as the method it sent.
  • The client connects but can’t publish or subscribe. The authorization rules of the SCRAM credentials don’t match the topic. Rule changes apply when the client reconnects.