Search code examples
oauthjwtmqttauth0json-web-token

How to handle JWT revocation with MQTT


Following the instructions in this Auth0 article, I successfully authenticated MQTT clients using "JWT" as username and the JWT token as a password.

In my use case, however, JWT tokens are short-lived. Clients must fetch a new token before the expiration date of the current token, and then provide it to the MQTT server. Otherwise, the connection is terminated by the server.

My question is: how do I implement the token update? Is it a publish message from the client? To which topic? Do I disconnect the client, and let the client re-authenticate with the new token? Or is there another way?


Solution

  • 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);
    }