Notification texts go here Contact Us Buy Now!

Call Microsoft Graph API with Function App that is linked to a Static Web App

Call Microsoft Graph API with Function App that is linked to a Static Web App

In a scenario where you are using BYOF (Bring Your Own Function), the authentication method utilized in the Azure Static Web App will not work for your Function App. This is because Azure Functions cannot execute interactive login inside the app, which is necessary for user-specific flows like Implicit or Auth code flow.

To address this issue, you will need to create an Azure Function with the Client Credentials Flow using an Azure service principal—Client ID, Client Secret, and Tenant ID—as detailed below.

Refer to the following Stack Overflow question for more information.

Function Code

using Azure.Core;
using Azure.Identity;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System.Net.Http.Json;

namespace FunctionApp1
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            var token = await GetAccessToken("Tenant-Id", "Client-Id", "Client-Secret");
            var results = await GetResults(token);

            return new OkObjectResult(results);
        }

        private static async Task<string> GetAccessToken(string tenantId, string clientId, string clientKey)
        {
            var credentials = new ClientSecretCredential(tenantId, clientId, clientKey);
            var result = await credentials.GetTokenAsync(new TokenRequestContext(new[] { "https://graph.microsoft.com/.default"
}), default);
            return result.Token;
        }

        private static async Task<string> GetResults(string token)
        {
            var httpClient = new HttpClient
            {
                BaseAddress = new Uri("https://graph.microsoft.com/v1.0/")
            };

            string URI = $"users/a8f97275-2685-41ce-a61d-dc550cd090f8";

            httpClient.DefaultRequestHeaders.Remove("Authorization");
            httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
            HttpResponseMessage response = await httpClient.GetAsync(URI);

            var HttpsResponse = await response.Content.ReadAsStringAsync();
            //var JSONObject = JsonConvert.DeserializeObject<object>(HttpsResponse);

            //return response.StatusCode.ToString();
            return HttpsResponse;
        }
    }
}

Output

After successfully setting up the Function App, you can add it to your Azure Static Web App and call it along with the static web app URL.

enter image description here

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.