Search code examples
azureazure-storageazure-resource-manager

Calling azure resource manager storage API from window desktop app using user credentials


I want to call this API from azure resource manager to get the storage keys: https://learn.microsoft.com/en-us/rest/api/storagerp/storageaccounts/listkeys

I want to use user authentication for this call and possibly .net sdk. Is there any .net sdk(Nuget package) I can include in my c# project to call this API? I am seeing many solution which is using .net sdk but they are using AAD app secret, but I cannot use secret in the app since it is a desktop app. I think there should be a way to call these API with user auth and .net sdk.


Solution

  • The Microsoft.Azure.Services.AppAuthentication for .NET library may meet your requirement. It uses the developer's credentials to authenticate during local development. When the solution is later deployed to Azure, the library automatically switches to application credentials.

    The Microsoft.Azure.Services.AppAuthentication library supports local development with Microsoft Visual Studio, Azure CLI, or Azure AD Integrated Authentication.

    Sample:

    using Microsoft.Azure.Management.Storage;
    using Microsoft.Azure.Services.AppAuthentication;
    using Microsoft.Rest;
    
    namespace ConsoleApp6
    {
        class Program
        {
            static void Main(string[] args)
            {
                AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
                string accessToken = azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/").Result;
                var Credentials = new TokenCredentials(accessToken);
                var storageManagementClient = new StorageManagementClient(Credentials);
                storageManagementClient.SubscriptionId = "subscription id";
                var storageAccountKey = storageManagementClient.StorageAccounts.ListKeysAsync("resource grouop name", "storage account name");
                string storage_Account_Key = storageAccountKey.Result.Keys[0].Value;
                System.Console.WriteLine(storage_Account_Key);
            }
        }
    }
    

    enter image description here

    For more details about the authentication, you could take a look at this link.