Updating JWT tokens matters because tokens have expiration dates. If a device is connected via MQTT and its token expires, the MQTT broker should automatically disconnect the device from the broker. You can prevent the device from turning off by automatically updating its token.
The following examples show how to check if a token has expired, and if there is one, how to reconnect to 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); }
Ruhollah delpak
source share