How to handle JWT revocation with MQTT

The easiest way is to implement an asynchron service, that checks periodically your connected clients and reads the token timestamp. If the timestamp is to old - force the disconnect of the client, and reconnect.

Depending on the system you use, you can add this functionality to your Message Broker you use.

In HiveMQ for example you can plugin easily an asynchron callback, that schedules these kind of background job and executes this periodically.

The extension system of HiveMQ is well documented and you can find some examples here: https://www.hivemq.com/docs/4/extensions/services.html#managed-extension-executor


Considering refreshing JWT tokens is matter because tokens have expiration dates. If a device is connected over MQTT and its token expires, MQTT broker should automatically disconnect device from broker. You can prevent the device from disconnecting by automatically refreshing its token.

The following samples illustrate how to check whether a token has expired and, if it has, how to reconnect with a new token without disconnecting the device.

long secsSinceRefresh = ((new DateTime()).getMillis() - iat.getMillis()) / 1000;
if (secsSinceRefresh > (options.tokenExpMins * 60)) {
  System.out.format("\tRefreshing token after: %d seconds\n", secsSinceRefresh);
  iat = new DateTime();
  if (options.algorithm.equals("RS256")) {
    connectOptions.setPassword(
        createJwtRsa(options.projectId, options.privateKeyFile).toCharArray());
  } else if (options.algorithm.equals("ES256")) {
    connectOptions.setPassword(
        createJwtEs(options.projectId, options.privateKeyFile).toCharArray());
  } else {
    throw new IllegalArgumentException(
        "Invalid algorithm " + options.algorithm + ". Should be one of 'RS256' or 'ES256'.");
  }
  client.disconnect();
  client.connect();
  attachCallback(client, options.deviceId);
}