An Azure Developer CLI (azd) template using Bicep that demonstrates how to call OAuth-Protected APIs on Azure API Management (APIM) from Azure Functions and Logic Apps using managed identity authentication with OAuth.
It also shows how one APIM API can securely call another APIM API using its managed identity, enabling secret-free, secure authentication between Azure services.
Additionally, the repository includes CI/CD pipelines that demonstrate how to call OAuth-protected APIs from a CI/CD pipeline using federated credentials.
This template deploys the following resources:
-
Azure API Management service with two APIs:
- Protected API: A backend API that's protected with OAuth
- Unprotected API: A public API that calls the protected API using the system-assigned managed identity of API Management
-
Azure Function App: A .NET 10 function that calls the protected API using the system-assigned managed identity of the Function App
-
Azure Logic App (Standard): A workflow that calls the protected API using the system-assigned managed identity of the Logic App
-
Supporting resources: Application Insights, Log Analytics workspace, Storage Account, and Entra ID app registrations
The template demonstrates how to authenticate between Azure services using managed identities instead of client secrets or certificates. This approach provides better security and eliminates the need to manage and rotate secrets. Supported scenarios include:
- Call OAuth-Protected APIs with Managed Identity from API Management
- Call OAuth-Protected APIs with Managed Identity from Azure Functions (.NET)
- Call OAuth-Protected APIs with Managed Identity from Logic Apps
If you can't use a managed identity, have a look at Call API Management backend with OAuth instead.
Important
This template is not production-ready; it uses minimal cost SKUs and omits network isolation, advanced security, governance and resiliency. Harden security, implement enterprise controls and/or replace modules with Azure Verified Modules before any production use.
This repository also includes CI/CD pipelines using GitHub Actions and Azure DevOps that automate the build, deployment, testing and cleanup process. These pipelines demonstrate how to call OAuth-protected APIs from a CI/CD pipeline using federated credentials, eliminating the need for secrets in your automation workflows.
Pipeline scenarios include:
- Call OAuth-Protected APIs from GitHub Actions Using Federated Credentials
- Call OAuth-Protected APIs from Azure DevOps Using Federated Credentials
See pipeline for more details.
Before you can deploy this template, make sure you have the following tools installed and the necessary permissions:
Required Tools:
- Azure Developer CLI (azd)
Installingazdalso installs the following tools: - .NET 10 SDK
- npm CLI (This template uses a workaround to deploy the Logic App workflow, which requires the npm CLI.)
- This template includes several hooks that run at different stages of the deployment process and require the following tools. For more details, see Hooks.
Required Permissions:
- You need Owner or Contributor permissions on an Azure Subscription to deploy this template
- You need Application Administrator or Cloud Application Administrator permissions to register the Entra ID app registrations (You already have enough permissions if 'Users can register applications' is enabled in your Entra tenant.)
Once the prerequisites are installed on your machine, you can deploy this template using the following steps:
-
Run the
azd initcommand in an empty directory with the--templateparameter to clone this template into the current directory.azd init --template ronaldbosma/call-apim-with-managed-identity
When prompted, specify the name of the environment (for example,
managedidentity). The maximum length is 32 characters. -
Run the
azd auth logincommand to authenticate to your Azure subscription using the Azure Developer CLI (if you haven't already).azd auth login
-
Run the
az logincommand to authenticate to your Azure subscription using the Azure CLI (if you haven't already). This is required for the hooks to function properly. Make sure to log into the same tenant as the Azure Developer CLI.az login
-
Run the
azd upcommand to provision the resources in your Azure subscription and Entra ID tenant. This deployment typically takes around 7 minutes to complete. (Useazd provisionto only deploy the infrastructure.)azd up
See Troubleshooting if you encounter any issues during deployment.
-
Once the deployment is complete, you can locally modify the application or infrastructure and run
azd upagain to update the resources in Azure.
The Demo Guide provides a step-by-step walkthrough on how to test and demonstrate the deployed resources.
Once you're done and want to clean up, run the azd down command. By including the --purge parameter, you ensure that the API Management service and Log Analytics workspace don't remain in a soft-deleted state, which could cause issues with future deployments of the same environment.
azd down --purgeBy default, this template allows API access for users by adding a scope to the API Management app registration. This is configured through the allowApiAccessForUsers parameter in main.parameters.json. The default is true.
To disable it, run the following command before deploying the template:
azd env set ALLOW_API_ACCESS_FOR_USERS=falseIn an enterprise environment (for tenants with Entra IDs enabled by Service Tree management), the ServiceManagementReference field on an application (app registration) is mandatory.
If you're deploying this template in such an environment, you can set this field through the serviceManagementReference parameter in main.parameters.json. The default is an empty string.
Use the following command to set a valid Service Management Reference ID before deploying the template:
azd env set AZURE_SERVICE_MANAGEMENT_REFERENCE <id>Replace <id> with the valid Service Tree ID.
If you don't provide a valid ID, the deployment will fail with the following error: Value for ServiceManagementReference must be a valid GUID.
The repository consists of the following files and directories:
├── .azdo
│ └── pipelines [ Azure DevOps pipeline(s) ]
├── .devcontainer [ Development container configuration files ]
├── .github
│ └── workflows [ GitHub Actions workflow(s) ]
├── .vscode [ Visual Studio Code configuration files ]
├── demos [ Demo guide(s) ]
├── hooks [ AZD Hooks to execute at different stages of the deployment process ]
├── images [ Images used in the README and demo guide ]
├── infra [ Infrastructure As Code files ]
│ ├── functions [ Bicep user-defined functions ]
│ ├── modules
│ │ ├── application [ Protected and unprotected APIs ]
│ │ ├── entra-id [ Modules for all Entra ID resources ]
│ │ └── services [ Modules for all Azure services ]
│ │ └── shared [ Shared modules ]
│ ├── types [ Bicep user-defined types ]
│ ├── main.bicep [ Main infrastructure file ]
│ └── main.parameters.json [ Parameters file ]
├── src
│ ├── functionApp [ Azure Function that calls the protected API ]
│ └── logicApp [ Logic App workflow that calls the protected API ]
├── tests
│ ├── IntegrationTests [ Integration tests for automatically verifying different scenarios ]
│ └── *.http [ HTTP request files for testing different scenarios ]
├── azure.yaml [ Describes the apps and types of Azure resources ]
└── bicepconfig.json [ Bicep configuration file ]
This template has several hooks that are executed at different stages of the deployment process. The following hooks are included:
These PowerShell scripts are executed before the resources are removed.
- predown-remove-app-registrations.ps1:
Removes the app registrations created during the deployment process, because
azddoesn't support deleting Entra ID resources yet. See the related GitHub issue: Azure/azure-dev#4724. The Entra ID resources have a custom tagazd-env-id: <environment-id>, so we can find and delete them.
This template includes a GitHub Actions workflow that automates the build, deployment and cleanup process. The workflow is defined in azure-dev.yml and provides a complete CI/CD pipeline for this template using the Azure Developer CLI.
The pipeline consists of the following jobs:
-
Build, Verify and Package: This job sets up the build environment, validates the Bicep template and packages the Function App, Logic App and integration tests.
-
Deploy to Azure: This job provisions the Azure infrastructure and deploys the packaged applications to the created resources.
-
Verify Deployment: This job runs automated integration tests on the deployed resources to verify correct functionality.
-
Clean Up Resources: This job removes all deployed Azure resources.
By default, cleanup runs automatically after the deployment. This can be disabled via an input parameter when the workflow is triggered manually.
For draft PRs, only the 'Build, Verify and Package' job is executed to avoid deploying from work-in-progress branches. When the PR is marked ready for review, the workflow will trigger and execute all jobs.
See GitHub Actions Workflow for Azure Developer CLI (azd) Templates for a detailed explanation of the workflow.
Note
An Azure DevOps pipeline is also included in .azdo/pipelines/azure-dev.yml that implements the same jobs as the GitHub Actions workflow.
To set up the pipeline in your own repository, run the following command (add --provider azdo if you want to create an Azure DevOps pipeline):
azd pipeline configFollow the instructions and choose Federated Service Principal (SP + OIDC), as OpenID Connect (OIDC) is the authentication method used by the pipeline, and only a service principal can be granted the necessary permissions in Entra ID.
After the service principal has been created:
- Add the Microsoft Graph permissions Application.ReadWrite.All, AppRoleAssignment.ReadWrite.All and DelegatedPermissionGrant.ReadWrite.All to the app registration of the service principal, and grant admin consent for these permissions. Use the application permissions type, not delegated permissions type. These permissions are necessary to deploy the Entra ID resources with the Microsoft Graph Bicep Extension.
- Assign the service principal either the Application Administrator or Cloud Application Administrator role if it's not already assigned. One of these roles is necessary for the hooks to successfully remove the Entra ID resources during cleanup.
For detailed guidance, refer to:
- Explore Azure Developer CLI support for CI/CD pipelines
- Create a GitHub Actions CI/CD pipeline using the Azure Developer CLI
or Create an Azure DevOps CI/CD pipeline using the Azure Developer CLI
Tip
By default, AZURE_CLIENT_ID, AZURE_TENANT_ID and AZURE_SUBSCRIPTION_ID are created as variables in GitHub when running azd pipeline config. However, Microsoft recommends using secrets for these values to avoid exposing them in logs. The workflow supports both approaches, so you can manually create secrets and remove the variables if desired.
Note
In the GitHub Actions workflow, the environment name in the AZURE_ENV_NAME variable is suffixed with -pr{id} for pull requests. This prevents conflicts when multiple PRs are open and avoids accidental removal of environments, because the environment name tag is used when removing resources.
The project includes integration tests built with .NET 10 that validate various scenarios through the deployed Azure services. The tests implement the same scenarios described in the Demo and are located in IntegrationTests.
Some things to note about the integration tests:
- The tests automatically locate your azd environment's
.envfile if available, to retrieve necessary configuration. In the pipeline they rely on environment variables set in the workflow. - The Logic App integration tests use Azure.ResourceManager.AppService to retrieve the Logic App workflow callback URL, leveraging Azure CLI or Azure Developer CLI authentication.
- The Pipeline integration tests use Azure CLI or Azure Developer CLI credentials to call the OAuth-protected API directly.
If you've previously deployed this template and deleted the resources, you may encounter the following error when redeploying the template. This error occurs because the API Management service is in a soft-deleted state and needs to be purged before you can create a new service with the same name.
{
"code": "DeploymentFailed",
"target": "/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg-managedidentity-nwe-i2jdr/providers/Microsoft.Resources/deployments/apiManagement",
"message": "At least one resource deployment operation failed. Please list deployment operations for details. Please see https://aka.ms/arm-deployment-operations for usage details.",
"details": [
{
"code": "ServiceAlreadyExistsInSoftDeletedState",
"message": "Api service apim-managedidentity-nwe-i2jdr was soft-deleted. In order to create the new service with the same name, you have to either undelete the service or purge it. See https://aka.ms/apimsoftdelete."
}
]
}Use the az apim deletedservice list Azure CLI command to list all deleted API Management services in your subscription. Locate the service that is in a soft-deleted state and purge it using the purge command. See the following example:
az apim deletedservice purge --location "swedencentral" --service-name "apim-managedidentity-nwe-i2jdr"If you already have a Consumption tier (SKU=Y1) Function App deployed in the same region, you may encounter the following error when deploying the template. This error occurs because you have reached the region's quota for your subscription.
{
"code": "InvalidTemplateDeployment",
"message": "The template deployment 'functionApp' is not valid according to the validation procedure. The tracking id is '00000000-0000-0000-0000-000000000000'. See inner errors for details.",
"details": [
{
"code": "ValidationForResourceFailed",
"message": "Validation failed for a resource. Check 'Error.Details[0]' for more information.",
"details": [
{
"code": "SubscriptionIsOverQuotaForSku",
"message": "This region has quota of 1 instances for your subscription. Try selecting different region or SKU."
}
]
}
]
}Use the azd down --purge command to delete the resources, then deploy the template in a different region.
If you already have a Workflow Standard WS1 tier (SKU=WS1) Logic App deployed in the same region, you may encounter the following error when deploying the template. This error occurs because you have reached the region's quota for your subscription.
{
"code": "InvalidTemplateDeployment",
"message": "The template deployment 'logicApp' is not valid according to the validation procedure. The tracking id is '00000000-0000-0000-0000-000000000000'. See inner errors for details.",
"details": [
{
"code": "ValidationForResourceFailed",
"message": "Validation failed for a resource. Check 'Error.Details[0]' for more information.",
"details": [
{
"code": "SubscriptionIsOverQuotaForSku",
"message": "This region has quota of 1 instances for your subscription. Try selecting different region or SKU."
}
]
}
]
}Use the azd down --purge command to delete the resources, then deploy the template in a different region.
Deployment fails with BadRequest: ServiceManagementReference field is required for Update, but is missing in the request
In an enterprise environment (for tenants with Entra IDs enabled by Service Tree management), the ServiceManagementReference field on an application (app registration) is mandatory.
If you're deploying this template in such an environment, you may encounter the following error during deployment:
ERROR: error executing step command 'provision': deployment failed: error deploying infrastructure: deploying to subscription:
Deployment Error Details:
BadRequest: ServiceManagementReference field is required for Update, but is missing in the request.
Refer to the TSG `https://aka.ms/service-management-reference-error` for resolving the error
Graph client request id: <request-id>.
Graph request time: 2025-11-20T12:34:56.789Z.
TraceID: <trace-id>
This template provides an optional parameter to set the ServiceManagementReference field on app registrations if required by your tenant.
Use the following command to set the AZURE_SERVICE_MANAGEMENT_REFERENCE environment variable in your azd environment:
azd env set AZURE_SERVICE_MANAGEMENT_REFERENCE <id>Replace <id> with the valid Service Tree ID.
If you don't provide a valid ID, the deployment will fail with the following error: Value for ServiceManagementReference must be a valid GUID.



