0

Is there a built-in way to setup an isolated Azure Function to use Microsoft.Identity authentication similar to a Web API or MVC app using services.AddAuthentication(...)?

I swear I saw a video demoing this but I have looked for days and can not find it.

I am at the point where I don't want to use the built in auth from app service anymore.

1 Answer 1

-2

Yes, you can make use of Azure.Identity in Azure Functions Isolated Trigger like below:-

I am using Azure.Identity from Azure Isolated Function to get the List of Resource group from my Function Trigger using Client Credentials flow:-

Function1.cs:-

using System.Net;
using Microsoft.Azure.Functions.Worker;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using System.Net.Http;
using Microsoft.Azure.Functions.Worker.Http;
using Newtonsoft.Json;

namespace FunctionApp1
{
    public class Function1
    {
        private readonly ILogger<Function1> _logger;
        private readonly IHttpClientFactory _httpClientFactory;

        public Function1(ILogger<Function1> logger, IHttpClientFactory httpClientFactory)
        {
            _logger = logger;
            _httpClientFactory = httpClientFactory;
        }

        [Function("Function1")]
        public async Task<HttpResponseData> RunAsync(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req,
            FunctionContext executionContext)
        {
            _logger.LogInformation("C# HTTP trigger function processed a request.");

            var token = await GetAccessToken("TENANT-ID", "CLIENT-ID", "CLIENT-SECRET");
            var results = await GetResults(token);

            var response = req.CreateResponse(HttpStatusCode.OK);
            response.Headers.Add("Content-Type", "application/json; charset=utf-8");

            await response.WriteStringAsync(JsonConvert.SerializeObject(results));

            return response;
        }

        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://management.azure.com/.default" }), default);
            return result.Token;
        }

        private async Task<string> GetResults(string token)
        {
            var httpClient = _httpClientFactory.CreateClient();
            httpClient.BaseAddress = new Uri("https://management.azure.com/");

            string subscriptionId = "0151c365-f598-44d6-b4fd-e2b6e97cb2a7";
            string apiVersion = "2021-04-01";

            string URI = $"subscriptions/{subscriptionId}/resourcegroups?api-version={apiVersion}";

            httpClient.DefaultRequestHeaders.Remove("Authorization");
            httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

            var response = await httpClient.GetAsync(URI);

            if (response.IsSuccessStatusCode)
            {
                var content = await response.Content.ReadAsStringAsync();
                return content;
            }
            else
            {
                // Handle the error response here
                return "Error: " + response.StatusCode.ToString();
            }
        }
    }
}

Program.cs:-

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var host = new HostBuilder()
    .ConfigureFunctionsWebApplication()
    .ConfigureServices(services =>
    {
        services.AddApplicationInsightsTelemetryWorkerService();
        services.AddHttpClient(); // Adding IHttpClientFactory
    })
    .Build();

host.Run();

Output:-

enter image description here

Browser:-

enter image description here

Reference:- azure - Call Microsoft Graph API with Function App that is linked to a Static Web App - Stack Overflow

Sign up to request clarification or add additional context in comments.

1 Comment

I am looking to use Azure Identity in place of built in Azure Functions Authentication as a middle ware. So when the bearer auth token comes in the request the isolated functions are automatically authorized for use or not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.