visual-studio-codeazure-functionsmicrosoft-graph-apiaccess-tokendefaultazurecredential

DefaultAzureCredential: Graph access forbidden with VisualStudio Code Credential


I'm trying to read user properties from ms graph inside an Azure function. For authentication I used the DefaultAzureCredential class from Azure.Identity.

Access with Shared Token Cache Credential locally and Managed Identity Credential in Azure is no prob! I wanted to use the Visual Studio Code Credential, but I get an "Authorization_RequestDenied! Insufficient privileges to complete the operation" error message when I call the graph API.

The problem seems to be the access token I received with the VS Code Credential. The user account is the same one I used with the Shared Token Cache Credential.

Any ideas? Thank you.

Code:

DefaultAzureCredentialOptions options = new DefaultAzureCredentialOptions();
options.VisualStudioCodeTenantId = Environment.GetEnvironmentVariable("Debug_VisualStudioCodeTenantId");


var credential = new DefaultAzureCredential(options);
token = credential.GetToken(
                    new Azure.Core.TokenRequestContext(
                        new[] { "https://graph.microsoft.com/.default" }));

accessToken = token.Token;


var graphServiceClient = new GraphServiceClient(
            new DelegateAuthenticationProvider((requestMessage) =>
            {
                requestMessage
                .Headers
                .Authorization = new AuthenticationHeaderValue("bearer", accessToken);

                return Task.CompletedTask;
            }));

var users = await graphServiceClient.Users.Request().GetAsync(); // throw the forbidden exception

Exception: "Code: Authorization_RequestDenied\r\nMessage: Insufficient privileges to complete the operation.\r\nInner error:\r\n\tAdditionalData:\r\n\tdate: 2021-04-20T08:02:23\r\n\trequest-id: ...\r\n\tclient-request-id: ...\r\nClientRequestId: ...\r\n"


Solution

  • After inspecting the token returned by VS Code, it seems to be missing a required delegated permission/scope. The docs say one of these is required to list users:

    User.ReadBasic.All, User.Read.All, User.ReadWrite.All, Directory.Read.All, Directory.ReadWrite.All, Directory.AccessAsUser.All

    Since the service principal that VS Code is using does not require any of these, it won't work. After trying to explicitly get the token with the required scope, it doesn't seem to work either.

    So the VS Code credential currently just doesn't seem to work for this purpose. You'll need a different credential or perhaps use the client secret/certificate credential with your own app registration.