- Print
- DarkLight
- PDF
Authorizing User Requests in Azure Functions with Azure Active Directory
- Print
- DarkLight
- PDF
You can use HTTP-triggered Azure Functions to build APIs and secure them with Azure Active Directory so that only authenticated and authorized users can operate on them.
In this article, you will learn to integrate Azure AD with Azure Functions and read user claims issued by the AD. You can use the claims to implement claims-based authorization in Azure Functions per your requirements.
Creating the Azure Function
Use the following Azure CLI commands to create an Azure Function app. Remember to replace the resource names with the names you desire:
az group create --name <resource group> --location eastus
az storage account create --name <storage account> --location eastus --resource-group <resource group> --sku "Standard_LRS"
az functionapp create –name <function app> --storage-account <storage account> --consumption-plan-location "eastus" --resource-group <resource group> --functions-version 4 --os-type Windows
Create an HTTP-triggered function in the app with the following settings:
Replace the code generated by default for the function with the following code listing:
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using System.Security.Claims;
using System.Text;
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
var sb = new StringBuilder();
var identity = req.HttpContext?.User?.Identity as ClaimsIdentity;
sb.AppendLine($"IsAuthenticated: {identity?.IsAuthenticated}");
sb.AppendLine($"Identity name: {identity?.Name}");
sb.AppendLine($"AuthenticationType: {identity?.AuthenticationType}");
foreach (var claim in identity?.Claims)
{
sb.AppendLine($"Claim: {claim.Type} : {claim.Value}");
}
return new OkObjectResult(sb.ToString());
}
The previous code segment reads the claims sent by the Identity Provider and returns them as the response to the request. You can use the claims to implement custom authorization rules, such as allowing only the employees to receive a valid response from the function.
Integrating Azure Function with Azure Active Directory
On your Function App, click Authentication. Click Add provider to initiate the process of adding a new identity provider.
Select Microsoft from the list of identity providers. Select Create new app registration to create a new application for the function in Azure AD. We will restrict the application user base to those registered in Azure AD by setting the account type to Current tenant – Single tenant. Configure the rest of the settings and click Add to complete the process.
Testing the Function
Copy the URL of the function from the Code + Test console as follows:
Use a different browser (or private browser instance) to visit the URL. Following is a quick demo of the process from my setup: