0

I have an Azure Function which needs to invoke an Azure REST API for Azure Container Instances - basically I just need to restart the Container group- I have managed identity enabled for the function and tried using AzureServiceTokenProvider to get access token to the management API for Azure Containers.

The resource used with token provider is https://management.azure.com. But when I tried accessing the REST API using the token, I am getting Forbidden Error.

I have given Contributor role to my system assigned managed identity for the function. What could be the issue? Code inside the function is as below

var azureServiceTokenprovider = new AzureServiceTokenProvider();
        string accessToken = await azureServiceTokenprovider.GetAccessTokenAsync("https://management.azure.com/");

        var acrUrl = $"https://management.azure.com/subscriptions/{mysubid}/resourceGroups/{reource group name}/providers/Microsoft.ContainerInstance/containerGroups/{container group name}/restart?api-version=2021-09-01";
        HttpClient client = new();
        var content = "{}";
        client.DefaultRequestHeaders.Authorization =    new AuthenticationHeaderValue("Bearer", accessToken);
        var result = await client.PostAsync(acrUrl, new StringContent(content.ToString()));
jereesh thomas
  • 113
  • 1
  • 13
  • Can you add your azure function code, or at least the way your are using DefaultAzureCredential from the azure identity package ? – Quentin Geff Jan 05 '22 at 15:32
  • 1
    I have added the code inside the function – jereesh thomas Jan 05 '22 at 16:17
  • Is the access token correct ? you can check with tools like this : https://jwt.ms/ Also gave you the contributor role on your containerGroup to the managedID ? Are you able to see the attempt in AD activity logs https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/how-to-view-managed-identity-activity#view-authentication-attempts-by-managed-identities – Quentin Geff Jan 05 '22 at 16:30

1 Answers1

0

I've faced a similar problem. What I did to solve was accessing the Resource Group -> Access Control IAM and gave add the principal to Contributor Role, it worked in my case and I do believe it will work for yours too.

Thiago Custodio
  • 17,332
  • 6
  • 45
  • 90