Refreshing JSON Web Tokens (JWTs) in Google Cloud IoT Core

Mike Kahn
Google Cloud - Community
2 min readJan 5, 2018

To authenticate to Google Cloud IoT Core and send a message from a device each device must create a JWT before establishing a MQTT or HTTP connection. JWTs are a secure signing method that verifies and sends data between devices and Cloud IoT core topics.

Cloud IoT core JWT and key auth

By default in the quickstart example the JWT exp (“expiration”) has a maximum lifetime of 60 minutes or 3600 seconds:

token = {            
# The time that the token was issued at
'iat': datetime.datetime.utcnow(),
# The time the token expires.
'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), # The audience field should always be set to the GCP project id. 'aud': project_id
}

If you are not refreshing the JWT you may see an error like this one below in Cloud IoT Core (mqtt: SERVER:The authorization token expired). This will delay device publishing and create problems for sensors that need to maintain a reliable data stream.

Device not refreshing JWT token and having a bad time

Check lines 222–233 on the python IoT Core MQTT sample for code on how to plugin a JWT refresh into your script. More details as well on the Cloud IoT Core documentation page.

seconds_since_issue = (datetime.datetime.utcnow() - jwt_iat).seconds
if seconds_since_issue > 60 * jwt_exp_mins:
print('Refreshing token after {}s').format(seconds_since_issue)
client.loop_stop()
jwt_iat = datetime.datetime.utcnow()
client = get_client(
args.project_id, args.cloud_region,
args.registry_id, args.device_id, args.private_key_file,
args.algorithm, args.ca_certs, args.mqtt_bridge_hostname,
args.mqtt_bridge_port)

Also, check my github issue here for more on the JWT refresh and JWT.io for helper libraries in nearly every language.

Thanks to Gus Class for the code assist and @noerog for making GCP documentation better everyday.

Paolo reached out to me and let me know of the helper he created that creates IoT Core MQTT clients in node. This is wonderful for devices with a weak connection with occasional disconnects. Thanks Paolo. You can check it out here.

Update: As of April 2018 you can use a longer expiration up to 24 hours from the issue time + skew time. This can save you from having to regenerate tokens on constrained devices.

--

--

Mike Kahn
Google Cloud - Community

Field Engineering Manager, Databricks. All views and opinions are my own. @mkahn5