Home > Software design >  How to protect an Azure Function with System assigned Managed Identity
How to protect an Azure Function with System assigned Managed Identity

Time:11-15

I have a simple azure function (Authorization level set to Anonymous) with an HTTP trigger

public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
    return new OkObjectResult("This is a response from secured function.");
}

I want to secure it with Managed Identities, so I turned on system-assigned identity enter image description here

And in my AD enterprise app registration, I can see created a system-assigned identity so I copied its Application ID value enter image description here

and for testing purposes, I want to trigger it from another azure function

public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
{
    var clientID = {application / client ID of system identity}
    var azureServiceTokenProvider = new  AzureServiceTokenProvider();
    var accessToken = await azureServiceTokenProvider.GetAccessTokenAsync(clientID);
    
    // Call secured azure function
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("https://my-secured-function.azurewebsites.net");
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

        var response = await client.GetAsync("/api/HttpTrigger1");
        if (response.IsSuccessStatusCode)
        {
            var result = await response.Content.ReadAsStringAsync();

            return new OkObjectResult(result);
        }
        else
        {
            return new OkObjectResult("Error - "   response.StatusCode);
        }
    }
}

The code works, it generates & sends a token within the HTTP request. However, the "secured" azure function is still publicly available.

The question is how can I protect the "secured" azure function, so it can be triggered only with an HTTP request with a generated token using managed identities.

CodePudding user response:

The System Assigned Managed Identity you enabled here only gives an identity to your app, through a Service Principal. This is not blocking any access unlike the Firewall/IP Restrictions (that you could use but I assume that you want to rely on Identity only here).

What you are looking for is basically enter image description here

Add the necessary settings(you can let Azure create an App registration or use the managed identity which you have already created. With this step, you will lock your Azure function app so it is triggered only if a valid AD token is provided to it.

  • Related