Search code examples
azureazure-data-lake

Use DefaultAzureCredential for DataLakeServiceClient


I have an api that grants sas tokens to callers to upload files to blob storage. I would like to get this working with the DefaultAzureCredential.

This is the code in my program.cs:

builder.Services.AddAzureClients(azureBuilder => 
{
    var credential = new DefaultAzureCredential();
    azureBuilder.UseCredential(credential);
    azureBuilder.AddDataLakeServiceClient(new Uri("https://mystorageaccount.dfs.core.windows.net/"));
});

And this is how i generate the sas uri:

        public string GenerateSasUri(string containerName) 
        {
            if (string.IsNullOrWhiteSpace(containerName)) throw new ArgumentNullException(nameof(containerName));

            var permissions = DataLakeFileSystemSasPermissions.Add 
                | DataLakeFileSystemSasPermissions.Write
                | DataLakeFileSystemSasPermissions.Create
                | DataLakeFileSystemSasPermissions.List;

            return _dataLakeServiceClient
                .GetFileSystemClient(containerName)
                .GenerateSasUri(permissions, DateTimeOffset.Now.AddMinutes(15))
                .AbsoluteUri;
        }

But i am getting this error:

System.ArgumentNullException: 'Value cannot be null. (Parameter 'sharedKeyCredential')'

Upon inspection of the properties on the DataLakeServiceClient, i see that the _dataLakeServiceClient.CanGenerateAccountSasUri property is false?

Did i misunderstand some things? Is this not supposed to work?


Solution

  • Because you're authenticating using Azure AD you cannot create a service SAS, instead you can only create a user delegation SAS.

    See this article on how to create a user delegation SAS for a blob: Create a user delegation SAS for a blob with .NET.