APIM Policy Authoring
These samples show the deployed ION policy structure without publishing tenant, application, identity, Front Door, or endpoint identifiers. Replace placeholders through Terraform variables or APIM named values. Do not paste environment values into policy XML.
Policy-order baseline
Every product, API, and operation policy inherits its parent scope:
<policies>
<inbound>
<base />
<!-- Local inbound policy executes after inherited inbound policy. -->
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>
The placement of <base /> controls order. Removing it can remove global caller
validation, MFE capability validation, or the parent API’s managed-identity
backend authentication.
Global policy pattern
The platform owns the complete environment global policy. The following reduced sample shows its control flow in the target state, with the APIM-01 and APIM-02 fixes applied. Service teams must not copy it into product or API scope.
<policies>
<inbound>
<check-header
name="X-Azure-FDID"
failed-check-httpcode="403"
failed-check-error-message="Request was not routed through Front Door."
ignore-case="false">
<value>{{APIM-FRONT-DOOR-ID}}</value>
</check-header>
<check-header
name="Authorization"
failed-check-httpcode="401"
failed-check-error-message="Not authorized"
ignore-case="false" />
<set-header name="X-Transaction-Id" exists-action="skip">
<value>@(Guid.NewGuid().ToString())</value>
</set-header>
<validate-jwt
header-name="Authorization"
require-scheme="Bearer"
require-signed-tokens="true"
output-token-variable-name="jwt">
<openid-config url="{{APIM-OPENID-CONFIGURATION-URL}}" />
<audiences>
<audience>{{APIM-ALLOWED-AUDIENCE}}</audience>
</audiences>
<required-claims>
<claim name="tid" match="all" />
<claim name="roles" match="all" />
</required-claims>
</validate-jwt>
<set-header name="X-Tenant-Id" exists-action="override">
<value>@(((Jwt)context.Variables["jwt"]).Claims.GetValueOrDefault("tid", ""))</value>
</set-header>
<!-- Target state: override, never skip. Deployed policy uses skip (APIM-01). -->
<set-header name="X-Authorization" exists-action="override">
<value>@(context.Request.Headers.GetValueOrDefault("Authorization", ""))</value>
</set-header>
<include-fragment fragment-id="fragment-request-trace" />
</inbound>
<backend>
<limit-concurrency key="@(context.Api.Id)" max-count="200">
<forward-request timeout="120" fail-on-error-status-code="true" />
</limit-concurrency>
</backend>
<outbound>
<include-fragment fragment-id="fragment-response-trace" />
</outbound>
<on-error>
<include-fragment fragment-id="fragment-error-trace" />
</on-error>
</policies>
Customer tenant activation is an additional global step in the deployed policy.
It uses a cached managed-identity-authenticated HEAD request and denies inactive
or unresolved customer tenants. See Global policy implementation
for the full deployed sequence; this reduced sample is guidance, not a replacement
for the platform-owned policy.
MFE product policy
This is the shape of the deployed MFE product policy
(signet/infrastructure-shared/policies/apim-product-mfe-policy.xml), reduced
for readability. The full file also extracts the workspace path parameter.
<policies>
<inbound>
<base /> <!-- MUST be first: global caller validation runs before capability logic -->
<rate-limit-by-key
calls="300"
renewal-period="60"
counter-key="@(context.Api.Id + "-" + ((Jwt)context.Variables["jwt"]).Claims.GetValueOrDefault("oid", "none"))" />
<quota-by-key
calls="5000"
bandwidth="40000"
renewal-period="3600"
counter-key="@(((Jwt)context.Variables["jwt"]).Claims.GetValueOrDefault("tid", "none"))" />
<send-request mode="new" response-variable-name="capValidation" timeout="5" ignore-error="false">
<set-url>${globals.backend_base_url}/v1/validations</set-url>
<set-method>POST</set-method>
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>@{
/* capabilities_token from X-Capabilities, tenant_id and ion_workspace_id
from matched path parameters, request_method */
}</set-body>
<authentication-managed-identity
resource="{{APIM-AZURE-AD-APPLICATION-ID}}"
client-id="{{APIM-MSI-CLIENT-ID}}" />
</send-request>
<choose>
<when condition="@(((IResponse)context.Variables["capValidation"]).StatusCode != 200)">
<return-response>
<set-status code="403" reason="Forbidden" />
</return-response>
</when>
</choose>
<!-- Does not touch Authorization, X-Authorization, or X-Tenant-Id. -->
</inbound>
<backend><base /></backend>
<outbound>
<base />
<set-header name="x-aspnet-version" exists-action="delete" />
<set-header name="x-powered-by" exists-action="delete" />
</outbound>
<on-error><base /></on-error>
</policies>
Rules for any product policy:
<base />MUST be the first inbound statement.- It MUST NOT modify
Authorization,X-Authorization, orX-Tenant-Id. - Validation calls MUST fail closed:
ignore-error="false", a short timeout, and a non-success result returns403. - Changes MUST receive platform and security review (CODEOWNERS).
Service API policy
This is the standard API-level pattern. Global caller validation (and any product
policy) executes first; APIM then selects the service backend, applies rate
limiting, acquires an APIM identity token for the backend audience, and replaces
Authorization.
<policies>
<inbound>
<base />
<set-backend-service base-url="${globals.backend_base_url}" />
<set-variable
name="rateLimitKey"
value="@(context.Api.Id + "-" + ((Jwt)context.Variables["jwt"]).Claims.GetValueOrDefault("oid", "none"))" />
<rate-limit-by-key
calls="${globals.rate_limit_calls}"
renewal-period="60"
counter-key="@(context.Variables.GetValueOrDefault<string>("rateLimitKey", "none"))" />
<authentication-managed-identity
resource="{{APIM-AZURE-AD-APPLICATION-ID}}"
client-id="{{APIM-MSI-CLIENT-ID}}"
output-token-variable-name="backend-access-token"
ignore-error="false" />
<set-header name="Authorization" exists-action="override">
<value>@("Bearer " + (string)context.Variables["backend-access-token"])</value>
</set-header>
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
<set-header name="x-aspnet-version" exists-action="delete" />
<set-header name="x-powered-by" exists-action="delete" />
</outbound>
<on-error>
<base />
</on-error>
</policies>
ignore-error="false" is mandatory: failure to acquire the APIM backend token
must stop the request. If the backend needs no caller context, the API policy
MAY also override X-Authorization with the APIM token, as the Internal API
does.
Operation role and rewrite policy
The operation map supplies the rewrite and role list. This example authorizes the
request when the caller has any configured required role. Every operation
template that receives roles_csv must contain this block; Signet’s template
currently does not (gap APIM-05).
<policies>
<inbound>
<base />
<rewrite-uri
template="${globals.rewrite_template_path}"
copy-unmatched-params="true" />
<choose>
<when condition="@{
var jwt = (Jwt)context.Variables["jwt"];
if (!jwt.Claims.ContainsKey("roles")) {
return true;
}
string[] callerRoles = jwt.Claims["roles"];
string[] requiredRoles = { ${globals.roles_csv} };
return !requiredRoles.Any(requiredRole =>
Array.Exists(callerRoles, callerRole => callerRole == requiredRole));
}">
<set-variable name="X-Status-Code" value="403" />
<set-variable name="X-Status-Reason" value="Forbidden" />
<set-variable
name="X-Last-Error"
value="Required role is not present in the caller token." />
<include-fragment fragment-id="fragment-error-trace" />
<return-response>
<set-status code="403" reason="Forbidden" />
</return-response>
</when>
</choose>
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
</outbound>
<on-error>
<base />
</on-error>
</policies>
Do not put the caller’s full role list or token into the denial message or trace.
Optional response cache
Cache policy belongs at operation scope. Include tenant/customer variation for customer-dependent responses, and capability variation for MFE routes.
<cache-lookup
allow-private-response-caching="true"
caching-type="internal"
vary-by-developer="false"
vary-by-developer-groups="false">
<vary-by-header>X-Tenant-Id</vary-by-header>
<vary-by-header>Accept</vary-by-header>
<vary-by-query-parameter>page[cursor]</vary-by-query-parameter>
<vary-by-query-parameter>page[limit]</vary-by-query-parameter>
</cache-lookup>
Store only successful, explicitly cacheable responses:
<choose>
<when condition="@(
context.Response.StatusCode == 200 &&
string.Equals("${globals.cache_response}", "true", StringComparison.OrdinalIgnoreCase)
)">
<cache-store duration="${globals.cache_duration}" />
</when>
</choose>
A cache key that omits customer context can become a cross-customer disclosure.
Operation-specific backend override
An operation may route to another protected backend. It must still inherit the API and global policy chain. If the alternate backend has a different audience or approved APIM identity, explicitly acquire the correct token after selecting it.
<set-backend-service base-url="${globals.messaging_backend_base_url}" />
<authentication-managed-identity
resource="{{APIM-MESSAGING-BACKEND-AUDIENCE}}"
client-id="{{APIM-MSI-CLIENT-ID}}"
output-token-variable-name="messaging-backend-token"
ignore-error="false" />
<set-header name="Authorization" exists-action="override">
<value>@("Bearer " + (string)context.Variables["messaging-backend-token"])</value>
</set-header>
Synthetic public health operation
Only a deliberately public synthetic health operation may omit <base /> in
inbound policy to bypass global authentication. It must return no dependency or
customer information.
<policies>
<inbound>
<return-response>
<set-status code="200" reason="OK" />
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>{ "status": "available" }</set-body>
</return-response>
</inbound>
<backend />
<outbound />
<on-error />
</policies>
This reports gateway policy availability, not backend readiness. An authenticated
health operation should use the normal <base /> chain and a health-read role.
External-provider webhook exception
A reviewed webhook API may omit inbound <base /> when its provider cannot
present an ION bearer token. It must check X-Azure-FDID, implement
provider-specific sender validation, acquire an APIM UAMI token for backend OAuth,
and continue to inherit global backend, outbound, and error policy. It must not
include body-logging trace fragments. Do not adapt the synthetic-health pattern,
because webhook requests reach application code.
The deployed Phoenix and Pigeon examples are in Webhook flow implementation.
Safe trace fragment
Trace bounded metadata rather than headers, token claims, or bodies. This fragment is also safe for webhook APIs.
<fragment>
<trace source="ION API Gateway" severity="information">
<message>APIM request</message>
<metadata
name="TransactionId"
value="@(context.Request.Headers.GetValueOrDefault("X-Transaction-Id", "none"))" />
<metadata name="ApiId" value="@(context.Api.Id)" />
<metadata name="OperationId" value="@(context.Operation.Id)" />
<metadata name="RequestId" value="@(context.RequestId.ToString())" />
</trace>
</fragment>
Never add Authorization, X-Authorization, X-Capabilities, provider
signatures, raw JWT data, secrets, or unredacted request/response bodies to a
fragment.
Terraform operation-policy renderer
The service-local module renders one policy for each OpenAPI operationId:
resource "azurerm_api_management_api_operation_policy" "operation" {
for_each = var.apim_api_operations_policy
api_name = var.api_name
api_management_name = var.api_management_name
resource_group_name = var.resource_group_name
operation_id = each.key
xml_content = templatefile(each.value.file, {
globals = merge(local.default_template_vars, each.value.vars)
})
}
Defaults are convenience values, not permission decisions. A default role must not accidentally authorize an operation; reviewers must verify both the explicit role for every mapped operation and that the template consumes it.
Authoring checklist
- XML is valid and special characters in expressions are escaped.
<base />appears in every inherited section at the intended order, and first in product inbound policy.- Named values replace environment-specific identifiers and URLs.
- Managed-identity acquisition fails closed.
- Caller and backend tokens are not confused;
X-Authorizationis overridden, never skipped. - Operation role behavior is explicit (any required role versus all required
roles), and the template uses
roles_csv. - Cache variation preserves tenant, customer, and capability isolation.
- Errors reveal no roles, token data, backend secrets, or internal exception text.
- Trace metadata is bounded and contains no credentials or sensitive payloads.