Is it possible to script the configuration of Azure App Service Authentication?

Viewed 3808

Azure App Service includes a turnkey authentication solution, under the Authentication/Authorization settings blade. This allowed me to configure Active Directory authentication for my App Service web api. I have a provisioning script for setting up my environment and I would like to automate the configuration of App Service Authentication, either through an ARM template or through Powershell commands.

I've tried using resource.azure.com to view the setup of my site but I couldn't see AD-related config. I've tried searching for ARM templates that do this, without success. I also couldn't see an Azure Resource Manager commandlet that could do this.

Does anyone know how to automate the configuration of App Service Authentication, specifically for AD authentication?

3 Answers

Edit 2020/06: I found getting a basic example of this working to be unreasonably arcane. Here is a detailed way to get a WebApp to use Azure AD for authentication


Ref: az ad app create / az ad app permission / az webapp auth update

Step 1: Define some basic variables

RSGROUP="MyResourceGroup"
webappname="MyWebSite"

WebAppFDQN=$(az webapp show --name "$webappname" -g "$RSGROUP" --query "defaultHostName" --out tsv);
prodURL="https://myapp.customdomainblah.com";
AADsuffix="/.auth/login/aad/callback" # AD Online is hardcoded to redirect to this path!!
urls="https://${WebAppFDQN}${AADsuffix} ${prodURL}${AADsuffix}";

AADappName="$webappname"

Step 2 - Create Azure Active Directory (AAD) App Registration

az ad app create \
  --display-name "$AADappName" \
  --homepage="https://${WebAppFDQN}" \
  --reply-urls $urls \
  --oauth2-allow-implicit-flow true

Step 3 - Add AD App Permissions

Microsoft Graph API w/ Read permission appears to be required.

AADappId=$(az ad app list --display-name "$AADappName" --query [].appId -o tsv);
MSGraphAPI="00000003-0000-0000-c000-000000000000" #UID of Microsoft Graph
Permission="e1fe6dd8-ba31-4d61-89e7-88639da4683d=Scope" # ID: Read permission, Type: Scope

az ad app permission add \
 --id "$AADappId" \
 --api "$MSGraphAPI" --api-permissions "$Permission"

# Appears to be safe to ignore resulting warning: 
#  "Invoking "az ad app permission grant --id $AADappId --api $MSGraphAPI" is needed to make the change effective"

Step 4 - Web: Enable Authentication

Appears idempotent (safe to execute during every deploy)

az webapp auth update \
  -g "$RSGROUP" -n "$webappname" --enabled true \
  --action LoginWithAzureActiveDirectory \
  --aad-client-id "$AADappId"

Previous answer:

This is now merged into Azure CLI and is available under az webapp auth.

{EDIT: Snipped documentation that was mostly useless - can be seen here: az webapp auth}

Related