
Azure Workshopz | Beyond Cloud with Chriz
DEPLOY • SECURE • AUTHENTICATE • THROTTLE • BREAK • DIAGNOSE • REPAIR • VERIFY • CLEAN UP
Level: Intermediate to Advanced | Platform: Microsoft Azure | Tools: Azure CLI, Azure Cloud Shell (Bash), Python, KQL | Cost: Medium–High | Format: One integrated enterprise mega lab
Introduction
Your backend application is running. Your REST API is available. Azure API Management reports successful provisioning. But your customers suddenly receive HTTP 401, 403, or 429 responses. Is the subscription key invalid? Has the authentication token expired? Does the caller lack a role? Has the rate limit been exceeded? Or is API Management unable to authenticate to the backend?
In this mega lab, we build a real REST API on Azure App Service, publish it through Azure API Management, configure JWT authentication and role-based authorization, protect the backend with rate limiting, then deliberately introduce five failures and recover the service. The goal is to understand how enterprise APIs behave when something goes wrong—not simply how to publish an API.
What you'll learn
Deploy APIM and App Service; publish REST operations; create API-scoped subscriptions; validate JWT signature, issuer, audience and expiration; enforce application roles; configure Named Values and rate limits; diagnose HTTP 401, 403 and 429; investigate gateway versus backend errors using Log Analytics and KQL; restore policies; verify and clean up.
Enterprise workshop architecture
Azure Cloud Shell (Azure CLI / curl)
|
Subscription key + Bearer JWT
v
Azure API Management (Developer)
- Subscription check
- JWT validation
- Role authorization
- Rate limiting
- Backend credential from Named Value
|
HTTPS
v
Azure App Service (Python REST API)
GET /health
GET /orders
|
v
Synthetic customer orders
APIM GatewayLogs --> Log Analytics
HTTP 401 / 403 / 429
Backend response codes / latency / policy errorsSubscription keys identify API subscription access; JWT validation authenticates a caller; role authorization determines permissions; rate limiting protects the backend; backend authentication secures the gateway-to-application request.
Prerequisites and costs
Use a disposable Azure subscription or dedicated resource group with permission to deploy APIM, App Service, Log Analytics and monitoring resources. You need Bash, Python 3, curl, jq, OpenSSL and zip. Azure infrastructure is managed using Azure CLI, including az rest. Python is used for the test workload and synthetic JWT issuer.
Developer tier supports the key-based rate limiting and gateway logs used here. It is intended for nonproduction use and does not provide a production SLA. APIM Developer, App Service B1, monitoring ingestion and network transfer may incur charges. Both dedicated services remain billable when idle. Delete the resource group when finished.
Pricing: https://azure.microsoft.com/en-us/pricing/details/api-management/
Production deployments should use an appropriate service tier, trusted identity provider, managed identities, Key Vault and private networking where appropriate. The lab uses synthetic tokens and a shared backend secret, not Microsoft Entra-issued tokens or a private backend.
THE MEGA LAB — ONE COMPLETE END-TO-END EXERCISE
Step 1 — Prepare Azure Cloud Shell
Open https://shell.azure.com and choose Bash. Verify tools and the active subscription.
az version
python3 --version
curl --version
jq --version
openssl version
zip -v | head -n 2
az account show --query "{Name:name,SubscriptionId:id}" -o table
# If necessary:
# az account set --subscription "<YOUR-SUBSCRIPTION-ID>"
export LOCATION="westeurope"
export SUFFIX=$(openssl rand -hex 4)
export RG="rg-apim-megalab-$SUFFIX"
export APIM="apim-enterprise-$SUFFIX"
export API_ID="orders-api"
export OPERATION_ID="get-orders"
export API_SUBSCRIPTION="workshop-client"
export PLAN="plan-apim-$SUFFIX"
export APP="app-orders-$SUFFIX"
export LAW="law-apim-$SUFFIX"
export DIAG="diag-apim-gateway"
export JWT_ISSUER="https://issuer.workshop.example"
export JWT_AUDIENCE="azure-workshopz-orders"
export API_VERSION="2024-05-01"
export LAB_DIR="$HOME/apim-megalab-$SUFFIX"
mkdir -p "$LAB_DIR"
cd "$LAB_DIR"
umask 077
read -rp "Publisher email address: " PUBLISHER_EMAIL
export PUBLISHER_EMAIL
az group create \
--name "$RG" \
--location "$LOCATION" \
--tags Environment=Workshop Project=Azure-APIM-MegaLab
az group show -n "$RG" \
--query "{Name:name,State:properties.provisioningState}" -o tableStep 2 — Deploy Azure API Management
Start the Developer instance without waiting so we can prepare the backend during provisioning.
az apim create \
--resource-group "$RG" \
--name "$APIM" \
--location "$LOCATION" \
--publisher-name "Azure Workshopz" \
--publisher-email "$PUBLISHER_EMAIL" \
--sku-name Developer \
--no-wait
az apim show -g "$RG" -n "$APIM" \
--query "{Name:name,State:provisioningState}" -o tableAPIM provisioning can take considerable time. Do not publish the API until the service is ready.
Step 3 — Build the backend REST API
GET /health checks application availability. GET /orders returns three synthetic customer records only when a correct gateway-to-backend credential is supplied. Do not use real customer data or production secrets.
export BACKEND_KEY=$(openssl rand -hex 32)
cat > app.py <<'PY'
import os
import json
import hmac
ORDERS = [
{
"id": "ORD-1001",
"customer": "Customer-A",
"amount": 149.90,
"status": "Completed"
},
{
"id": "ORD-1002",
"customer": "Customer-B",
"amount": 299.00,
"status": "Processing"
},
{
"id": "ORD-1003",
"customer": "Customer-C",
"amount": 79.50,
"status": "Pending"
}
]
def application(environ, start_response):
path = environ.get("PATH_INFO", "/")
method = environ.get("REQUEST_METHOD", "GET")
if method != "GET":
status = "405 Method Not Allowed"
result = {"error": "Method not allowed"}
elif path in ("/", "/health"):
status = "200 OK"
result = {
"status": "Healthy",
"service": "Enterprise Orders API"
}
elif path == "/orders":
supplied = environ.get("HTTP_X_BACKEND_KEY", "")
expected = os.environ.get("BACKEND_KEY", "")
if not expected or not hmac.compare_digest(
supplied, expected
):
status = "403 Forbidden"
result = {
"error": "Backend access denied",
"source": "App Service"
}
else:
status = "200 OK"
result = {
"service": "Enterprise Orders API",
"count": len(ORDERS),
"orders": ORDERS
}
else:
status = "404 Not Found"
result = {"error": "Endpoint not found"}
body = json.dumps(result).encode("utf-8")
start_response(status, [
("Content-Type", "application/json"),
("Content-Length", str(len(body)))
])
return [body]
PY
python3 -m py_compile app.py
zip backend.zip app.pyStep 4 — Deploy Azure App Service
Create the Linux plan and Web App, enable HTTPS-only access and configure the backend credential. Gunicorn hosts the WSGI app.
az appservice plan create \
-g "$RG" -n "$PLAN" -l "$LOCATION" \
--sku B1 --is-linux
az webapp list-runtimes --os linux -o table
az webapp create \
-g "$RG" --plan "$PLAN" -n "$APP" \
--runtime "PYTHON:3.12"
az webapp update -g "$RG" -n "$APP" --https-only true
az webapp config appsettings set \
-g "$RG" -n "$APP" \
--settings "BACKEND_KEY=$BACKEND_KEY" -o none
az webapp config set \
-g "$RG" -n "$APP" \
--startup-file "gunicorn --bind=0.0.0.0:8000 --workers 2 app:application"
az webapp deploy \
-g "$RG" -n "$APP" \
--src-path backend.zip --type zip
export APP_HOST=$(az webapp show -g "$RG" -n "$APP" \
--query defaultHostName -o tsv)
export BACKEND_URL="https://$APP_HOST"
curl -i "$BACKEND_URL/health"
curl -i "$BACKEND_URL/orders"
curl -sS -H "X-Backend-Key: $BACKEND_KEY" \
"$BACKEND_URL/orders" | jqExpected: health returns HTTP 200; direct orders access without the key returns HTTP 403; the authorized request returns three orders. If the selected Python version isn't supported, choose one listed by the CLI. If the application fails to start, investigate App Service startup logs and runtime availability before continuing. The public backend is protected by a lab secret but is not network-isolated.
Step 5 — Complete API Management deployment
az apim wait \
--resource-group "$RG" \
--name "$APIM" \
--created --timeout 7200
az apim show -g "$RG" -n "$APIM" \
--query "{Name:name,State:provisioningState,Gateway:gatewayUrl}" -o table
export GATEWAY_URL=$(az apim show -g "$RG" -n "$APIM" \
--query gatewayUrl -o tsv)
export APIM_ID=$(az apim show -g "$RG" -n "$APIM" \
--query id -o tsv)
echo "API Gateway: $GATEWAY_URL"
echo "Backend: $BACKEND_URL"Checkpoint: APIM provisioning state must be Succeeded.
Step 6 — Publish the Orders API
az apim api create \
--resource-group "$RG" \
--service-name "$APIM" \
--api-id "$API_ID" \
--display-name "Enterprise Orders API" \
--path workshop \
--service-url "$BACKEND_URL" \
--protocols https \
--subscription-required true
az apim api operation create \
--resource-group "$RG" \
--service-name "$APIM" \
--api-id "$API_ID" \
--operation-id "$OPERATION_ID" \
--display-name "Get Customer Orders" \
--method GET \
--url-template "/orders"
az apim api show -g "$RG" --service-name "$APIM" \
--api-id "$API_ID" \
--query "{Name:displayName,Path:path,Backend:serviceUrl,SubscriptionRequired:subscriptionRequired}" -o json
az apim api operation list -g "$RG" --service-name "$APIM" \
--api-id "$API_ID" -o table
export API_URL="${GATEWAY_URL%/}/workshop/orders"
echo "$API_URL"The gateway forwards /workshop/orders to the backend's /orders endpoint.
Step 7 — Configure API subscription access
An API Management subscription is different from an Azure billing subscription. Create an API-scoped subscription and retrieve the key without printing it.
jq -n --arg scope "/apis/$API_ID" \
'{properties:{displayName:"Workshop Client",scope:$scope,state:"active"}}' \
> subscription.json
export SUBSCRIPTION_URI="https://management.azure.com${APIM_ID}/subscriptions/${API_SUBSCRIPTION}"
az rest --method put \
--uri "${SUBSCRIPTION_URI}?api-version=${API_VERSION}" \
--headers "Content-Type=application/json" \
--body @subscription.json -o none
export APIM_KEY=$(az rest --method post \
--uri "${SUBSCRIPTION_URI}/listSecrets?api-version=${API_VERSION}" \
--query primaryKey -o tsv)
if [[ -n "$APIM_KEY" ]]; then
echo "API subscription key available."
fiThe client sends the key in Ocp-Apim-Subscription-Key. It is not a substitute for user authentication.
Step 8 — Configure APIM Named Values
Create two secret Named Values: one for the backend shared secret and one for the synthetic JWT signing key. Never publish the generated values.
export JWT_KEY=$(openssl rand -base64 32)
az apim nv create \
-g "$RG" --service-name "$APIM" \
--named-value-id backend-key \
--display-name backend-key \
--value "$BACKEND_KEY" --secret true -o none
az apim nv create \
-g "$RG" --service-name "$APIM" \
--named-value-id jwt-signing-key \
--display-name jwt-signing-key \
--value "$JWT_KEY" --secret true -o none
az apim nv list -g "$RG" --service-name "$APIM" \
--query "[].{Name:displayName,Secret:secret}" -o tableProduction systems should consider Key Vault-backed Named Values and managed identity-based backend authentication.
Step 9 — Build the JWT authentication client
A JWT consists of HEADER.PAYLOAD.SIGNATURE. The lab generates signed HS256 tokens with issuer, audience, subject, role, issuance and expiration timestamps, and a unique identifier. Use a trusted identity provider in production.
cat > generate-token.py <<'PY'
import argparse
import base64
import hashlib
import hmac
import json
import os
import time
import uuid
parser = argparse.ArgumentParser()
parser.add_argument("--role", default="Orders.Read")
parser.add_argument("--audience", default=os.environ["JWT_AUDIENCE"])
parser.add_argument("--lifetime", type=int, default=3600)
parser.add_argument("--subject", default="workshop-user")
args = parser.parse_args()
key = base64.b64decode(os.environ["JWT_KEY"])
now = int(time.time())
def encode(value):
return base64.urlsafe_b64encode(value).rstrip(b"=").decode()
header = {"alg": "HS256", "typ": "JWT"}
payload = {
"iss": os.environ["JWT_ISSUER"],
"aud": args.audience,
"sub": args.subject,
"role": args.role,
"iat": now,
"exp": now + args.lifetime,
"jti": str(uuid.uuid4())
}
encoded_header = encode(json.dumps(header, separators=(",", ":")).encode())
encoded_payload = encode(json.dumps(payload, separators=(",", ":")).encode())
message = encoded_header + "." + encoded_payload
signature = hmac.new(key, message.encode(), hashlib.sha256).digest()
print(message + "." + encode(signature))
PY
export VALID_TOKEN=$(python3 generate-token.py --role Orders.Read)
export WRONG_AUDIENCE_TOKEN=$(python3 generate-token.py \
--role Orders.Read --audience incorrect-api)
export EXPIRED_TOKEN=$(python3 generate-token.py \
--role Orders.Read --lifetime -3600)
export FORBIDDEN_TOKEN=$(python3 generate-token.py --role Orders.Viewer)Expected: valid token -> 200; wrong audience or expired token -> 401; missing role -> 403. These are laboratory tokens, not Microsoft Entra access tokens.
Step 10 — Configure the enterprise API security policy
The inbound policy validates JWTs, checks the role, applies a per-subscription rate limit, injects the backend credential, and removes client authentication headers. Outbound and error policies attach a correlation identifier where executed.
cat > policy-good.xml <<'XML'
<policies>
<inbound>
<base />
<validate-jwt
header-name="Authorization"
require-scheme="Bearer"
require-expiration-time="true"
require-signed-tokens="true"
failed-validation-httpcode="401"
failed-validation-error-message="Invalid or expired token"
output-token-variable-name="labJwt">
<issuer-signing-keys>
<key>{{jwt-signing-key}}</key>
</issuer-signing-keys>
<audiences>
<audience>azure-workshopz-orders</audience>
</audiences>
<issuers>
<issuer>https://issuer.workshop.example</issuer>
</issuers>
</validate-jwt>
<choose>
<when condition='@(((Jwt)context.Variables["labJwt"]).Claims.GetValueOrDefault("role", "") != "Orders.Read")'>
<return-response>
<set-status code="403" reason="Forbidden" />
<set-header name="Content-Type" exists-action="override">
<value>application/json</value>
</set-header>
<set-body>{"error":"Required role missing","source":"APIM"}</set-body>
</return-response>
</when>
</choose>
<rate-limit-by-key
calls="30"
renewal-period="60"
counter-key='@("orders-normal-" + context.Subscription.Id)'
remaining-calls-header-name="X-RateLimit-Remaining" />
<set-header name="X-Backend-Key" exists-action="override">
<value>{{backend-key}}</value>
</set-header>
<set-header name="Authorization" exists-action="delete" />
<set-header name="Ocp-Apim-Subscription-Key" exists-action="delete" />
<set-query-parameter name="subscription-key" exists-action="delete" />
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
<set-header name="X-Lab-Correlation-Id" exists-action="override">
<value>@(context.RequestId.ToString())</value>
</set-header>
</outbound>
<on-error>
<base />
<set-header name="X-Lab-Correlation-Id" exists-action="override">
<value>@(context.RequestId.ToString())</value>
</set-header>
</on-error>
</policies>
XML
export POLICY_URI="https://management.azure.com${APIM_ID}/apis/${API_ID}/policies/policy?api-version=${API_VERSION}"
jq -n --rawfile policy policy-good.xml \
'{properties:{format:"rawxml",value:$policy}}' > policy-request.json
az rest --method put --uri "$POLICY_URI" \
--headers "Content-Type=application/json" \
--body @policy-request.json -o none
apply_policy() {
local POLICY_FILE="$1"
jq -n --rawfile policy "$POLICY_FILE" \
'{properties:{format:"rawxml",value:$policy}}' > policy-request.json
az rest --method put --uri "$POLICY_URI" \
--headers "Content-Type=application/json" "If-Match=*" \
--body @policy-request.json -o none
}
az rest --method get --uri "$POLICY_URI" \
--query properties.value -o tsvThe wildcard ETag is used for convenience in a disposable lab. Production policy deployments should use appropriate concurrency controls. Allow gateway policy changes to propagate before testing.
Step 11 — Enable centralized API monitoring
az monitor log-analytics workspace create \
-g "$RG" --workspace-name "$LAW" -l "$LOCATION" \
--sku PerGB2018 --retention-time 30
export LAW_ID=$(az monitor log-analytics workspace show \
-g "$RG" --workspace-name "$LAW" --query id -o tsv)
export LAW_CUSTOMER_ID=$(az monitor log-analytics workspace show \
-g "$RG" --workspace-name "$LAW" --query customerId -o tsv)
az monitor diagnostic-settings categories list \
--resource "$APIM_ID" -o table
az monitor diagnostic-settings create \
--resource "$APIM_ID" --name "$DIAG" \
--workspace "$LAW_ID" \
--export-to-resource-specific true \
--logs '[{"category":"GatewayLogs","enabled":true}]'
az monitor diagnostic-settings list \
--resource "$APIM_ID" -o jsonConfirm GatewayLogs is available. The resource-specific table is ApiManagementGatewayLogs. Ingestion can take time. Do not configure logging of sensitive request headers or full payloads.
Step 12 — Establish the working API baseline
export VALID_TOKEN=$(python3 generate-token.py --role Orders.Read)
curl -i --max-time 30 \
-H "Ocp-Apim-Subscription-Key: $APIM_KEY" \
-H "Authorization: Bearer $VALID_TOKEN" \
"$API_URL"
call_api() {
local TOKEN="$1"
curl -sS --max-time 30 \
-D response-headers.txt \
-o response-body.json \
-w "HTTP %{http_code} | %{time_total}s\n" \
-H "Ocp-Apim-Subscription-Key: $APIM_KEY" \
-H "Authorization: Bearer $TOKEN" \
"$API_URL"
cat response-body.json
echo
}
call_api "$VALID_TOKEN"Expected: HTTP 200, a JSON body containing three orders, X-RateLimit-Remaining and X-Lab-Correlation-Id headers on the successful response.
HTTP 200
{"service":"Enterprise Orders API","count":3,"orders":[...]}Do not continue until the subscription, token, authorization, rate limit, backend connectivity and backend authentication all work.
Step 13 — BREAK #1: Missing API subscription key
Send a valid JWT without the subscription key, then repeat with an invalid key.
curl -i --max-time 30 \
-H "Authorization: Bearer $VALID_TOKEN" "$API_URL"
curl -i --max-time 30 \
-H "Ocp-Apim-Subscription-Key: invalid-key" \
-H "Authorization: Bearer $VALID_TOKEN" "$API_URL"Expected: HTTP 401 Unauthorized. The request is rejected before reaching the backend.
Diagnose the API configuration and subscription state:
az apim api show -g "$RG" --service-name "$APIM" \
--api-id "$API_ID" --query subscriptionRequired -o tsv
az rest --method get \
--uri "${SUBSCRIPTION_URI}?api-version=${API_VERSION}" \
--query "properties.{State:state,Scope:scope}" -o jsonRepair by restoring the correct subscription header:
call_api "$VALID_TOKEN"Expected: HTTP 200. A valid JWT does not replace a required subscription key.
Step 14 — BREAK #2: Invalid or expired JWT
call_api "$WRONG_AUDIENCE_TOKEN"
call_api "$EXPIRED_TOKEN"
call_api "invalid-jwt-token"Expected: HTTP 401, invalid or expired token. The validate-jwt policy verifies signature, issuer, audience and expiry.
Decode the wrong audience token locally for troubleshooting (decoding is not signature verification):
export INSPECT_TOKEN="$WRONG_AUDIENCE_TOKEN"
python3 - <<'PY'
import os
import json
import base64
token = os.environ["INSPECT_TOKEN"]
payload = token.split(".")[1]
payload += "=" * (-len(payload) % 4)
claims = json.loads(base64.urlsafe_b64decode(payload))
print(json.dumps(claims, indent=2))
PY
unset INSPECT_TOKENThe audience is incorrect-api instead of azure-workshopz-orders. Repair by generating a fresh valid token.
export VALID_TOKEN=$(python3 generate-token.py \
--role Orders.Read --audience "$JWT_AUDIENCE")
call_api "$VALID_TOKEN"Expected: HTTP 200. A valid subscription does not guarantee valid authentication.
Step 15 — BREAK #3: Insufficient application permissions
A caller may have a valid JWT but lack the required Orders.Read role.
export FORBIDDEN_TOKEN=$(python3 generate-token.py --role Orders.Viewer)
call_api "$FORBIDDEN_TOKEN"Expected:
HTTP 403
{"error":"Required role missing","source":"APIM"}The issuer, audience, signature and expiration are valid; the role is incorrect. Restore access using the correctly issued token.
export VALID_TOKEN=$(python3 generate-token.py --role Orders.Read)
call_api "$VALID_TOKEN"Expected: HTTP 200. In production roles must be assigned through an authorized identity-management process; arbitrary role generation is possible only because this is a controlled test issuer.
Step 16 — BREAK #4: Rate limiting and HTTP 429
Reduce the normal policy from 30 calls per 60 seconds to 3. Use a separate counter-key prefix to avoid interference from the baseline.
sed \
-e 's/calls="30"/calls="3"/' \
-e 's/orders-normal-/orders-burst-test-/' \
policy-good.xml > policy-throttle.xml
apply_policy policy-throttle.xmlAllow the policy to propagate. Generate a fresh token and send ten controlled requests.
export VALID_TOKEN=$(python3 generate-token.py --role Orders.Read)
for i in $(seq 1 10); do
echo "Request $i"
curl -sS --max-time 30 \
-D "burst-headers-$i.txt" \
-o "burst-response-$i.json" \
-w "HTTP %{http_code} | %{time_total}s\n" \
-H "Ocp-Apim-Subscription-Key: $APIM_KEY" \
-H "Authorization: Bearer $VALID_TOKEN" \
"$API_URL"
sleep 0.2
done
grep -iE 'HTTP/|retry-after:|x-ratelimit-remaining:' \
burst-headers-*.txtIllustrative results: the first three requests succeed, subsequent requests return HTTP 429. Distributed rate limiting is approximate, so the exact boundary may vary. Inspect Retry-After. A rate-limit response is intentional traffic protection, not necessarily an outage.
Test compliant recovery, then restore the original policy.
sleep 65
call_api "$VALID_TOKEN"
apply_policy policy-good.xml
# Allow propagation before testing.
call_api "$VALID_TOKEN"Expected: HTTP 200. If a normal-policy counter remains active, wait for its window to clear. Clients should respect Retry-After and use appropriate backoff.
Step 17 — BREAK #5: Gateway-to-backend authentication failure
Replace the correct Named Value reference with an incorrect synthetic backend key.
sed 's/{{backend-key}}/incorrect-workshop-backend-key/' \
policy-good.xml > policy-backend-broken.xml
apply_policy policy-backend-broken.xml
# Allow propagation.
call_api "$VALID_TOKEN"Expected:
HTTP 403
{"error":"Backend access denied","source":"App Service"}Unlike the role-related 403, this response comes from the backend. Verify the backend health and direct authorized access.
curl -i "$BACKEND_URL/health"
curl -sS -H "X-Backend-Key: $BACKEND_KEY" \
"$BACKEND_URL/orders" | jqBoth should work. The fault is the gateway's backend credential. Repair:
apply_policy policy-good.xml
# Allow propagation.
call_api "$VALID_TOKEN"Expected: HTTP 200. Identical status codes can originate at different architectural layers.
Step 18 — Investigate all incidents using Log Analytics
Use the resource-specific gateway table. If the table has not appeared yet, verify diagnostics and wait for ingestion. Actual values depend on the test; example output is not measured data.
Query 1 — Recent API requests
az monitor log-analytics query \
--workspace "$LAW_CUSTOMER_ID" \
--analytics-query "
ApiManagementGatewayLogs
| where TimeGenerated > ago(4h)
| where Url contains '/workshop/orders'
| project TimeGenerated, ApiId, OperationId, ResponseCode,
BackendResponseCode, LastErrorReason, CorrelationId
| order by TimeGenerated desc
| take 50
" -o tableQuery 2 — HTTP 401 authentication failures
az monitor log-analytics query \
--workspace "$LAW_CUSTOMER_ID" \
--analytics-query "
ApiManagementGatewayLogs
| where TimeGenerated > ago(4h)
| where Url contains '/workshop/orders'
| where ResponseCode == 401
| project TimeGenerated, ResponseCode, LastErrorReason,
LastErrorMessage, LastErrorSource, CorrelationId
| order by TimeGenerated desc
" -o tableCompare missing subscription key errors with JWT validation errors.
Query 3 — HTTP 403 authorization failures
az monitor log-analytics query \
--workspace "$LAW_CUSTOMER_ID" \
--analytics-query "
ApiManagementGatewayLogs
| where TimeGenerated > ago(4h)
| where Url contains '/workshop/orders'
| where ResponseCode == 403
| extend FailureLayer = iff(BackendResponseCode == 403,
'Backend', 'Gateway or policy')
| project TimeGenerated, ResponseCode, BackendResponseCode,
FailureLayer, LastErrorReason, CorrelationId
| order by TimeGenerated desc
" -o tableA gateway-generated 403 may have no backend response, whereas a backend-generated 403 should expose a backend response code.
Query 4 — HTTP 429 rate limiting
az monitor log-analytics query \
--workspace "$LAW_CUSTOMER_ID" \
--analytics-query "
ApiManagementGatewayLogs
| where TimeGenerated > ago(4h)
| where Url contains '/workshop/orders'
| where ResponseCode == 429
| summarize ThrottledRequests=count() by bin(TimeGenerated, 1m)
| order by TimeGenerated asc
" -o tableQuery 5 — Response-code distribution
az monitor log-analytics query \
--workspace "$LAW_CUSTOMER_ID" \
--analytics-query "
ApiManagementGatewayLogs
| where TimeGenerated > ago(4h)
| where Url contains '/workshop/orders'
| summarize Requests=count() by ResponseCode
| order by Requests desc
" -o tableQuery 6 — API response latency
az monitor log-analytics query \
--workspace "$LAW_CUSTOMER_ID" \
--analytics-query "
ApiManagementGatewayLogs
| where TimeGenerated > ago(4h)
| where Url contains '/workshop/orders'
| where ResponseCode == 200
| summarize Requests=count(),
AverageLatencyMs=avg(TotalTime),
P95LatencyMs=percentile(TotalTime, 95),
AverageBackendMs=avg(BackendTime)
by bin(TimeGenerated, 5m)
| order by TimeGenerated asc
" -o tableCompare total gateway latency against backend latency.
Step 19 — Configure an Azure Monitor server error alert
401 and 429 may indicate correct security behavior, not availability failures. Configure an alert on the APIM Requests metric for gateway 5xx responses.
az monitor metrics list-definitions \
--resource "$APIM_ID" \
--query "[?name.value=='Requests']" -o json
az monitor metrics list --resource "$APIM_ID" \
--metric Requests --interval PT1M --aggregation Total -o json
az monitor metrics alert create \
--resource-group "$RG" \
--name alert-apim-server-errors \
--scopes "$APIM_ID" \
--condition "total Requests > 5 where GatewayResponseCodeCategory includes 5xx" \
--window-size 5m \
--evaluation-frequency 1m \
--severity 2 \
--description "APIM gateway server error threshold exceeded"
az monitor metrics alert show -g "$RG" \
--name alert-apim-server-errors -o jsonCheck the actual metric dimension and supported category values; adjust if the selected service exposes different values. This rule does not send email without an Action Group. The five 4xx incidents are not expected to trigger it.
Step 20 — Review the complete incident matrix
Scenario HTTP Backend reached?
Missing subscription key 401 No
Invalid or expired JWT 401 No
Missing application role 403 No
Rate limit exceeded 429 No
Wrong backend credential 403 Yes
Healthy request 200 YesThe key troubleshooting question: At which layer did the request fail?
API request fails
|
Check HTTP status and APIM gateway logs
|
+-- Backend not reached
| Subscription key / JWT / role / rate limit
|
+-- Backend reached
Backend health / credential / application
|
Apply targeted repair --> Verify HTTP 200Avoid changing multiple security policies simultaneously.
Step 21 — Final end-to-end verification
Restore the original policy and generate a new valid token. Verify healthy gateway access, direct backend protection, and the expected security failures.
apply_policy policy-good.xml
export VALID_TOKEN=$(python3 generate-token.py --role Orders.Read)
curl -i "$BACKEND_URL/health"
curl -i "$BACKEND_URL/orders"
call_api "$VALID_TOKEN"
curl -sS \
-H "Ocp-Apim-Subscription-Key: $APIM_KEY" \
-H "Authorization: Bearer $VALID_TOKEN" \
"$API_URL" | jq -e '.count == 3 and (.orders | length == 3)'
curl -sS -o /dev/null \
-w "Missing subscription: HTTP %{http_code}\n" \
-H "Authorization: Bearer $VALID_TOKEN" "$API_URL"
export FORBIDDEN_TOKEN=$(python3 generate-token.py --role Orders.Viewer)
curl -sS -o /dev/null \
-w "Invalid role: HTTP %{http_code}\n" \
-H "Ocp-Apim-Subscription-Key: $APIM_KEY" \
-H "Authorization: Bearer $FORBIDDEN_TOKEN" "$API_URL"
curl -sS -o /dev/null \
-w "Invalid token: HTTP %{http_code}\n" \
-H "Ocp-Apim-Subscription-Key: $APIM_KEY" \
-H "Authorization: Bearer invalid-token" "$API_URL"Final checkpoint: APIM succeeded, App Service running, subscription active, JWT and role validation enabled, rate limit 30/60 seconds, correct backend credential, direct unauthenticated orders access denied, authorized request HTTP 200 with three records, 401/403/429 behavior demonstrated and gateway diagnostics enabled.
Step 22 — Cleanup
APIM and App Service are billable even while idle. Review resources and delete the dedicated resource group.
az resource list -g "$RG" \
--query "[].{Name:name,Type:type}" -o table
az group delete --name "$RG" --yes
az group exists --name "$RG"Expected: false. APIM can enter a soft-deleted state, preventing immediate reuse of the service name. Clear secrets and remove local files after preserving any incident evidence.
unset BACKEND_KEY JWT_KEY APIM_KEY VALID_TOKEN
unset WRONG_AUDIENCE_TOKEN EXPIRED_TOKEN FORBIDDEN_TOKEN PUBLISHER_EMAIL
cd "$HOME"
rm -rf -- "$LAB_DIR"
umask 022Workshop review — five failures, five operational lessons
1. Subscription access: a valid JWT does not replace a required subscription key.
2. Authentication: token signature, issuer, audience and expiration must satisfy the policy.
3. Authorization: authenticated callers may still lack permission.
4. Rate limiting: HTTP 429 can indicate protection is working as intended.
5. Backend authentication: the gateway may authenticate a caller successfully while failing to authenticate itself to the backend.
Advanced enterprise extensions
Microsoft Entra ID authentication: replace the synthetic issuer with Entra application registrations, app roles and validate-azure-ad-token.
Managed identity backend authentication: replace the shared secret with an identity-based token and test authorization.
Key Vault integration: store sensitive Named Values in Key Vault and test rotation.
API revisions and rollback: deploy a new revision with an incorrect backend configuration and restore the previous revision.
Private backend networking: use supported networking tiers and investigate private DNS and access restrictions.
Response caching: compare backend requests and latency, then investigate stale responses and expiry.
Multi-backend resilience: explore supported backend pools and circuit breakers with a second backend.
Final challenge — test your knowledge
What is the difference between APIM and App Service? Why are subscription keys not user authentication? What are the three parts of a JWT? What is the difference between issuer and audience? Why reject expired tokens? How do 401 and 403 differ? What is claim-based authorization? Why use Named Values and separate backend credentials? What does 429 mean and why respect Retry-After? How can you distinguish a gateway rejection from a backend rejection? What would you change to make this design production-ready?
Production architecture considerations
Use production-supported APIM tiers, Microsoft Entra ID and OAuth 2.0, managed identities, Key Vault, appropriate private network connectivity, versioning and revisions, schema validation, quotas and capacity planning, suitable retry and timeout policies, circuit breakers, centralized security monitoring and automated policy tests. Avoid logging sensitive information. The lab's public backend with a shared secret is not equivalent to a network-isolated private backend.
Conclusion
Azure API Management is more than an endpoint for publishing APIs. It provides API security, authentication, authorization, traffic management and operational visibility. In this mega lab we deploy a complete environment, introduce five incidents, investigate the gateway and backend using logs, and restore service. An API returning an error does not necessarily mean that the application is unavailable; it may mean that a security or traffic-management policy is working exactly as intended.
Deploy. Secure. Authenticate. Throttle. Break. Diagnose. Repair. Verify.
Technical validation: The commands and expected results are based on documented Azure CLI and REST interfaces. This workshop has not been executed end-to-end in a live Azure subscription; actual provisioning, response codes, propagation and telemetry should be verified in a disposable environment.
Official Microsoft documentation
Azure API Management overview — https://learn.microsoft.com/en-us/azure/api-management/api-management-key-concepts
Service tiers — https://learn.microsoft.com/en-us/azure/api-management/api-management-features
Azure CLI API Management — https://learn.microsoft.com/en-us/cli/azure/apim
Azure CLI API Management APIs — https://learn.microsoft.com/en-us/cli/azure/apim/api
Policy reference — https://learn.microsoft.com/en-us/azure/api-management/api-management-policies
Validate JWT — https://learn.microsoft.com/en-us/azure/api-management/validate-jwt-policy
Rate limit by key — https://learn.microsoft.com/en-us/azure/api-management/rate-limit-by-key-policy
Named Values — https://learn.microsoft.com/en-us/azure/api-management/api-management-howto-properties
Authentication and authorization — https://learn.microsoft.com/en-us/azure/api-management/authentication-authorization-overview
Policy expressions — https://learn.microsoft.com/en-us/azure/api-management/api-management-policy-expressions
App Service Python configuration — https://learn.microsoft.com/en-us/azure/app-service/containers/how-to-configure-python
Monitoring — https://learn.microsoft.com/en-us/azure/api-management/monitor-api-management
Gateway log schema — https://learn.microsoft.com/en-us/azure/azure-monitor/reference/tables/apimanagementgatewaylogs
REST policy API — https://learn.microsoft.com/en-us/rest/api/apimanagement/api-policy/create-or-update
Pricing — https://azure.microsoft.com/en-us/pricing/details/api-management/
Azure Workshopz | Beyond Cloud with Chriz
Hands-on Azure infrastructure workshops focused on deployment, security, automation, troubleshooting and recovery.
Comments