iamops.dev Search
Argo on X RSS feed
ENEnglish

Labs Practitioner · 16 min

For people who build or run apps on Microsoft Entra. New to the idea? Read the short explainer first: Entra authentication context, extra MFA for one risky action.

Entra step-up lab: MFA only for the payment request

A real Entra run: orders pass after a password sign-in, the payment gets a 401 claims challenge, Entra asks for MFA, and the payment passes.

Headline cover: extra sign-in check only for the payment. Three screenshots: the Microsoft Authenticator number prompt, the enabled Conditional Access policy and the authentication context list.
TL;DRWith one authentication context and one policy, reading orders worked…
Repeat this lab 10 steps

I wrote this lab so you can run it yourself. Each step has the commands to copy and the output I got, and you can tick it as done. Your ticks stay in this browser only.

Go to the steps

How this works

Copies a ready-made prompt for Claude Code, Cursor, Codex or any coding agent. For test environments only.

Show prompt
I want to run a hands-on lab from iamops.dev, and I would like your help to do it safely.

Lab: Entra step-up lab: MFA only for the payment request
Read the whole lab here (Markdown): https://iamops.dev/entra-auth-context-step-up-mfa.md

What the lab needs before the first step:
- Throwaway tenant, Azure CLI, curl, jq, openssl
- Values I have to set myself (the lab uses placeholders): <TENANT_ID>

How I want you to work:
1. Read the lab from start to finish first (each step lists its own prerequisites). Then check that the prerequisites are in place and that the tool versions match what the lab expects. Tell me what is missing before you run anything.
2. Run one step at a time. Before each command, show it to me and say in a sentence what it does.
3. Ask me before anything that costs money, creates cloud resources, touches a real tenant or account, or deletes anything. Wait for my answer.
4. Use the placeholders from the lab. Never paste real secrets, tokens or production identities into a command, a file or this chat. If a value is needed, tell me where to set it myself.
5. After each step, compare the output with the expected output in the lab. If it does not match, stop and tell me what differs. Do not carry on or invent a fix without asking me.
6. At the end, report what passed, what failed and which cleanup you did. Then offer to tick the steps off for me. The lab page keeps ticks only in my browser, so if you cannot do that, list the steps I should tick.

This lab is for test environments only. Do not run it against production, or against a tenant or account that holds real data or real users.

You may answer in my language.

The answer: yes, one request inside an app can demand multi-factor authentication (MFA) while the others do not. In this run, GET /orders returned 200 after a password sign-in. POST /payments returned 401 until I approved a number in Microsoft Authenticator, then returned 200.

Sequence diagram: the app reads orders and gets 200, posts a payment and gets 401 with a claims challenge for c1, sends the challenge to Entra, the user approves MFA, and the same payment returns 200 with c1 in the token.
The run. Only the payment asks for more.

Setup#

You need a throwaway tenant with Microsoft Entra ID P1 or P2, a test user who is Global Administrator and has Microsoft Authenticator registered, the Azure CLI, curl, jq, openssl and Python 3.10 or newer. Never use a work or production tenant.

Every step below is a command you run yourself: Azure CLI for the app registrations, curl against Microsoft Graph and the Entra token endpoint for the rest. The only Python is api.py, the small local API you are protecting. Download it into an empty folder and work from there.

Sign in and check that the tenant has a plan for Conditional Access:

bash
export TENANT_ID="<TENANT_ID>"
export CONTEXT=c1
az login --tenant "$TENANT_ID" --allow-no-subscriptions
az rest --method get --uri https://graph.microsoft.com/v1.0/subscribedSkus \
  --query "value[?capabilityStatus=='Enabled'].servicePlans[].servicePlanName" -o tsv | grep AAD_PREMIUM

My tenant listed AAD_PREMIUM and AAD_PREMIUM_P2. If nothing comes back, stop here: the policy cannot be switched on.

The three sign-ins in this lab use the authorization code flow with PKCE. Make one verifier and its challenge now:

bash
VERIFIER=$(openssl rand -base64 48 | tr -d '=+/\n' | cut -c1-43)
PKCE=$(printf %s "$VERIFIER" | openssl dgst -sha256 -binary | openssl base64 | tr '+/' '-_' | tr -d '=\n')

Create the app registrations#

Three app registrations: the API with a Payments.Use scope, a public client that calls it, and an admin client you sign in to for the Conditional Access calls. The Azure CLI cannot get a token for those Graph permissions itself, which is why the admin client exists.

bash
export API_APP_ID=$(az ad app create --display-name lab-authctx-api \
  --sign-in-audience AzureADMyOrg --query appId -o tsv)
SCOPE_ID=$(uuidgen | tr 'A-Z' 'a-z')
cat > api-app.json <<EOF
{
  "identifierUris": ["api://$API_APP_ID"],
  "api": {
    "requestedAccessTokenVersion": 2,
    "oauth2PermissionScopes": [{
      "id": "$SCOPE_ID", "value": "Payments.Use", "type": "User", "isEnabled": true,
      "adminConsentDisplayName": "Use the lab payments API", "adminConsentDescription": "Use the lab payments API",
      "userConsentDisplayName": "Use the lab payments API", "userConsentDescription": "Use the lab payments API"
    }]
  },
  "optionalClaims": {"accessToken": [{"name": "xms_cc", "essential": false}]}
}
EOF
az rest --method patch --body @api-app.json \
  --uri "https://graph.microsoft.com/v1.0/applications(appId='$API_APP_ID')"

The optional claim xms_cc lets the API see whether a client can handle a claims challenge. Now the client and the admin app, both public clients that redirect to http://localhost:

bash
cat > client-app.json <<EOF
{
  "displayName": "lab-authctx-client", "signInAudience": "AzureADMyOrg",
  "isFallbackPublicClient": true, "publicClient": {"redirectUris": ["http://localhost"]},
  "requiredResourceAccess": [{"resourceAppId": "$API_APP_ID",
    "resourceAccess": [{"id": "$SCOPE_ID", "type": "Scope"}]}]
}
EOF
CLIENT_ID=$(az rest --method post --uri https://graph.microsoft.com/v1.0/applications \
  --body @client-app.json --query appId -o tsv)
ADMIN_ID=$(az rest --method post --uri https://graph.microsoft.com/v1.0/applications \
  --body '{"displayName":"lab-authctx-admin","signInAudience":"AzureADMyOrg","isFallbackPublicClient":true,"publicClient":{"redirectUris":["http://localhost"]}}' \
  --query appId -o tsv)
for id in "$API_APP_ID" "$CLIENT_ID" "$ADMIN_ID"; do az ad sp create --id "$id" --query displayName -o tsv; done
USER_ID=$(az ad signed-in-user show --query id -o tsv)
Entra app registrations list showing lab-authctx-admin, lab-authctx-api and lab-authctx-client.
The three apps. IDs are cropped away.

Sign in to the admin app#

Print the sign-in address, open it in your browser and consent to the permissions:

bash
GRAPH_SCOPES="https://graph.microsoft.com/Policy.Read.All https://graph.microsoft.com/Policy.ReadWrite.ConditionalAccess https://graph.microsoft.com/AuthenticationContext.ReadWrite.All"
echo "https://login.microsoftonline.com/$TENANT_ID/oauth2/v2.0/authorize?client_id=$ADMIN_ID&response_type=code&redirect_uri=http%3A%2F%2Flocalhost&code_challenge=$PKCE&code_challenge_method=S256&scope=$(jq -rn --arg s "$GRAPH_SCOPES" '$s|@uri')"

After the sign-in the browser goes to http://localhost/?code=… and shows a page that cannot be reached. That is expected: copy the value of code from the address bar, up to the next &, and exchange it for a token. The token goes into a variable and is never printed.

bash
CODE='<paste the code>'
GRAPH_TOKEN=$(curl -s "https://login.microsoftonline.com/$TENANT_ID/oauth2/v2.0/token" \
  -d client_id="$ADMIN_ID" -d grant_type=authorization_code -d code="$CODE" \
  -d code_verifier="$VERIFIER" --data-urlencode redirect_uri=http://localhost \
  --data-urlencode scope="$GRAPH_SCOPES" | jq -r .access_token)

The token is valid for about an hour. If a later Graph call answers 401, repeat this step.

Create the label and the policy#

List the authentication contexts the tenant already has. If c1 is taken, pick a free ID and set CONTEXT to it.

bash
curl -s https://graph.microsoft.com/v1.0/identity/conditionalAccess/authenticationContextClassReferences \
  -H "Authorization: Bearer $GRAPH_TOKEN" | jq -r '.value[] | "\(.id)  \(.displayName)"'

Create the label. A PATCH to a free ID creates it:

bash
curl -s -o /dev/null -w '%{http_code}\n' -X PATCH \
  "https://graph.microsoft.com/v1.0/identity/conditionalAccess/authenticationContextClassReferences/$CONTEXT" \
  -H "Authorization: Bearer $GRAPH_TOKEN" -H "Content-Type: application/json" \
  -d '{"displayName":"lab payment step-up","description":"lab-authctx","isAvailable":true}'

Then the policy. It targets that label, not an application, covers only your test user, and its only grant control is MFA. It starts in report-only:

bash
cat > policy.json <<EOF
{
  "displayName": "lab-authctx MFA for the payment context",
  "state": "enabledForReportingButNotEnforced",
  "conditions": {
    "clientAppTypes": ["all"],
    "users": {"includeUsers": ["$USER_ID"]},
    "applications": {"includeAuthenticationContextClassReferences": ["$CONTEXT"]}
  },
  "grantControls": {"operator": "OR", "builtInControls": ["mfa"]}
}
EOF
POLICY_ID=$(curl -s -X POST https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies \
  -H "Authorization: Bearer $GRAPH_TOKEN" -H "Content-Type: application/json" \
  -d @policy.json | jq -r .id)
echo "$POLICY_ID"
Terminal output of my run: licence plans AAD_PREMIUM and AAD_PREMIUM_P2, three app registrations created, authentication context c1 created and a report-only policy for the signed-in user only.
My run. Three apps, the label c1 and a report-only policy for one user.
Entra admin center, Conditional Access, Authentication contexts: one entry named lab payment step-up.
The label. One authentication context, c1, named “lab payment step-up”.

To switch the policy on, the tenant had to have security defaults off. The admin center says so on the policy page:

Policy page with Report-only selected and a warning that security defaults must be disabled before a Conditional Access policy can be enabled.
The blocker. Security defaults and Conditional Access policies do not run together.

Turning security defaults off removes a baseline protection for every user in the tenant. Do it only in a test tenant, and turn them back on after the cleanup. Then enable the policy and wait about five minutes:

bash
curl -s -o /dev/null -w '%{http_code}\n' -X PATCH \
  "https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies/$POLICY_ID" \
  -H "Authorization: Bearer $GRAPH_TOKEN" -H "Content-Type: application/json" \
  -d '{"state":"enabled"}'
Conditional Access policy lab-authctx MFA for the payment context: specific users, one authentication context included, Enable policy set to On.
Enabled. Specific users, one authentication context, policy On.

Start the API#

api.py checks the token’s signature against the tenant’s published keys, then audience, issuer, expiry and scope. GET /orders needs nothing more. POST /payments also needs the label in the token’s acrs claim and otherwise answers with a claims challenge. Run its offline self-test, then start it in the background:

bash
python3 -m pip install "pyjwt[crypto]"
python3 api.py selftest
python3 api.py > api.log 2>&1 &
API_PID=$!

All 11 offline cases passed.

The normal call#

Open a private browser window, so the first sign-in is password only. If the session has already done MFA, Entra can add the label later without a new prompt.

The sign-in asks for the API scope and sends one claims request: xms_cc with the value cp1. That is how a client tells Entra it can handle a claims challenge. prompt=login forces a fresh password sign-in.

bash
API_SCOPE="api://$API_APP_ID/Payments.Use"
CP1='{"access_token":{"xms_cc":{"values":["cp1"]}}}'
echo "https://login.microsoftonline.com/$TENANT_ID/oauth2/v2.0/authorize?client_id=$CLIENT_ID&response_type=code&redirect_uri=http%3A%2F%2Flocalhost&code_challenge=$PKCE&code_challenge_method=S256&prompt=login&scope=$(jq -rn --arg s "$API_SCOPE" '$s|@uri')&claims=$(jq -rn --arg c "$CP1" '$c|@uri')"

Entra asked me for the password and for consent to the client app. It did not ask for a second factor.

Microsoft consent screen for lab-authctx-client asking to use the lab payments API, maintain access and view the basic profile. The account name is replaced by lab user.
Consent. The client asks to use the lab payments API.

Copy the code from the address bar, get the token and call the orders endpoint:

bash
CODE='<paste the code>'
TOKEN=$(curl -s "https://login.microsoftonline.com/$TENANT_ID/oauth2/v2.0/token" \
  -d client_id="$CLIENT_ID" -d grant_type=authorization_code -d code="$CODE" \
  -d code_verifier="$VERIFIER" --data-urlencode redirect_uri=http://localhost \
  --data-urlencode scope="$API_SCOPE" | jq -r .access_token)
curl -s -i http://127.0.0.1:9310/orders -H "Authorization: Bearer $TOKEN"

The answer was 200 with {"orders": 3, "acrs_in_token": []}: a valid token, no label in it.

The payment is refused#

bash
curl -s -i -X POST http://127.0.0.1:9310/payments -H "Authorization: Bearer $TOKEN"
Terminal output of my run: GET /orders returns 200 with no acrs, POST /payments returns 401 insufficient_claims needing c1, and the decoded claims challenge.
Same token, two answers. Orders pass, the payment needs c1.

The token had no acrs value. For the payment, the API looks for c1 there. It answered 401 with a WWW-Authenticate header carrying error="insufficient_claims" and a base64-encoded claims value. Take it out of the header and decode it:

bash
CHALLENGE=$(curl -s -D - -o /dev/null -X POST http://127.0.0.1:9310/payments \
  -H "Authorization: Bearer $TOKEN" | sed -n 's/.*claims="\([^"]*\)".*/\1/p' | base64 -d)
echo "$CHALLENGE"
json
{"access_token":{"acrs":{"essential":true,"value":"c1"}}}

Entra asks for the extra factor#

The client sends that request back to Entra with a new sign-in. Merge it with the cp1 capability, print the address and open it in the same private window. This time without prompt=login, so Entra reuses the password session and asks only for what is missing:

bash
STEPUP=$(jq -cn --argjson ch "$CHALLENGE" '{access_token: ({xms_cc: {values: ["cp1"]}} + $ch.access_token)}')
echo "https://login.microsoftonline.com/$TENANT_ID/oauth2/v2.0/authorize?client_id=$CLIENT_ID&response_type=code&redirect_uri=http%3A%2F%2Flocalhost&code_challenge=$PKCE&code_challenge_method=S256&scope=$(jq -rn --arg s "$API_SCOPE" '$s|@uri')&claims=$(jq -rn --arg c "$STEPUP" '$c|@uri')"

Entra asked for the second factor:

Microsoft sign-in page titled Approve sign in request with the number 24 to enter in the Authenticator app. The account name is replaced by lab user.
The step-up. Number matching in Microsoft Authenticator.

The payment passes#

Exchange the new code and send the same payment again:

bash
CODE='<paste the new code>'
TOKEN=$(curl -s "https://login.microsoftonline.com/$TENANT_ID/oauth2/v2.0/token" \
  -d client_id="$CLIENT_ID" -d grant_type=authorization_code -d code="$CODE" \
  -d code_verifier="$VERIFIER" --data-urlencode redirect_uri=http://localhost \
  --data-urlencode scope="$API_SCOPE" | jq -r .access_token)
curl -s -i -X POST http://127.0.0.1:9310/payments -H "Authorization: Bearer $TOKEN"
curl -s -i http://127.0.0.1:9310/orders -H "Authorization: Bearer $TOKEN"
Terminal output of my run: the sign-in with the claims challenge finished after 13 seconds, POST /payments returns 200 accepted with acrs c1, and GET /orders returns 200 with acrs c1.
Accepted. The new token carries c1.

The same request now returned 200. The orders call also showed c1, because it used the newer token.

What the sign-in log shows#

I read the client app’s sign-in log through Microsoft Graph (the beta auditLogs/signIns endpoint) a few minutes after the run.

Selected sign-in log fields: at 14:13:04 a single-factor sign-in with Conditional Access not applied, and at 14:13:25 a multifactor sign-in with Conditional Access success, authentication context c1 required.
Two sign-ins. Only the second one required c1.

The step-up entry says MFA was “satisfied by claim in the token”, although I had approved a number seconds earlier. Do not read that wording as proof that no prompt appeared. The log also listed c1 on the earlier password-only sign-in as “previously satisfied”, while that token carried no acrs value. I cannot explain that, so check the claim in the token, not only the log.

What your own API has to do#

  • Validate the token first: signature, audience, issuer, expiry and scope. Only then look at acrs.
  • Answer with a claims challenge only to clients that declared the cp1 capability. api.py reads xms_cc and returns 403 otherwise.
  • Do not hard-code c1. Label IDs differ between tenants.
  • Treat the policy as part of the feature. Microsoft says a label with no policy might still be issued.

Cleanup#

Delete the policy first, then make the label unavailable and delete it. The label cannot go while Entra still knows a policy that uses it: if the last command does not return a 2xx status, wait a minute and repeat it.

bash
curl -s -o /dev/null -w '%{http_code}\n' -X DELETE \
  "https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies/$POLICY_ID" \
  -H "Authorization: Bearer $GRAPH_TOKEN"
curl -s -o /dev/null -w '%{http_code}\n' -X PATCH \
  "https://graph.microsoft.com/v1.0/identity/conditionalAccess/authenticationContextClassReferences/$CONTEXT" \
  -H "Authorization: Bearer $GRAPH_TOKEN" -H "Content-Type: application/json" -d '{"isAvailable":false}'
curl -s -o /dev/null -w '%{http_code}\n' -X DELETE \
  "https://graph.microsoft.com/v1.0/identity/conditionalAccess/authenticationContextClassReferences/$CONTEXT" \
  -H "Authorization: Bearer $GRAPH_TOKEN"

Then the app registrations, the API process and the local files:

bash
for id in "$API_APP_ID" "$CLIENT_ID" "$ADMIN_ID"; do az ad app delete --id "$id"; done
kill "$API_PID"
rm -f api-app.json client-app.json policy.json api.log
unset TOKEN GRAPH_TOKEN CODE VERIFIER

Check with separate queries that nothing is left:

bash
az rest --method get --query 'length(value)' \
  --uri "https://graph.microsoft.com/v1.0/applications?\$filter=startswith(displayName,'lab-authctx')"
az rest --method get --query 'length(value)' \
  --uri "https://graph.microsoft.com/v1.0/servicePrincipals?\$filter=startswith(displayName,'lab-authctx')"
Terminal output of my run: policy and authentication context deleted, no lab policies, contexts or app registrations left, confirmed by two separate az rest queries returning 0.
Removed. Everything the lab made is gone, and two separate queries return 0.

Deleted app registrations stay restorable in Entra for 30 days. Turn security defaults back on if the tenant used them before.

The same setup with Terraform#

You can create the label and the policy with Terraform instead of the curl calls. I tested this separately with Terraform 1.17.2, with the policy in report-only.

The usual Entra provider was not enough here. In the documentation of azuread_conditional_access_policy (version 3.10.0), the applications block takes applications or user actions, and no authentication context. main.tf therefore uses Microsoft’s msgraph provider, which sends your request body to Microsoft Graph.

hcl
resource "msgraph_resource" "policy" {
  url = "identity/conditionalAccess/policies"
  body = {
    displayName = "lab-authctx-tf MFA for the payment context"
    state       = var.policy_state
    conditions = {
      clientAppTypes = ["all"]
      users          = { includeUsers = [var.user_object_id] }
      applications   = { includeAuthenticationContextClassReferences = [var.context_id] }
    }
    grantControls = { operator = "OR", builtInControls = ["mfa"] }
  }
  depends_on = [msgraph_resource_action.context]
}

The label took three attempts:

  1. A normal resource on Graph v1.0 failed: POST returned 405, and the error listed only GET, PATCH and DELETE.
  2. On beta the label was created, but reading it back returned status 201. The provider treated that as an error, and I removed the half-made label by hand.
  3. What worked is msgraph_resource_action: a PATCH to publish the label on apply, then a PATCH to unpublish it and a DELETE on destroy.

The workaround has two limits. An action does not read the label back, so Terraform will not notice if someone changes it. And PATCH overwrites a label that already uses that ID, so pick a free one with context_id. If you already created c1 in the steps above, do not point Terraform at it.

Run it#

Terraform signs in as its own temporary app registration. Create one in the lab tenant, add these Microsoft Graph application permissions, grant admin consent, and create a short-lived client secret:

  • Policy.Read.All
  • Policy.ReadWrite.ConditionalAccess
  • AuthenticationContext.ReadWrite.All

These permissions can change Conditional Access for the whole tenant. Save the secret in a file that only you can read, outside the project folder, and keep it out of version control. Then, in the folder with main.tf:

bash
export ARM_TENANT_ID="<TENANT_ID>"
export ARM_CLIENT_ID="<APP_ID>"
export ARM_CLIENT_SECRET_FILE_PATH="<PATH_TO_SECRET_FILE>"
export ARM_USE_CLI=false
export TF_VAR_user_object_id="<TEST_USER_OBJECT_ID>"
terraform init
terraform apply
terraform plan
terraform destroy
Selected Terraform output: apply adds 4 resources, a second plan shows no changes, destroy removes 4 resources, and Graph then returns no policies, no authentication contexts and 404 for c1.
Round trip. Created, unchanged on a second plan, then removed.

When you are done, delete the temporary app registration and the secret file. I did both.

Terraform here creates only the label and the policy. The app registrations still come from the Azure CLI steps, and I did not repeat the step-up against the Terraform-made policy. It stayed in report-only; to enforce it, set policy_state to enabled, with security defaults off.

Written by Argo. Terminal output, the sign-in log and the number prompt come from the second run on 26 November 2026. That run sent the same Graph requests through one lab script, its sign-ins used the same authorization code flow through MSAL, and the script printed the short result lines in the terminal figures, so your curl output will look different. This page lists those requests one by one as commands, and api.py is that script’s API part, unchanged. The command sequence as written here has not been run in a tenant. The admin center and consent screenshots come from the first run the same day, with the same script and objects. The Terraform run was a separate test on the same day. Screenshots are cropped, and account names and identifiers are removed or replaced.

Repeat this lab#

Needs a throwaway Entra tenant with Entra ID P1 or P2, a Global Administrator test user with Microsoft Authenticator, the Azure CLI, curl, jq, openssl and Python 3.10+ for the local API (api.py). Every other step is an az or curl command. It creates three app registrations, one authentication context and one policy for your user only, then deletes them. About 30 minutes. Never use a work or production tenant.

Every value in angle brackets is a placeholder for your own test environment. Nothing on this page is a real identifier or secret.

Set your variables once

bash · env.sh
export TENANT_ID=<TENANT_ID>
export CONTEXT=c1
Step 1Sign in and check the licence

Goal. Sign in with the Azure CLI, confirm the tenant has a plan for Conditional Access and make one PKCE verifier for the sign-ins.

Prerequisites

  • Throwaway tenant, Azure CLI, curl, jq, openssl
bash · check.sh
az login --tenant "$TENANT_ID" --allow-no-subscriptions
az rest --method get --uri https://graph.microsoft.com/v1.0/subscribedSkus \
  --query "value[?capabilityStatus=='Enabled'].servicePlans[].servicePlanName" -o tsv | grep AAD_PREMIUM
VERIFIER=$(openssl rand -base64 48 | tr -d '=+/\n' | cut -c1-43)
PKCE=$(printf %s "$VERIFIER" | openssl dgst -sha256 -binary | openssl base64 | tr '+/' '-_' | tr -d '=\n')

Expected output

output
AAD_PREMIUM
AAD_PREMIUM_P2
Step 2Create the three app registrations

Goal. The API with the Payments.Use scope and the xms_cc optional claim, a public client and an admin client for the Conditional Access calls.

Prerequisites

  • The check step listed an AAD_PREMIUM plan
bash · apps.sh
export API_APP_ID=$(az ad app create --display-name lab-authctx-api \
  --sign-in-audience AzureADMyOrg --query appId -o tsv)
SCOPE_ID=$(uuidgen | tr 'A-Z' 'a-z')
cat > api-app.json <<EOF
{
  "identifierUris": ["api://$API_APP_ID"],
  "api": {
    "requestedAccessTokenVersion": 2,
    "oauth2PermissionScopes": [{
      "id": "$SCOPE_ID", "value": "Payments.Use", "type": "User", "isEnabled": true,
      "adminConsentDisplayName": "Use the lab payments API", "adminConsentDescription": "Use the lab payments API",
      "userConsentDisplayName": "Use the lab payments API", "userConsentDescription": "Use the lab payments API"
    }]
  },
  "optionalClaims": {"accessToken": [{"name": "xms_cc", "essential": false}]}
}
EOF
az rest --method patch --body @api-app.json \
  --uri "https://graph.microsoft.com/v1.0/applications(appId='$API_APP_ID')"
cat > client-app.json <<EOF
{
  "displayName": "lab-authctx-client", "signInAudience": "AzureADMyOrg",
  "isFallbackPublicClient": true, "publicClient": {"redirectUris": ["http://localhost"]},
  "requiredResourceAccess": [{"resourceAppId": "$API_APP_ID",
    "resourceAccess": [{"id": "$SCOPE_ID", "type": "Scope"}]}]
}
EOF
CLIENT_ID=$(az rest --method post --uri https://graph.microsoft.com/v1.0/applications \
  --body @client-app.json --query appId -o tsv)
ADMIN_ID=$(az rest --method post --uri https://graph.microsoft.com/v1.0/applications \
  --body '{"displayName":"lab-authctx-admin","signInAudience":"AzureADMyOrg","isFallbackPublicClient":true,"publicClient":{"redirectUris":["http://localhost"]}}' \
  --query appId -o tsv)
for id in "$API_APP_ID" "$CLIENT_ID" "$ADMIN_ID"; do az ad sp create --id "$id" --query displayName -o tsv; done
USER_ID=$(az ad signed-in-user show --query id -o tsv)

Expected output

output
lab-authctx-api
lab-authctx-client
lab-authctx-admin
Step 3Sign in to the admin app

Goal. Open the printed address, consent to the three Graph permissions, copy the code from the localhost address bar and exchange it for a Graph token.

Prerequisites

  • The three app registrations exist
bash · admin-url.sh
GRAPH_SCOPES="https://graph.microsoft.com/Policy.Read.All https://graph.microsoft.com/Policy.ReadWrite.ConditionalAccess https://graph.microsoft.com/AuthenticationContext.ReadWrite.All"
echo "https://login.microsoftonline.com/$TENANT_ID/oauth2/v2.0/authorize?client_id=$ADMIN_ID&response_type=code&redirect_uri=http%3A%2F%2Flocalhost&code_challenge=$PKCE&code_challenge_method=S256&scope=$(jq -rn --arg s "$GRAPH_SCOPES" '$s|@uri')"
bash · admin-token.sh
CODE='<paste the code>'
GRAPH_TOKEN=$(curl -s "https://login.microsoftonline.com/$TENANT_ID/oauth2/v2.0/token" \
  -d client_id="$ADMIN_ID" -d grant_type=authorization_code -d code="$CODE" \
  -d code_verifier="$VERIFIER" --data-urlencode redirect_uri=http://localhost \
  --data-urlencode scope="$GRAPH_SCOPES" | jq -r .access_token)

Expected output

output
https://login.microsoftonline.com/<TENANT_ID>/oauth2/v2.0/authorize?client_id=...
(no output from the token request: the token stays in GRAPH_TOKEN)
Step 4Create the label and the policy

Goal. List the existing authentication contexts, create yours and a report-only policy for your user only.

Prerequisites

  • A Graph token in GRAPH_TOKEN
bash · contexts.sh
curl -s https://graph.microsoft.com/v1.0/identity/conditionalAccess/authenticationContextClassReferences \
  -H "Authorization: Bearer $GRAPH_TOKEN" | jq -r '.value[] | "\(.id)  \(.displayName)"'
bash · context.sh
curl -s -o /dev/null -w '%{http_code}\n' -X PATCH \
  "https://graph.microsoft.com/v1.0/identity/conditionalAccess/authenticationContextClassReferences/$CONTEXT" \
  -H "Authorization: Bearer $GRAPH_TOKEN" -H "Content-Type: application/json" \
  -d '{"displayName":"lab payment step-up","description":"lab-authctx","isAvailable":true}'
bash · policy.sh
cat > policy.json <<EOF
{
  "displayName": "lab-authctx MFA for the payment context",
  "state": "enabledForReportingButNotEnforced",
  "conditions": {
    "clientAppTypes": ["all"],
    "users": {"includeUsers": ["$USER_ID"]},
    "applications": {"includeAuthenticationContextClassReferences": ["$CONTEXT"]}
  },
  "grantControls": {"operator": "OR", "builtInControls": ["mfa"]}
}
EOF
POLICY_ID=$(curl -s -X POST https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies \
  -H "Authorization: Bearer $GRAPH_TOKEN" -H "Content-Type: application/json" \
  -d @policy.json | jq -r .id)
echo "$POLICY_ID"

Expected output

output
a 2xx status for the label
the new policy ID
Step 5Enable the policy

Goal. Turn security defaults off in this test tenant first, then enable the policy and wait about five minutes.

Prerequisites

  • Security defaults are off in the test tenant
bash · enable.sh
curl -s -o /dev/null -w '%{http_code}\n' -X PATCH \
  "https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies/$POLICY_ID" \
  -H "Authorization: Bearer $GRAPH_TOKEN" -H "Content-Type: application/json" \
  -d '{"state":"enabled"}'

Expected output

output
a 2xx status
Step 6Start the API

Goal. Download api.py from https://iamops.dev/lab-files/entra-auth-context-step-up-mfa/api.py, run its offline self-test and start it in the background.

Prerequisites

  • Python 3.10 or newer
bash · api.sh
python3 -m pip install "pyjwt[crypto]"
python3 api.py selftest
python3 api.py > api.log 2>&1 &
API_PID=$!

Expected output

output
11/11 offline checks passed
Step 7Make the normal call

Goal. Open the address in a private browser window so you sign in with a password only, then exchange the code and read the orders.

Prerequisites

  • The policy has been on for five minutes and the API is running
bash · normal-url.sh
API_SCOPE="api://$API_APP_ID/Payments.Use"
CP1='{"access_token":{"xms_cc":{"values":["cp1"]}}}'
echo "https://login.microsoftonline.com/$TENANT_ID/oauth2/v2.0/authorize?client_id=$CLIENT_ID&response_type=code&redirect_uri=http%3A%2F%2Flocalhost&code_challenge=$PKCE&code_challenge_method=S256&prompt=login&scope=$(jq -rn --arg s "$API_SCOPE" '$s|@uri')&claims=$(jq -rn --arg c "$CP1" '$c|@uri')"
bash · normal.sh
CODE='<paste the code>'
TOKEN=$(curl -s "https://login.microsoftonline.com/$TENANT_ID/oauth2/v2.0/token" \
  -d client_id="$CLIENT_ID" -d grant_type=authorization_code -d code="$CODE" \
  -d code_verifier="$VERIFIER" --data-urlencode redirect_uri=http://localhost \
  --data-urlencode scope="$API_SCOPE" | jq -r .access_token)
curl -s -i http://127.0.0.1:9310/orders -H "Authorization: Bearer $TOKEN"

Expected output

output
HTTP/1.0 200 OK
...
{"orders": 3, "acrs_in_token": []}
Step 8Try the payment

Goal. The API refuses it with a claims challenge for the label. Decode the challenge from the header.

Prerequisites

  • The normal call returned 200
bash · payment.sh
curl -s -i -X POST http://127.0.0.1:9310/payments -H "Authorization: Bearer $TOKEN"
bash · challenge.sh
CHALLENGE=$(curl -s -D - -o /dev/null -X POST http://127.0.0.1:9310/payments \
  -H "Authorization: Bearer $TOKEN" | sed -n 's/.*claims="\([^"]*\)".*/\1/p' | base64 -d)
echo "$CHALLENGE"

Expected output

output
HTTP/1.0 401 Unauthorized
WWW-Authenticate: Bearer realm="", authorization_uri="...", error="insufficient_claims", claims="..."
{"error": "insufficient_claims", "needs": "c1"}
{"access_token":{"acrs":{"essential":true,"value":"c1"}}}
Step 9Step up and repeat the payment

Goal. Open the new address in the same private window, approve the prompt in Microsoft Authenticator, exchange the code and send the payment again.

Prerequisites

  • The decoded challenge in CHALLENGE
bash · stepup-url.sh
STEPUP=$(jq -cn --argjson ch "$CHALLENGE" '{access_token: ({xms_cc: {values: ["cp1"]}} + $ch.access_token)}')
echo "https://login.microsoftonline.com/$TENANT_ID/oauth2/v2.0/authorize?client_id=$CLIENT_ID&response_type=code&redirect_uri=http%3A%2F%2Flocalhost&code_challenge=$PKCE&code_challenge_method=S256&scope=$(jq -rn --arg s "$API_SCOPE" '$s|@uri')&claims=$(jq -rn --arg c "$STEPUP" '$c|@uri')"
bash · stepup.sh
CODE='<paste the new code>'
TOKEN=$(curl -s "https://login.microsoftonline.com/$TENANT_ID/oauth2/v2.0/token" \
  -d client_id="$CLIENT_ID" -d grant_type=authorization_code -d code="$CODE" \
  -d code_verifier="$VERIFIER" --data-urlencode redirect_uri=http://localhost \
  --data-urlencode scope="$API_SCOPE" | jq -r .access_token)
curl -s -i -X POST http://127.0.0.1:9310/payments -H "Authorization: Bearer $TOKEN"
curl -s -i http://127.0.0.1:9310/orders -H "Authorization: Bearer $TOKEN"

Expected output

output
HTTP/1.0 200 OK
...
{"payment": "accepted", "acrs_in_token": ["c1"]}
HTTP/1.0 200 OK
...
{"orders": 3, "acrs_in_token": ["c1"]}
Step 10Delete everything

Goal. Remove the policy, the label, the apps, the API process and the local files, then check that nothing is left. Turn security defaults back on if the tenant used them.

Prerequisites

  • Finished with the lab
bash · cleanup-graph.sh
curl -s -o /dev/null -w '%{http_code}\n' -X DELETE \
  "https://graph.microsoft.com/v1.0/identity/conditionalAccess/policies/$POLICY_ID" \
  -H "Authorization: Bearer $GRAPH_TOKEN"
curl -s -o /dev/null -w '%{http_code}\n' -X PATCH \
  "https://graph.microsoft.com/v1.0/identity/conditionalAccess/authenticationContextClassReferences/$CONTEXT" \
  -H "Authorization: Bearer $GRAPH_TOKEN" -H "Content-Type: application/json" -d '{"isAvailable":false}'
curl -s -o /dev/null -w '%{http_code}\n' -X DELETE \
  "https://graph.microsoft.com/v1.0/identity/conditionalAccess/authenticationContextClassReferences/$CONTEXT" \
  -H "Authorization: Bearer $GRAPH_TOKEN"
bash · cleanup-apps.sh
for id in "$API_APP_ID" "$CLIENT_ID" "$ADMIN_ID"; do az ad app delete --id "$id"; done
kill "$API_PID"
rm -f api-app.json client-app.json policy.json api.log
unset TOKEN GRAPH_TOKEN CODE VERIFIER
bash · verify.sh
az rest --method get --query 'length(value)' \
  --uri "https://graph.microsoft.com/v1.0/applications?\$filter=startswith(displayName,'lab-authctx')"
az rest --method get --query 'length(value)' \
  --uri "https://graph.microsoft.com/v1.0/servicePrincipals?\$filter=startswith(displayName,'lab-authctx')"

Expected output

output
2xx status for the policy, the label update and the label
0
0

Sources#

Discuss this on X or LinkedIn

Follow on X

New posts by email

One email a week with new posts and labs. Unsubscribe anytime.

Your address is stored with Kit, which sends the emails. Details

Related research and labs

Type to search every page. Use the arrow keys to move through the results.

    Open the full search page