How To Secure Azure Function With Azure AD

How To Secure Azure Function With Azure AD

In this Azure tutorial, we will discuss How To Secure Azure Function With Azure AD. Along with this, we will also discuss a few other topics like Securing an Azure Function App with Azure AD, Azure Functions Security Best Practices, and along with this we also discussed Azure AD Reply URL.

How To Secure Azure Function With Azure AD? We need to perform the below steps to secure Azure Function with Azure AD

  • Register the Azure AD App in the Azure Portal
  • Create The Azure Function (Target)
  • Enable Active Directory authentication for Azure function
  • Create The Azure Function (Caller)

How To Secure Azure Function With Azure AD

It’s not at all a good idea to give the Azure Function always Anonymous access in real-time scenarios. So we should implement the authentication for the Azure Function and should secure Azure Function With Azure AD Since Azure Active Directory is one of the excellent options for securing Azure Function.

Securing an Azure Function App with Azure AD

Well, let’s start the Azure AD configuration for the Azure Function. Instead of the Anonymous access, We will implement the login with the Azure Active Directory while accessing.

Register the Azure AD App in the Azure Portal

To register the Azure AD App in the Azure Portal, you can follow the below steps.

Sign in to the Azure Portal(https://portal.azure.com/)

Once Logged in Successfully, search for the Azure Active Directory

Secure Azure Function With Azure AD

Or, for the same option, you can click on the Azure Active Directory from the left side menu on the Home page

How To Secure Azure Function With Azure AD

Now click on the Azure Active Directory link, On the Azure Active Directory page, click on the App registrations link from the left navigation, and then click on the + New registration button.

Securing Azure Function With Azure AD

On the Register an application page, Fill out the below details

  • Name: Provide a name for this application.
  • Supported account types: Select the first option for Who can use this application or access this API.
  • Then select the Web option and then provide the URI where the access token will send.
Register the Azure AD App in the Azure Portal

The Redirect URI should be like

https://mytargetazurefunctionapp.azurewebsites.net

Where MyTargetAzureFunctionApp is my Target Function App name

Now click on the Register button.

You can able to see the MySecureApp is created successfully. Make the note of Application (client) ID that we are going to use later.

Securing Function App with Azure Active Directory authentication

Create The Azure Function (Target)

Login to the Azure Portal (https://portal.azure.com/)

Step-2: On the Home page, click on the + Create a resource and from the Home page, click on “Compute”. Now, choose the “Function App”.

How To Create Azure Function Apps In The Azure Portal

For the next step, you can follow the section, How To Create Azure Function Apps In The Azure Portal of my article How To Create Azure Functions In Visual Studio and create the Target Function App.

Now My Azure Function App is created sucessfully

Secure Azure function with Azure Active Directory

Now let’s add the Function, Click on the Functions from left side navigation and then click on the +Add button

Securing Azure Functions

Choose the HTTP trigger as the template and then Provide a name for the Azure Function, choose the authorization level, and then click on the Create Function button to create the Azure function. Now My Azure Function is created successfully without any issue.

Configure your App Service or Azure Functions app to use Azure AD login

Below is the code for my Azure Function that I have created just now.

Configure your Azure Functions app to use Azure AD login

How To Enable AD Authentication For Azure Function

Now we have already created the Azure AD App and Azure Function App, next the time to enable the AD authentication for the Azure Function.

Follow the below steps to Enable the AD authentication

Navigate to the Azure Function app that I have created before. Click on the Authentication/Authorization from the left navigation, Choose the below Options

  • App Service Authentication: Enable the On option here.
  • Action to take when the request is not authenticated: select Log in with Azure Active Directory

Now click on the Azure Active Directory (Not Configured) Option

Secure a Function App with Azure Active Directory

Now on the Azure Active Directory Settings page, Select the Management mode as Express, Select the Existing AD App and then choose the Azure AD app that you have created above. Finally, click on the Ok button.

Authenticate an Azure Function with Azure Active Directory

Finally, click on the Save button to save the changes.

Authenticate an Azure Function with Azure AD

How To Call Secured Function App 

Now register another app with the Azure Active Directory. This will be your Caller Azure AD App. Initially, we have created the Azure AD App, On the same way, you can create the Azure AD App.

Below is the Azure AD App that i have created, Copy the Application (client) ID.

Azure AD authentication in Azure Functions

The main reason behind this app is it will be used to get the token. So let’s create a secret for this AD app.

Click on the Certificates & Secrets from the left navigation and then click on the + New Client Secret.

Securing Azure Function

On the Add a client secret window, Provide a description, Choose In 1 year as the Expires option, and then click on the Add button.

Securing an Azure Function App with Azure AD

Make sure to copy the secret ID as highlighted below. Because you will not get that later.

How to Authenticate and Authorize Azure Function with Azure AD

Creation Of The Azure Function App (Caller)

Now the next step is, create another Azure Function App that will act like the Caller Azure Function App, You can follow the same steps on how we have created the Target Azure Function App above.

Now you can see below, I have created my Azure Function App

How to secure Azure Function with Azure Active Directory 1

Click on the Configurations from the left navigation and click on the Application settings tab. Now add all the application settings one by one by clicking on the + New application setting to add one by one

Basically, here, in this Azure function, we are going to call the above-created Target function, since it is secured with Azure AD. So first we need to get an access token, and to request the access token, we need all the below application settings

How Do I secure my Azure Function with Azure AD

Set all the below settings value by clicking on the + Add Application Settings button. One i will show you For AudienceID.

AudienceID: Provide the name as AudienceID and Target AD App’s Application (client) ID that you copied earlier and click the Ok button then click on the Save Button to apply the changes.

AzureAD authentication

Same way you add for all below app settings

  • ClientID: Use the Application (client) ID for the Caller AD app (MyCallerADApp) in my case that you created above.
  • ClientSecret: Use the Secret ID that you copied for the Caller AD app after configuring the client secret.
  • TargetURL: This is the Redirect URI that you mentioned while creating the target AD app (MySecureApp in my case).
  • TenantID: Click on the Azure Active Directory from the left navigation on the home page or search for the Azure Active Directory and click on that, you can able to see the Tenant ID under the Tenant information section.

Don’t forget to click on the Save button after adding each one. Now your application settings section should look like below.

Enable authentication on Azure Function

Now The next step is, we will create the caller function using the Visual Studio 2019.

Open the Visual Studio 2019, click on the Create New Project button.

On the Configure New Project window, Provide a Project name, Choose a location where you want to save your project, and then click on the Create button.

On the Create a new Azure Functions Application window, choose the Http trigger, the Storage Account as the Storage Emulator, and Authorization level as Function. Finally, click on the Create button to create the Azure Function project.

Now you can able to see below, My Azure Function Project created successfully.

Steps to secure Azure function with Azure Active Directory

Now Add the below Nuget package to the Azure Function Project.

Microsoft.IdentityModel.Clients.ActiveDirectory

Right click on the Project —> click on the Manage Nuget Packages

Search for the Microsoft.IdentityModel.Clients.ActiveDirectory and then select that package and click on the Install button to install the package.

How to Authenticate Azure Function with Azure AD

Now click on the I Accept button to accept the License.

Now Add this code to you Function

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Net.Http;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Text;

namespace MyCallerFunction
{
    public static class Function1
    {

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

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            HttpResponseMessage Tgtresponse = UpdateMessage(requestBody);
            return Tgtresponse != null
                ? (ActionResult)new OkObjectResult($"Hello, {Tgtresponse.Content.ReadAsStringAsync().Result}")
                : new BadRequestObjectResult("Pass name on the query string or in the request body");
        }
        public static HttpResponseMessage UpdateMessage(string body)
        {
            HttpResponseMessage newresponse;
            AuthenticationContext authContext = new AuthenticationContext("https://login.microsoftonline.com/" + Environment.GetEnvironmentVariable("TenantID"));
            ClientCredential clntCred = new ClientCredential(Environment.GetEnvironmentVariable("ClientID"), Environment.GetEnvironmentVariable("ClientSecret"));
            AuthenticationResult authRes = authContext.AcquireTokenAsync(Environment.GetEnvironmentVariable("AudienceID"), clntCred).Result;

            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authRes.AccessToken);
                var cnt = new StringContent(body, Encoding.UTF8, "application/json");
                newresponse = httpClient.PostAsync(Environment.GetEnvironmentVariable("TargetURL"), cnt).Result;
            }
            return newresponse;
        }

    }
}
How to Authenticate and Authorize Azure Function with Azure Web App Using Managed Service Identity

On the above code, we have used AuthenticationContext that will help to get the Azure Access token.

You need to add the application settings values in your local.settings.json file

{
    "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",
    "TenantID": "5d9d690a-0310-474d-ae8b-############",
    "ClientID": "8dd5dd1a-cf07-4df3-bf02-522067679212",
    "ClientSecret": "25Fbw-zf5T451Ke-QP5l7Pg1Tr_wG.UimW",
    "AudienceID": "c63889d3-d0b5-4d7c-9060-b86e9e215da5",
    "TargetURL": "https://mytargetazurefunctionapp.azurewebsites.net"

  }
}

Now right click on your Solution and Publish this to Azure

How To Secure Azure Function With AzureAD

Choose your Azure Function App while Publishing. Now You are done !!!

How To Secure Azure Function With AzureActiveDirectory

Azure Functions Security Best Practices

Well, here we will discuss a very important topic i.e What are the Best Practices in the case of Azure Functions Security that we need to follow while working with the Azure Functions. Below are a few key Best Practices that we need to keep in mind as part of the Security for the Azure Functions.

1- Validate Azure Function Input Properly

Make sure to validate the Azure Function Properly. Do not assume something for the Input parameters. You should use some trusted APIs if possible to validate the Azure Function Inputs.

Avoid untrusted inputs for your Azure Function. Follow all the coding standards Properly while writing the code for your Azure Function. While working with the Azure Function, you need to interact with many sources like Queue Storage, CosmosDB, NoSQL DB, etc, Just make sure to validate the Sources properly before using them.

2- Minimize Excessive Permissions

Do not use more permissions that are actually not needed and will be the reason of risk for your Azure Function. Only assign the Permission for the Azure Function So that the Azure Function can execute Successfully. Before assigning the permissions, analyze properly, and assign the exact permission that is actually needed.

You can use the Azure role-based access control (RABC) to assign the permissions to a specific user or group. You can also use the SAS token service from Microsoft to give the needed access to the Azure Resources.

3- Do not Disclose Your Azure Function Secrets

As you are working with the Azure Functions, many times you need to use the Azure Function Secrets. As the name suggests, Keep the Azure Function secret Properly.

You can use the Microsoft CredScan tool to analyze the Credential leaks if any. One more thing is you can use Key Vault that helps for these scenarios to manage the encrypted keys.

Azure AD Reply URL

Azure AD Reply URL is also known as the Azure AD Redirect URI. This is the place where the server sends the user after the app has been authorized successfully and granted an access token.

Rules Needs To Follow For The Azure AD Reply URL

There are different rules you need to follow while deciding for Azure AD Reply URL. Blow are few among them.

  • The Azure AD Reply URL must start with https.
  • The Azure AD Reply URL is case sensitive in nature. It must match with the Running application URL case.
  • The maximum number of characters you can use in the Azure AD URL is 256.
  • You should avoid wild card URLs, for example, https://*.tsinfo.com.
  • The maximum number of URLs allowed in the case of Organizations’ Azure AD tenant is 256 But in the case of personal accounts, it is 100 maximum.

Where To Set Azure AD Reply URL

Follow the below steps to set the Azure AD Reply URL

Login to the Azure Portal

Search for the Azure Active Directory and click on the search result Azure Active Directory

Where To Set Azure AD Reply URL

On the Default Directory page, click on the App registrations from the left navigation and then click on the + New registrations button as highlighted below.

Azure AD Reply URL

You can set the Azure Redirect URI as highlighted below.

Where To Set Azure AD Redirect URI

Azure AD Multiple Reply URLs

You can also able to add Multiple Azure AD URLs.

Once You click on the Register your Azure AD App will be created successfully.

Now navigate to the Azure AD App that you have created above, then click on the Authentication option from the left navigation then Under Redirect URI, click on the Add URL button as highlighted below to add multiple Redirect URI or Azure AD reply URLs.

Where To Set Azure AD  multiple Reply URLs

You may like following the below Articles

Wrapping Up

Well, in this article, we discussed, How To Secure Azure Function With Azure AD. We have created the Azure AD apps and the Azure Functions as needed to achieve the functionality. Finally, we have written the Azure Function code in Visual Studio 2019 and published that to Azure from the Visual Studio 2019, Along with this we also discussed Securing an Azure Function App with Azure AD, Azure Functions Security Best Practices, and Azure AD Reply URL. Hope you have enjoyed this article !!!

Leave a Comment