Skip to content

12 / 13Containers and serverless

Azure App Service security hardening

Harden Azure App Service: HTTPS and TLS, basic auth and FTP off, access restrictions, private endpoints, Key Vault references, logging and dangling DNS.

Service
App Service
Category
Containers and serverless
Baseline
12 controls
Updated
Published on 13 min read
On this page

Azure App Service hosts web apps, APIs and (through the same Microsoft.Web/sites resource type) function apps and Logic Apps Standard. Microsoft patches the operating system and runtime hosts, but almost every setting that decides how exposed an app is stays with you, and several defaults favour convenience: a new app is reachable from the whole internet, its Kudu (SCM) deployment site and FTP endpoint accept username and password publishing credentials, and anything you put in application settings is readable by everyone with Contributor on the app. The incident patterns are well documented: leaked publishing profiles used to push web shells (MITRE ATT&CK T1505.003), secrets harvested from app settings after a control plane compromise, staging slots left wide open while production sits behind a WAF, and subdomain takeovers through CNAME records that still point at a deleted *.azurewebsites.net app. This page maps to the Microsoft cloud security benchmark (MCSB) security baseline for App Service and to the App Service section of the CIS Microsoft Azure Compute Services Benchmark.

Baseline controls

Plain CIS numbers refer to the CIS Microsoft Azure Foundations Benchmark v7.0.0; numbers marked Compute refer to the CIS Microsoft Azure Compute Services Benchmark v2.0.1.

ControlWhyHow to checkID
HTTPS only and minimum TLS 1.2No cleartext traffic, no legacy TLSaz webapp show --query httpsOnly, az webapp config show --query minTlsVersionMCSB DP-3 / CIS Azure Compute 2.0.1 2.1.7, 2.1.8
Basic auth publishing credentials off, FTP disabledStatic deployment passwords bypass Entra ID and MFAaz resource show ... basicPublishingCredentialsPolicies/scmMCSB IM-1 / CIS Compute 2.1.4, 2.1.5
Restrict inbound network accessOnly the WAF or private network reaches the appaz webapp config access-restriction showMCSB NS-2 / CIS Compute 2.1.14, 2.1.16
Lock down the SCM siteKudu can deploy and run codescmIpSecurityRestrictions in access restriction outputMCSB NS-2
Managed identity and Key Vault referencesNo secrets in app settingsaz webapp config appsettings listMCSB IM-3, MCSB IM-8 / CIS Compute 2.1.13, 2.5
App Service Authentication with Entra IDPlatform-enforced sign-in before code runsaz webapp auth showMCSB IM-1 / CIS Compute 2.1.12
Remote debugging offOpens extra ports and a debug channelaz webapp config show --query remoteDebuggingEnabledMCSB PV-2 / CIS Compute 2.1.10
Supported runtime versionsEnd-of-life stacks stop receiving fixesaz webapp config show --query linuxFxVersionCIS Compute 2.1.1, 2.1.2, 2.1.3
Slot settings hygieneSlots are separate sites with their own exposureaz webapp deployment slot listCIS Compute 2.2.1 to 2.2.17
Unique default hostnames, no dangling CNAMEsPrevents subdomain takeoverDNS inventory against az webapp list-
Defender for App ServiceDetects web shells, scanners, dangling DNSaz security pricing show -n AppServicesMCSB LT-1 / CIS 8.1.6.1
Diagnostic logs to Log AnalyticsEvidence for FTP, Kudu and HTTP activityaz monitor diagnostic-settings list --resource <app-id>MCSB LT-4 / CIS 6.1.4, CIS Compute 2.11

HTTPS only and minimum TLS

App Service accepts plain HTTP by default. Turn on HTTPS Only so every HTTP request is redirected, and set the minimum inbound TLS version to 1.2 (or 1.3 when all your clients support it). The SCM site has its own minimum TLS setting, so set both.

bash
az webapp update -g rg-web -n app-contoso --https-only true
az webapp config set -g rg-web -n app-contoso \
  --min-tls-version 1.2 --http20-enabled true

Portal: App Service > Settings > Configuration > General settings (HTTPS Only, Minimum Inbound TLS Version, SCM Minimum Inbound TLS Version).

In Bicep, set everything in one place so a redeployment cannot regress it:

Bicep
resource app 'Microsoft.Web/sites@2024-04-01' = {
  name: 'app-contoso'
  location: location
  identity: { type: 'SystemAssigned' }
  properties: {
    serverFarmId: plan.id
    httpsOnly: true
    publicNetworkAccess: 'Disabled'
    autoGeneratedDomainNameLabelScope: 'TenantReuse'
    siteConfig: {
      minTlsVersion: '1.2'
      scmMinTlsVersion: '1.2'
      ftpsState: 'Disabled'
      remoteDebuggingEnabled: false
      http20Enabled: true
    }
  }
}

Verify across subscriptions with Resource Graph:

KQL
resources
| where type =~ "microsoft.web/sites"
| project name, kind, resourceGroup,
          httpsOnly = tobool(properties.httpsOnly),
          publicNetworkAccess = tostring(properties.publicNetworkAccess)
| where httpsOnly != true or publicNetworkAccess != "Disabled"

Enforce with the built-in policies App Service apps should only be accessible over HTTPS (Audit or Deny) and App Service apps should use the latest TLS version, or remediate existing apps with Configure App Service apps to only be accessible over HTTPS and Configure App Service apps to use the latest TLS version (DeployIfNotExists/Modify). Each has a separate "app slots" variant; assign both.

Basic auth publishing credentials and FTP

Every app has app-scope publishing credentials ($app-contoso plus a generated password) and every user can set user-scope deployment credentials. They work against FTP, Web Deploy and the Kudu Git endpoint, they are not covered by Conditional Access or MFA, and anyone with Contributor can download them in a publishing profile. Disable both basic auth surfaces and the FTP endpoint itself:

bash
APP_ID=$(az webapp show -g rg-web -n app-contoso --query id -o tsv)

for p in ftp scm; do
  az resource update --resource-group rg-web --name $p \
    --namespace Microsoft.Web --resource-type basicPublishingCredentialsPolicies \
    --parent sites/app-contoso --set properties.allow=false
done

az webapp config set -g rg-web -n app-contoso --ftps-state Disabled

Portal: Configuration > General settings > SCM Basic Auth Publishing Credentials and FTP Basic Auth Publishing Credentials, both Off. In Bicep, declare the child resources Microsoft.Web/sites/basicPublishingCredentialsPolicies named ftp and scm with allow: false.

Deployments then authenticate with Entra ID: Azure CLI 2.48.1 or later (az webapp deploy), Azure Pipelines with the AzureWebApp task, and GitHub Actions with OpenID Connect and a user-assigned identity all keep working. FTP and local Git do not.

To stop lower-privileged users from switching basic auth back on, put Microsoft.Web/sites/basicPublishingCredentialsPolicies/Write and Microsoft.Web/sites/slots/basicPublishingCredentialsPolicies/Write in the NotActions of the custom role you give app teams (see RBAC).

Enforce with App Service apps should have local authentication methods disabled for FTP deployments and App Service apps should have local authentication methods disabled for SCM site deployments, remediated by Configure App Service apps to disable local authentication for FTP deployments and Configure App Service apps to disable local authentication for SCM sites. Add App Service apps should require FTPS only for any app where you cannot yet disable FTP.

Network access: access restrictions and private endpoints

A new app answers on *.azurewebsites.net from anywhere. Choose one of two patterns:

  • Public app behind a WAF. Azure Front Door or Application Gateway with WAF in prevention mode, and access restrictions on the app that only allow the front door. For Front Door, allow the AzureFrontDoor.Backend service tag and check the X-Azure-FDID header, otherwise any other customer's Front Door profile can reach your app.
  • Private app. A private endpoint (group ID sites) in your VNet, the privatelink.azurewebsites.net private DNS zone, and public network access disabled.
bash
# Pattern 1: only your Front Door profile
az webapp config access-restriction add -g rg-web -n app-contoso \
  --rule-name afd-only --action Allow --priority 100 \
  --service-tag AzureFrontDoor.Backend \
  --http-headers x-azure-fdid=<front-door-profile-id>
az webapp config access-restriction set -g rg-web -n app-contoso --default-action Deny

# Pattern 2: private endpoint and no public access
az network private-endpoint create -g rg-web -n pe-app-contoso \
  --vnet-name vnet-spoke --subnet snet-pe \
  --private-connection-resource-id $APP_ID --group-id sites \
  --connection-name app-contoso
az resource update --ids $APP_ID --set properties.publicNetworkAccess=Disabled

Private endpoints only cover inbound traffic. For outbound calls to databases, Key Vault and storage, use VNet integration with --vnet-route-all-enabled true so egress passes through NSGs, route tables and your firewall (see Virtual Network).

Enforce with App Service apps should disable public network access (Audit or Deny), App Service apps should use private link, and the remediation policy Configure App Service apps to disable public network access.

SCM site restrictions

The SCM site (app-contoso.scm.azurewebsites.net) runs Kudu: file browser, console, process explorer, deployment APIs. With access restrictions on the main site only, the SCM site stays open to the internet. Either make it inherit the main site rules, or give it its own, tighter list (build agents, a jump subnet):

bash
# Option A: same rules as the main site
az webapp config access-restriction set -g rg-web -n app-contoso \
  --use-same-restrictions-for-scm-site true

# Option B: separate rules, deny by default
az webapp config access-restriction set -g rg-web -n app-contoso \
  --use-same-restrictions-for-scm-site false --scm-default-action Deny
az webapp config access-restriction add -g rg-web -n app-contoso \
  --rule-name build-agents --action Allow --priority 100 \
  --vnet-name vnet-devops --subnet snet-agents --scm-site true

A private endpoint covers both the app and its SCM hostname. Access to Kudu with Entra ID is controlled by Azure RBAC on Microsoft.Web/sites/publish/Action, which Website Contributor and Contributor include, so treat those roles as code execution rights on the app.

Managed identity and Key Vault references

Application settings and connection strings are encrypted at rest, but they are returned in clear to anyone who can call config/list on the app, and they end up in deployment templates and pipeline logs. Use a managed identity to reach Azure services directly (SQL, Storage, Service Bus, Cosmos DB with Entra authentication), and keep the remaining third-party secrets in Key Vault, referenced from app settings:

bash
az webapp identity assign -g rg-web -n app-contoso
PRINCIPAL=$(az webapp identity show -g rg-web -n app-contoso --query principalId -o tsv)

az role assignment create --assignee-object-id $PRINCIPAL \
  --assignee-principal-type ServicePrincipal \
  --role "Key Vault Secrets User" \
  --scope $(az keyvault show -n kv-contoso --query id -o tsv)

az webapp config appsettings set -g rg-web -n app-contoso --settings \
  "PaymentApiKey=@Microsoft.KeyVault(VaultName=kv-contoso;SecretName=payment-api-key)"

When the app has several identities, set the one used for references explicitly with az webapp update -g rg-web -n app-contoso --set keyVaultReferenceIdentity=<user-assigned-identity-id>. If the vault has public access disabled, the app needs VNet integration to resolve and reach the vault's private endpoint. Vault hardening (RBAC mode, purge protection, private endpoints) is on the Key Vault page; role scoping for identities is on Azure RBAC.

Find secrets left in plain text by listing settings whose values do not start with @Microsoft.KeyVault(:

bash
az webapp config appsettings list -g rg-web -n app-contoso \
  --query "[?!starts_with(value, '@Microsoft.KeyVault(')].name" -o tsv

Audit identity adoption with App Service apps should use managed identity.

App Service Authentication

App Service Authentication (often called Easy Auth) runs as a module in front of your code and rejects unauthenticated requests before they reach the application. For internal apps, configure the Microsoft identity provider with your Entra tenant, and return 401 instead of allowing anonymous access:

bash
az webapp auth microsoft update -g rg-web -n app-contoso \
  --client-id <app-registration-client-id> \
  --issuer https://login.microsoftonline.com/<tenant-id>/v2.0

az webapp auth update -g rg-web -n app-contoso --enabled true \
  --unauthenticated-client-action Return401 --require-https true

Points that matter:

  • Restrict who can sign in by setting Assignment required on the enterprise application and assigning groups, otherwise every user in the tenant gets a token. Apply Conditional Access to the app.
  • Use a federated identity credential or a certificate on the app registration rather than a client secret stored in an app setting. If you must use a secret, store it as a Key Vault reference.
  • Keep --excluded-paths to health probes only.
  • Authorization (roles, group claims) is still your code's job; Easy Auth only proves who the caller is.

Remote debugging off

Remote debugging opens additional ports and a debugging channel into the worker. It is meant for short sessions and should never be on in production.

bash
az webapp config set -g rg-web -n app-contoso --remote-debugging-enabled false

Enforce with App Service apps should have remote debugging turned off (Audit or Deny) and remediate with Configure App Service apps to turn off remote debugging.

Current runtime versions

Microsoft keeps the platform patched, but language runtimes that reach end of support (old Node.js, PHP, Python, .NET or Java versions) stop receiving security fixes, and the app keeps running on them until you change the stack. Check what each app runs and compare it with the App Service language support policy:

bash
az webapp list-runtimes --os linux -o table
az webapp config show -g rg-web -n app-contoso \
  --query "{linux:linuxFxVersion, net:netFrameworkVersion, java:javaVersion, php:phpVersion}"

Built-in policies such as App Service apps that use Python should use a specified 'Python version', the matching Java and PHP variants, and App Service apps should use latest 'HTTP Version' let you audit at scale. For custom containers, the runtime is in your image: scan it in your registry and rebuild on a schedule (see Defender for Cloud).

Deployment slot hygiene

Each deployment slot is a separate site with its own hostname, SCM site, access restrictions, identity and diagnostic settings. Hardening applied to production does not flow to slots, and slots are where test code, debug flags and verbose errors live.

  • Apply the same settings to every slot: --slot staging works on az webapp update, az webapp config set and az webapp config access-restriction, and the built-in policies above all have "App Service app slots" variants.
  • Mark environment-specific values as slot settings so they do not move during a swap: az webapp config appsettings set -g rg-web -n app-contoso --slot staging --slot-settings "ENVIRONMENT=staging". Otherwise a swap can carry a staging connection string into production, or a production secret into a less protected slot.
  • Each slot has its own system-assigned identity. Grant it access only to non-production resources.
  • Delete slots you no longer use. A forgotten slot keeps its hostname, its publishing credentials (unless disabled) and an old build.
bash
az webapp deployment slot list -g rg-web -n app-contoso --query "[].name" -o tsv

Subdomain takeover and dangling DNS

When you delete an app but leave shop.contoso.com CNAME app-contoso.azurewebsites.net in DNS, anyone who creates an app with the same name can serve content on your subdomain, harvest cookies scoped to your parent domain and run convincing phishing. App Service blocks reuse of a deleted name for a while outside your tenant, but that is not a substitute for DNS hygiene. Three layers:

  1. Secure unique default hostnames. New apps get a hostname such as app-contoso-<hash>.<region>.azurewebsites.net that nobody outside your tenant (or scope) can recreate. The portal uses it by default for new apps; CLI, ARM and Bicep deployments must opt in at creation time with --domain-name-scope TenantReuse or autoGeneratedDomainNameLabelScope. Existing apps need a clone or restore to a new app.
  2. Domain verification records. Create the asuid.<subdomain> TXT record with your app's custom domain verification ID. Without a matching token, another subscription cannot bind your hostname.
  3. Delete DNS first. Remove the CNAME before you delete the app, and run a periodic comparison of DNS records pointing to azurewebsites.net against existing apps.
bash
az webapp create -g rg-web -p plan-web -n app-contoso \
  --runtime "DOTNETCORE:8.0" --domain-name-scope TenantReuse

Defender for App Service

Microsoft Defender for App Service monitors the App Service plan instances, the requests to your apps and platform logs. It detects vulnerability scanners, connections from known malicious IPs to the FTP interface, suspicious process execution, web shells and dangling DNS entries when an app is decommissioned with its custom domain still in DNS. It is billed per App Service plan instance.

bash
az security pricing create -n AppServices --tier Standard
az security pricing show -n AppServices --query pricingTier

Enable it at subscription scope through Defender for Cloud, ideally enforced by the Defender plan DeployIfNotExists policies from a management group. Turn on diagnostic logs (next section) as well: Defender alerts are much easier to investigate with HTTP and audit logs available.

Logging and detection

Send resource logs from every app and slot to a central Log Analytics workspace with a diagnostic setting. The security-relevant categories are:

CategoryContains
AppServiceHTTPLogsWeb server requests: client IP, URI, status, user agent
AppServiceAuditLogsSign-ins to FTP and Kudu/Web Deploy, with protocol and source IP
AppServiceIPSecAuditLogsRequests evaluated by access restriction rules
AppServiceAuthenticationLogsApp Service Authentication module events
AppServicePlatformLogsContainer lifecycle operations
AppServiceConsoleLogs, AppServiceAppLogsApplication output (useful context, high volume)
AppServiceFileAuditLogsFile changes in site content (Premium tier and above)
bash
az monitor diagnostic-settings create --name to-law --resource $APP_ID \
  --workspace <log-analytics-workspace-id> \
  --logs '[{"category":"AppServiceHTTPLogs","enabled":true},
           {"category":"AppServiceAuditLogs","enabled":true},
           {"category":"AppServiceIPSecAuditLogs","enabled":true},
           {"category":"AppServicePlatformLogs","enabled":true}]'

Enforce with App Service apps should have resource logs enabled or the DeployIfNotExists policy Enable logging by category group for App Service (microsoft.web/sites) to Log Analytics.

Alert on any basic auth login once you have disabled it (a hit means it was re-enabled, or a policy is missing on a slot):

KQL
AppServiceAuditLogs
| where TimeGenerated > ago(1d)
| project TimeGenerated, _ResourceId, OperationName, Protocol, User, UserAddress

Look for web shell patterns: script files requested on an app that does not serve them, or POSTs to new paths that return 200:

KQL
AppServiceHTTPLogs
| where TimeGenerated > ago(1d)
| where CsUriStem matches regex @"(?i)\.(aspx|ashx|php|jsp)$" and CsMethod == "POST"
| summarize Requests = count(), Clients = dcount(CIp) by _ResourceId, CsUriStem, ScStatus
| order by Requests desc

In the activity log, alert on changes to basic auth policy, publishing profile downloads and slot swaps:

KQL
AzureActivity
| where OperationNameValue in~ (
    "MICROSOFT.WEB/SITES/BASICPUBLISHINGCREDENTIALSPOLICIES/WRITE",
    "MICROSOFT.WEB/SITES/PUBLISHXML/ACTION",
    "MICROSOFT.WEB/SITES/SLOTSSWAP/ACTION")
| project TimeGenerated, Caller, CallerIpAddress, OperationNameValue, _ResourceId

Workspace design, retention and activity log export are covered on the Azure Monitor page.

Common mistakes

  • Access restrictions on the main site only. The SCM site stays reachable from the internet, so anyone with a leaked publishing password or a Contributor token can deploy code through Kudu.
  • Allowing the AzureFrontDoor.Backend service tag without the X-Azure-FDID header check. Every Front Door profile in Azure, including an attacker's, can then reach and bypass your WAF.
  • Private endpoint added, public network access left on. The app is reachable privately and still answers on its public hostname.
  • Hardening production and forgetting slots. Staging slots keep basic auth, remote debugging and no access restrictions, and a swap can carry their weaker settings into production.
  • Deleting an app before its CNAME. The subdomain becomes claimable and Defender only alerts after the fact, if it is enabled.
  • Secrets as plain app settings because "they are encrypted". Any Contributor, any pipeline with list permissions and any exported template sees them in clear.
  • Disabling basic auth but keeping a GitHub or Bitbucket deployment that depends on it. Deployments break, and the quick fix teams reach for is re-enabling basic auth instead of moving to OpenID Connect.

References

Filed under app-service, web-apps, paas, cis-benchmark

Written by

, Cloud Security Engineer & Editor

Security engineer writing practical hardening pages for Microsoft Azure tenants and subscriptions, aligned with the CIS Microsoft Azure Foundations Benchmark.

Related services

  1. Azure FunctionsHarden Azure Functions: access keys and Entra auth, master key exposure, identity-based storage, network isolation, Flex Consumption, CORS and logging.
  2. Virtual MachinesHarden Azure VMs: Trusted Launch, no public IPs, JIT and Bastion access, Entra ID login, encryption at host, Update Manager patching and Defender for Servers.
  3. Virtual NetworkHarden Azure Virtual Network: NSGs without internet management ports, private subnets, Azure Firewall egress, private endpoints, DDoS, Bastion, flow logs.