Calling Microsoft Graph API from inside Azure Functions

后端 未结 3 697
傲寒
傲寒 2020-12-18 07:37

I\'m trying to write a simple Azure Function that calls the Microsoft Graph API. But I could not make the access_token work. Here is what I\'ve done:

  1. Created a
3条回答
  •  旧巷少年郎
    2020-12-18 08:02

    Azure Functions now supports native authentication for the Microsoft Graph. Docs are at https://docs.microsoft.com/en-us/azure/azure-functions/functions-bindings-microsoft-graph

    There's also a video at https://azure.microsoft.com/en-us/resources/videos/azure-friday-navigating-the-microsoft-graph-with-azure-functions-henderson/

    For example, you can create an HttpTrigger function and add the following to function.json.

    {
       "type": "token",
       "direction": "in",
       "name": "graphToken",
       "resource": "https://graph.microsoft.com",
       "identity": "userFromRequest"
    }
    

    Then, you can query the Graph API on behalf of the user making the request. The access token is passed in as a parameter that you can add as a header to an HttpClient

    using System.Net; 
    using System.Net.Http; 
    using System.Net.Http.Headers; 
    
    public static async Task Run(HttpRequestMessage req, string graphToken, TraceWriter log)
    {
        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", graphToken);
        return await client.GetAsync("https://graph.microsoft.com/v1.0/me/");
    }
    

    You can also run functions with the ClientCredentials authentication mode, which means it runs as an app instead of in the context of a particular user.

提交回复
热议问题