Search code examples
azuremicrosoft-graph-apiasp.net-core-webapi

The best setup local connect to graph api


I am working on a dotnet 7 web API, which has access (with managed identity) to most of my infrasctructure components; storage, mssql, etc etc. All working perfectly. I am following this article for using managed identity to connect to microsoft graph api (per API and not on behalf on the user): https://learn.microsoft.com/en-us/entra/identity-platform/multi-service-web-app-access-microsoft-graph-as-app?tabs=azure-cli%2Cprogramming-language-csharp&tryIt=true#code-try-1

and while I am running it in the app, all working smooth, but locally it doesn't work, and now using client_credential flow with the app (which has the graph api permissions set), it feels wrong. Now I am actually mananing for deployed apps the permissions on the managed identity, and locally I have to add client secret, and on top of it, set the permissions on the same "test" web app to graph api.

everything inside me tells me I am doing it wrong, but no clue how to do it different :(

EDIT: I am using the EnvironmentCredential setup locally to connect to it.


Solution

  • Managed identity can't be used to authenticate locally running applications. Your application must be deployed to an Azure service that supports Managed Identity.

    We have a tip here although it is not for graph api. Therefore, we need to use some other options when test locally. As we can see in the comment from the article you shared.

    // Create the Graph service client with a ChainedTokenCredential which gets an access
    // token using the available Managed Identity or environment variables if running
    // in development.
    var credential = new ChainedTokenCredential(
            new ManagedIdentityCredential(),
            new EnvironmentCredential());
    
    string[] scopes = new[] { "https://graph.microsoft.com/.default" };
    

    So we could use EnvironmentCredential when test locally. Just adding AZURE_TENANT_ID, AZURE_CLIENT_ID, AZURE_CLIENT_SECRET environment variable in your local machine, then you don't need to use client credential flow instead.

    enter image description here