[Python] Generating SAS URL for Azure Blob Container with Proper Permissions

Discussão em 'Python' iniciado por Stack, Dezembro 19, 2024.

  1. Stack

    Stack Membro Participativo

    I'm attempting to generate a Shared Access Signature (SAS) URL for an Azure Blob storage container using Python and the Azure SDK. The SAS token is successfully generated, but when I try to use it to upload a file to the container, I encounter an "AuthorizationPermissionMismatch" error.

    def generate_sas_url_for_container(strg_account, credentials, container_name, permissions, validity_hours):
    try:
    # Create BlobServiceClient using the storage account name and credentials
    blob_service_client = BlobServiceClient(account_url=f"https://{strg_account}.blob.core.windows.net/", credential=credentials)

    # Define permissions for the SAS token
    container_permissions = ContainerSasPermissions(read=permissions.read, create=permissions.create, list=permissions.list)
    user_delegation_key = blob_service_client.get_user_delegation_key(datetime.utcnow(), datetime.utcnow() + timedelta(hours=1))

    # Define expiry for the SAS token
    expiry = datetime.utcnow() + timedelta(hours=validity_hours)

    # Generate SAS token for the container
    sas_token = generate_container_sas(
    account_name=blob_service_client.account_name,
    user_delegation_key=user_delegation_key,
    container_name=container_name,
    account_key=None,
    permission=container_permissions,
    expiry=expiry,
    sv="2020-08-04"
    )
    sas_url = f"https://{blob_service_client.account_name}.blob.core.windows.net/{container_name}?{sas_token}"
    return sas_url
    except Exception as e:
    print(f"Error generating SAS URL for container: {e}")
    return None


    And here's the error message I'm encountering when trying to use the generated SAS URL to upload a file:

    <?xml version="1.0" encoding="utf-8"?><Error><Code>AuthorizationPermissionMismatch</Code><Message>This request is not authorized to perform this operation using this permission.
    RequestId:a6cfe60c-501e-0095-40bf-a00
    Time:2024-05-14T05:26:24.9759212Z</Message></Error>

    Continue reading...

Compartilhe esta Página