How to get file from Azure services(Azure blob storage) using Azure Service Principal Name(SPN) using C#.net?

985 Views Asked by At

In General, I want to get files from the Azure blob storage account using C#.net, and I have an SPN name. I have tried the following ways to do it.

Note: Here Authentication key stored in KEY Vault and Azure admin provide us only SPN Name

Way 1:

private static async Task<string> GetAccessToken()
string accessToken = "";
            try
            {
                var authContext = new AuthenticationContext($"https://login.windows.net/{TenantID}");
                var credential = new ClientCredential("{ClientID}", "{SPN Name}");
                var result = await authContext.AcquireTokenAsync("https://storage.azure.com", credential);

                if (result == null)
                {
                    throw new Exception("Failed to authenticate via ADAL");
                }
                accessToken = result.AccessToken;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine("Exception for get Blob container" + ex.Message.ToString());
            }

Way 2:

private static async Task<string> GetAccessToken()
 var serviceTokenProvider = new AzureServiceTokenProvider();

            var keyVaultClient = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(serviceTokenProvider.KeyVaultTokenCallback));
          
            SecretBundle secretValue = null;
            try
            {
                secretValue = await keyVaultClient.GetSecretAsync("{KeyVault URI}", {SPN_Name});
            }
            catch (Exception kex)
            {
                System.Diagnostics.Trace.WriteLine("Exception for get Blob container" + kex.Message.ToString());
            }
           return secretValue.Value;

Following code to Access File from Azure Storage

public static async Task<List<IListBlobItem>> GetBlobContainer( string containerName)
        var token = await GetAccessToken();
                TokenCredential tokenCredential = new TokenCredential(token);
        //here i am getting all one day file
                DateTime date = DateTime.Now;
                date = date.AddDays(-1);
               
                StorageCredentials _objectCrentials = new StorageCredentials(tokenCredential);

                CloudBlobClient blobClient = new CloudBlobClient(new Uri($"{Storage Account URI}"), _objectCrentials);
                // container
                CloudBlobContainer blobContainer = blobClient.GetContainerReference(containerName);
                IEnumerable<IListBlobItem> listOfBlob = blobContainer.ListBlobs().OfType<CloudBlob>()
                   .OrderByDescending(b => b.Properties.LastModified > date);
                //check her do you get any list
                _list = listOfBlob.ToList();

Way 2 have gives this error.

Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/{tenantID}. Exception Message: Tried the following 3 methods to get an access token, but none of them worked. Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/{tenantID}. Exception Message: Tried to get token using Managed Service Identity. Unable to connect to the Instance Metadata Service (IMDS). Skipping request to the Managed Service Identity (MSI) token endpoint. Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/{tenantID}. Exception Message: Tried to get token using Visual Studio. Access token could not be acquired. Exception for Visual Studio token provider Microsoft.Asal.TokenService.exe : TS003: Error, TS005: No accounts found. Please go to Tools->Options->Azure Services Authentication, and add an account to be to authenticate to Azure services during development.

Parameters: Connection String: [No connection string specified], Resource: https://vault.azure.net, Authority: https://login.windows.net/{tenantID}. Exception Message: Tried to get token using Azure CLI. Access token could not be acquired. 'az' is not recognized as an internal or external command, operable program or batch file.

Please correct me if followed wrong steps.

0

There are 0 best solutions below