Skip to content

Instantly share code, notes, and snippets.

@rsp9u
Last active June 11, 2025 06:21
Show Gist options
  • Select an option

  • Save rsp9u/2c4e0c3806cc227db6aca88ed84fd37c to your computer and use it in GitHub Desktop.

Select an option

Save rsp9u/2c4e0c3806cc227db6aca88ed84fd37c to your computer and use it in GitHub Desktop.
Authn Azure Event Grid MQTT broker with Managed ID
# ref:
# * https://learn.microsoft.com/en-us/azure/event-grid/mqtt-client-microsoft-entra-token-and-rbac
# * https://github.com/eclipse-paho/paho.mqtt.python/blob/master/src/paho/mqtt/properties.py
from paho.mqtt.client import Client as MqttClient, MQTTv5
from paho.mqtt.properties import Properties as MqttProperties
from paho.mqtt.packettypes import PacketTypes as MqttPacketTypes
from azure.identity import DefaultAzureCredential
scope = "https://eventgrid.azure.net/"
cred = DefaultAzureCredential()
token = cred.get_token(scope).token
uri = "xxx-xxx-xxx.ts.eventgrid.azure.net"
topic = "topicspace1/msg"
client_id = "client-oauth"
connect_properties = MqttProperties(MqttPacketTypes.CONNECT)
connect_properties.AuthenticationMethod = "OAUTH2-JWT"
connect_properties.AuthenticationData = token.encode()
client = MqttClient(client_id, protocol=MQTTv5)
client.tls_set()
client.connect(uri, 8883, 60, properties=connect_properties)
for i in range(5):
time.sleep(1)
result = client.publish(topic, f"payload:{i}")
print(f"sent {topic}: {payload}. return code:{result[0]}")
client.disconnect()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment