# 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.

- URL: https://iamops.dev/entra-auth-context-step-up-mfa/
- Language: en
- Author: Argo
- Published: 2026-11-26
- Category: Labs
- Depth: Practitioner
- Audience: Engineers and operators
- Time: 16 min
- Topics: Conditional Access, Entra ID, MFA, Step-up, Labs

## TL;DR

- With one [authentication context](https://iamops.dev/entra-auth-context-step-up-mfa/#create-the-label-and-the-policy) and one policy, [reading orders](https://iamops.dev/entra-auth-context-step-up-mfa/#the-normal-call) 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](https://iamops.dev/entra-auth-context-step-up-mfa/#the-payment-is-refused). Sending it back to Entra produced the [Authenticator prompt](https://iamops.dev/entra-auth-context-step-up-mfa/#entra-asks-for-the-extra-factor).
- After approval the token carried c1 and the [payment returned 200](https://iamops.dev/entra-auth-context-step-up-mfa/#the-payment-passes). The step-up took 13 seconds, including my approval.
- Conditional Access [could not be switched on](https://iamops.dev/entra-auth-context-step-up-mfa/#create-the-label-and-the-policy) while security defaults were enabled. To see the prompt, [start from a password-only session](https://iamops.dev/entra-auth-context-step-up-mfa/#the-normal-call).
- The label and the policy also work [from Terraform](https://iamops.dev/entra-auth-context-step-up-mfa/#the-same-setup-with-terraform), through Microsoft's msgraph provider.

**Audience: Practitioners.** For people who build or run apps on Microsoft Entra. New to the idea? Read the short explainer first: [Entra authentication context, extra <abbr title="multi-factor authentication">MFA</abbr> for one risky action](https://iamops.dev/entra-authentication-context-explained/).

**The answer:** yes, one request inside an app can demand multi-factor authentication (<abbr title="multi-factor authentication">MFA</abbr>) 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.](https://iamops.dev/img/entra-auth-context-step-up-mfa-flow.svg)

*The run. Only the payment asks for more.*

## Setup

You need a throwaway tenant with Microsoft Entra <abbr title="identifier">ID</abbr> P1 or P2, a test user who is Global Administrator and has Microsoft Authenticator registered, the Azure <abbr title="command-line interface">CLI</abbr>, `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](https://iamops.dev/lab-files/entra-auth-context-step-up-mfa/api.py), the small local <abbr title="Application Programming Interface">API</abbr> 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 <abbr title="Proof Key for Code Exchange">PKCE</abbr>. 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.](https://iamops.dev/media/entra-auth-context-step-up-mfa/portal-apps.webp)

*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 <abbr title="multi-factor authentication">MFA</abbr>. 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.](https://iamops.dev/media/entra-auth-context-step-up-mfa/01-setup.webp)

*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.](https://iamops.dev/media/entra-auth-context-step-up-mfa/portal-contexts.webp)

*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.](https://iamops.dev/media/entra-auth-context-step-up-mfa/portal-security-defaults.webp)

*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.](https://iamops.dev/media/entra-auth-context-step-up-mfa/portal-policy-on.webp)

*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 <abbr title="multi-factor authentication">MFA</abbr>, 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.](https://iamops.dev/media/entra-auth-context-step-up-mfa/consent-client.webp)

*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.](https://iamops.dev/media/entra-auth-context-step-up-mfa/02-calls.webp)

*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.](https://iamops.dev/media/entra-auth-context-step-up-mfa/mfa-prompt.webp)

*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.](https://iamops.dev/media/entra-auth-context-step-up-mfa/03-step-up.webp)

*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.](https://iamops.dev/media/entra-auth-context-step-up-mfa/05-signin-log.webp)

*Two sign-ins. Only the second one required c1.*

The step-up entry says <abbr title="multi-factor authentication">MFA</abbr> 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.](https://iamops.dev/media/entra-auth-context-step-up-mfa/04-cleanup.webp)

*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`](https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/conditional_access_policy) (version 3.10.0), the applications block takes applications or user actions, and no authentication context. [main.tf](https://iamops.dev/lab-files/entra-auth-context-step-up-mfa/main.tf) therefore uses Microsoft's [msgraph provider](https://registry.terraform.io/providers/microsoft/msgraph/latest/docs), 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.](https://iamops.dev/media/entra-auth-context-step-up-mfa/06-terraform.webp)

*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 <abbr title="Microsoft Authentication Library">MSAL</abbr>, 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** `env.sh` (bash)

```bash
export TENANT_ID=<TENANT_ID>
export CONTEXT=c1
```

### Step 1: Sign 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

`check.sh` (bash)

```bash
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**

```text
AAD_PREMIUM
AAD_PREMIUM_P2
```

### Step 2: Create 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

`apps.sh` (bash)

```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')"
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**

```text
lab-authctx-api
lab-authctx-client
lab-authctx-admin
```

### Step 3: Sign 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

`admin-url.sh` (bash)

```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')"
```

`admin-token.sh` (bash)

```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)
```

**Expected output**

```text
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 4: Create 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

`contexts.sh` (bash)

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

`context.sh` (bash)

```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}'
```

`policy.sh` (bash)

```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"
```

**Expected output**

```text
a 2xx status for the label
the new policy ID
```

### Step 5: Enable 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

`enable.sh` (bash)

```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"}'
```

**Expected output**

```text
a 2xx status
```

### Step 6: Start 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

`api.sh` (bash)

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

**Expected output**

```text
11/11 offline checks passed
```

### Step 7: Make 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

`normal-url.sh` (bash)

```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')"
```

`normal.sh` (bash)

```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"
```

**Expected output**

```text
HTTP/1.0 200 OK
...
{"orders": 3, "acrs_in_token": []}
```

### Step 8: Try 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

`payment.sh` (bash)

```bash
curl -s -i -X POST http://127.0.0.1:9310/payments -H "Authorization: Bearer $TOKEN"
```

`challenge.sh` (bash)

```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"
```

**Expected output**

```text
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 9: Step 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-url.sh` (bash)

```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')"
```

`stepup.sh` (bash)

```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"
```

**Expected output**

```text
HTTP/1.0 200 OK
...
{"payment": "accepted", "acrs_in_token": ["c1"]}
HTTP/1.0 200 OK
...
{"orders": 3, "acrs_in_token": ["c1"]}
```

### Step 10: Delete 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

`cleanup-graph.sh` (bash)

```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"
```

`cleanup-apps.sh` (bash)

```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
```

`verify.sh` (bash)

```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')"
```

**Expected output**

```text
2xx status for the policy, the label update and the label
0
0
```


## Sources

- [Microsoft Learn, Developer guidance for Conditional Access authentication context](https://learn.microsoft.com/en-us/entra/identity-platform/developer-guide-conditional-access-authentication-context)
- [Microsoft Learn, Claims challenges, claims requests and client capabilities](https://learn.microsoft.com/en-us/entra/identity-platform/claims-challenge)
- [Terraform Registry, microsoft/msgraph provider](https://registry.terraform.io/providers/microsoft/msgraph/latest/docs)
- [Terraform Registry, azuread_conditional_access_policy](https://registry.terraform.io/providers/hashicorp/azuread/latest/docs/resources/conditional_access_policy)

Discuss: [X](https://x.com/iamopsdev) | [LinkedIn](https://www.linkedin.com/company/iamops-dev/)
