Search code examples
azureazure-maps

Is it possible to create Azure Maps SAS token programmatically?


This question for Azure maps Not for Storage account.

we implemented SAS token key for Azure maps instead for subscription key. Is it possible to create azure maps SAS token programmatically?, so it can be periodically renew the token whenever it get expire.

enter image description here


Solution

  • For people who come across this question and are looking for an implementation in Python to generate SAS tokens programmatically, here is a solution using the azure-mgmt-maps package from the Microsoft Azure SDK for Python:

    import datetime
    
    from azure.identity import DefaultAzureCredential
    from azure.mgmt.maps import AzureMapsManagementClient
    from azure.mgmt.maps.models import AccountSasParameters, SigningKey
    
    
    def format_time(time: datetime.datetime) -> str:
        return time.strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z'
    
    
    client = AzureMapsManagementClient(
        credential=DefaultAzureCredential(), 
        subscription_id="[your_subscription_id]"
    )
    time_now = datetime.datetime.utcnow()
    sas_params = AccountSasParameters(
        signing_key=SigningKey.MANAGED_IDENTITY,
        principal_id="[your_managed_id_principal_id]",
        max_rate_per_second=500,
        start=format_time(time_now),
        expiry=format_time(time_now + datetime.timedelta(hours=2)),
        regions=["westeurope"]
    )
    sas_token = client.accounts.list_sas(
        resource_group_name="[your_resource_group_name]",
        account_name="[your_azure_maps_account_name]",
        maps_account_sas_parameters=sas_params
    )
    print(sas_token.account_sas_token)