Skip to content

Instantly share code, notes, and snippets.

@ChrisRomp
Created October 14, 2021 18:02
Show Gist options
  • Save ChrisRomp/000934f8484c6f67fdfff9b8c5ef5dca to your computer and use it in GitHub Desktop.
Save ChrisRomp/000934f8484c6f67fdfff9b8c5ef5dca to your computer and use it in GitHub Desktop.
Example of authenticating to Azure Storage Blob service with AD-delegated SAS key using the machine/service managed identity
import xml.dom.minidom
import html
from datetime import datetime, timedelta
import requests
from azure.identity import ClientSecretCredential, ManagedIdentityCredential
from azure.storage.blob import BlobServiceClient, generate_container_sas, AccountSasPermissions
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello, world."
@app.route("/storage")
def storage():
# # Service Principal
# tenant_id = ""
# client_id = "" # Blob Data Contributor
# client_secret = ""
# # Get Service Principal credential
# cred = ClientSecretCredential(
# tenant_id,
# client_id,
# client_secret
# )
# Using Managed Identity credential
managed_identity = ManagedIdentityCredential()
# Storage Account/Container
account_name = "myaccount"
container_name = "container1"
account_url = f"https://{account_name}.blob.core.windows.net"
# Using AD/RBAC to auth for blob client
blob_client = BlobServiceClient(
account_url=account_url,
credential=managed_identity
)
# Get user-delegated key
user_key = blob_client.get_user_delegation_key(
key_start_time = datetime.utcnow(),
key_expiry_time = datetime.utcnow() + timedelta(minutes=5)
)
# Generate AD-delegated SAS token for container
container_sas_token = generate_container_sas(
account_name=account_name,
container_name=container_name,
user_delegation_key=user_key,
permission=AccountSasPermissions(read=True,write=True,list=True),
expiry=datetime.utcnow() + timedelta(minutes=5)
)
# Format request (list files in container)
url = f"{account_url}/{container_name}?restype=container&comp=list&{container_sas_token}"
headers = {
"x-ms-version": "2017-11-09",
"x-ms-date": f"{datetime.utcnow().ctime()} GMT"
}
# GET container contents
result = requests.get(
url=url,
headers=headers
)
# Format output
parsed_xml = xml.dom.minidom.parseString(result.text)
formatted_xml = parsed_xml.toprettyxml()
output = f"Request URL: {url}\r\n\r\nResult:\r\n\r\n{html.escape(formatted_xml)}"
return f"<pre>{output}</pre>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment