APIM Policy Authoring
These samples show the deployed ION policy structure without publishing tenant, application, identity, or endpoint identifiers. Replace placeholders through Terraform variables or APIM named values. Do not paste environment values into policy XML.
Policy-order baseline
Every service 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 or the parent API’s managed-identity backend authentication.
Global policy pattern
The platform owns the complete environment global policy. The following reduced sample demonstrates its control flow; service teams must not copy it into API scope.
<policies>
<inbound>
<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>
<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.
Service API policy
This is the standard API-level pattern. Global caller validation 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-BACKEND-AUDIENCE}}"
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.
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.
<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.
<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[offset]</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 implement provider-specific sender validation,
acquire an APIM UAMI token for backend OAuth, and continue to inherit global
backend, outbound, and error policy. Do not adapt the synthetic-health pattern,
because webhook requests reach application code.
The complete deployed Phoenix example and sanitized XML are in Webhook flow implementation.
Safe trace fragment
Trace bounded metadata rather than headers, token claims, or bodies.
<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, 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 the explicit role for every mapped operation.
Authoring checklist
- XML is valid and special characters in expressions are escaped.
<base />appears in every inherited section at the intended order.- Named values replace environment-specific identifiers and URLs.
- Managed-identity acquisition fails closed.
- Caller and backend tokens are not confused.
- Operation role behavior is explicit: any required role versus all required roles.
- Cache variation preserves tenant and customer isolation.
- Errors reveal no roles, token data, backend secrets, or internal exception text.
- Trace metadata is bounded and contains no credentials or sensitive payloads.