Microsoft Graph permissions issue when using managed identity and DefaultAzureCredential

Viewed 67

I have set up a test project that follows this microsoft guide: https://docs.microsoft.com/en-us/azure/app-service/scenario-secure-app-access-microsoft-graph-as-app?tabs=azure-powershell

The only difference that I made from that tutorial is the code portion. I changed it to look like this:

TokenCredential tokenCredential = new DefaultAzureCredential();

var scopes = new[] { "https://graph.microsoft.com/.default" };

var graphClient = new GraphServiceClient(tokenCredential, scopes);

var group = graphClient.Groups["<my-group-id>"].Request().GetAsync().Result;

Everything works as expected when I publish the website and access it, but when I run this code locally I receive

Insufficient privileges to complete the operation.

I am signed into VS using the same account that I am using in Azure portal (it's a global admin account). Is there any other configuration setting that I am missing so that I can run this code and test locally?

1 Answers
  1. Usually you need one of the following permissions to query groups i.e delegated and application permissions : GroupMember.Read.All, Group.Read.All, Directory.Read.All, Group.ReadWrite.All, Directory.ReadWrite.All User.Read.All
  2. Run VS as administrator and also give user administrator role.

enter image description here

  • But visual studio may not work in this case . So please try with different credential type like client secret/certificate credential with your app .
  • In local debugging ,use Shared Token Cache Credential ,as in your local environment, DefaultAzureCredential uses the shared token credential from the IDE.
  • In Visual Studio, you can set the account that you want to use when debugging using VS : under Options -> Azure Service Authentication.

enter image description here

Please check Azure Managed Service Identity And Local Development by Rahul Nath (rahulpnath.com)

If multiple accounts are configured, try to set the SharedTokenCacheUsername property to that specific account to use.

var azureCredentialOptions = new DefaultAzureCredentialOptions();
 azureCredentialOptions.SharedTokenCacheUsername = "<azure ad User Name>";
var credential = new DefaultAzureCredential(azureCredentialOptions);

Reference: DefaultAzureCredential: Unifying How We Get Azure AD Token | Rahul Nath (rahulpnath.com)

Related