TL;DR
- With one authentication context and one policy, reading orders worked after a password-only sign-in while the payment was refused.
- The application programming interface (API) answered the payment with a 401 claims challenge. Sending it back to Entra produced the Authenticator prompt.
- After approval the token carried c1 and the payment returned 200. The step-up took 13 seconds, including my approval.
- Conditional Access could not be switched on while security defaults were enabled. To see the prompt, start from a password-only session.
- The label and the policy also work from Terraform, through Microsoft's msgraph provider.
Repeat this lab
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.
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.
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:
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_PREMIUMMy 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:
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.
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:
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)
Sign in to the admin app#
Print the sign-in address, open it in your browser and consent to the permissions:
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.
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.
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:
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:
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"
c1 and a report-only policy for one user.
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:

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:
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"}'
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:
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.
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.

Copy the code from the address bar, get the token and call the orders endpoint:
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#
curl -s -i -X POST http://127.0.0.1:9310/payments -H "Authorization: Bearer $TOKEN"
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:
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"{"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:
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:

The payment passes#
Exchange the new code and send the same payment again:
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"
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.

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
cp1capability.api.pyreadsxms_ccand returns403otherwise. - 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.
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:
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 VERIFIERCheck with separate queries that nothing is left:
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')"
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.
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:
- A normal resource on Graph
v1.0failed:POSTreturned405, and the error listed onlyGET,PATCHandDELETE. - On
betathe label was created, but reading it back returned status201. The provider treated that as an error, and I removed the half-made label by hand. - What worked is
msgraph_resource_action: aPATCHto publish the label on apply, then aPATCHto unpublish it and aDELETEon 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.AllPolicy.ReadWrite.ConditionalAccessAuthenticationContext.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:
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
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
export TENANT_ID=<TENANT_ID>
export CONTEXT=c1 0 of 10 steps done
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
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
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
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
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
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')" 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
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
curl -s https://graph.microsoft.com/v1.0/identity/conditionalAccess/authenticationContextClassReferences \
-H "Authorization: Bearer $GRAPH_TOKEN" | jq -r '.value[] | "\(.id) \(.displayName)"' 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}' 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
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
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
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
python3 -m pip install "pyjwt[crypto]"
python3 api.py selftest
python3 api.py > api.log 2>&1 &
API_PID=$! Expected 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
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')" 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
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
curl -s -i -X POST http://127.0.0.1:9310/payments -H "Authorization: Bearer $TOKEN" 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
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
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')" 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
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
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" 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 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
2xx status for the policy, the label update and the label
0
0 Sources#
This post as Markdown · RSS · JSON feed
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