azureservicebusazure-sdk-python

How to generate a SAS token for a ServiceBus subscription with the python azure sdk?


I am building a service that needs to create at runtime a servicebus namespace, topic and subscriptions. I need to genrate the sas token(or url) to the subscription created by the service and send it to other services in the system.

How can i generate the sas token with the azure python sdk


Solution

  • I'd note in addition to Jim's accurate answer: one can also approach this using the azure-mgmt-servicebus SDK. It would require using azure.common.credentials.ServicePrincpalCredential for authentication, but would give a slightly more structured flow; not only to create the namespace and topic/subscription, but to create or update authorization rules against a given topic or the namespace itself, and then fetch your keys programmatically.

    See the following as a self-contained example:

    from azure.mgmt.servicebus import ServiceBusManagementClient
    from azure.common.credentials import ServicePrincipalCredentials
    from azure.mgmt.servicebus.models import AccessRights
    
    client_id = 'REPLACEME'
    client_secret = 'REPLACEME'
    subscription = 'REPLACEME'
    tenant = 'REPLACEME'
    resource_group_name = 'REPLACEME'
    namespace_name = 'REPLACEME'
    authorization_rule_name = 'REPLACEME'
    topic_name = 'REPLACEME'
    subscription_name = 'REPLACEME'
    authorization_rule_rights = [AccessRights.manage]
    
    credential = ServicePrincipalCredentials(client_id, client_secret, tenant=tenant)
    
    client = ServiceBusManagementClient(credential, subscription)
    
    client.namespaces.create_or_update(resource_group_name, namespace_name)
    client.topics.create_or_update(resource_group_name, namespace_name, topic_name)
    client.subscriptions.create_or_update(resource_group_name, namespace_name, topic_name, subscription_name)
    client.topics.create_or_update_authorization_rule(resource_group_name, namespace_name, topic_name, authorization_rule_name, authorization_rule_rights)
    rule = client.topics.list_keys(resource_group_name, namespace_name, topic_name, authorization_rule_name)
    

    As always, full disclosure, I'm one of the folks maintaining the python azure servicebus lib, so don't hesitate to shout if any of this is unclear.