IAM Labs
← All hands-on guides

OAuth 2.0 in Entra ID · Part 2 of 7

Authorization code flow with PKCE

FreeIntermediate25 min read + 20 min lab2026-10-19

The authorization code flow with PKCE is how an app used by a real person gets a badge from Entra ID safely, even when the app cannot keep a secret. It is the flow Microsoft recommends for every web, single-page, mobile and desktop app that signs people in.

Part 1 explained the visitor badge idea. This part follows one badge from start to finish, using a small app you can run yourself: the Contoso Employee Directory, where an employee searches for a colleague and sees their job title, manager and team.

By the end you will have:

  • understood the flow in plain words, then step by step;
  • made the design choices an identity engineer makes before building it;
  • set up the Employee Directory app in your own Entra ID tenant;
  • watched the raw flow in PowerShell, read the tokens it returns, and seen how refresh tokens keep the app connected until an administrator takes that access away.

In plain words: a cloakroom ticket with a secret half

The flow gets its name from a short-lived code that Entra ID hands out before the real badge. Think of a cloakroom at a busy event.

  1. You hand in your coat and receive a ticket. The ticket is not the coat; it only proves you may collect it.
  2. Later, you swap the ticket at the counter for your coat.

In OAuth, the authorization code is the ticket and the access token is the coat. Entra ID gives the app the ticket first, through the browser, then the app swaps it for the token directly with Entra ID.

The weakness: tickets can be picked up

The ticket travels through the browser address bar, where another program could spot it. If a stranger grabs the ticket first, they could collect your coat.

The fix: PKCE, the secret half

PKCE (Proof Key for Code Exchange, pronounced “pixie”) closes that gap. Before asking for a ticket, the app makes up a random secret and keeps it to itself. It shows the cloakroom only a fingerprint of that secret.

When the app swaps the ticket, it must show the original secret. The counter checks it matches the fingerprint it saw earlier. A stranger holding only the ticket has no secret, so the swap fails.

Plain wordsTechnical nameWho holds it
Cloakroom ticketAuthorization codeTravels through the browser, valid for minutes, single use
The coatAccess tokenThe app, for about an hour
Secret halfCode verifierOnly the app, never sent until the swap
Fingerprint of the secretCode challenge (SHA-256 hash)Sent to Entra ID at the start

The Contoso example: an employee directory

Contoso’s intranet has a Find a colleague page. Divya, an IAM Analyst, types “Ravi” and sees Ravi’s name and email. In org chart mode she also sees his job title, his manager and his team.

The page stores no passwords and keeps no copy of the directory. Each time, it asks Entra ID for permission to read the directory on Divya’s behalf, then calls Microsoft Graph with the badge it receives.

In the storyOAuth roleIn the lab
Divya, the employeeResource ownerA test user in your tenant
Employee Directory pageClient (public, browser app)One HTML file using MSAL.js
Entra IDAuthorization serverYour tenant’s login.microsoftonline.com endpoint
Company directoryResource serverMicrosoft Graph

Two modes, two kinds of consent

The app is built in two stages, because each one teaches a different kind of consent.

ModeScopes requestedWhat Divya seesWho can consent
BasicUser.Read, User.ReadBasic.AllNames and emailsDivya herself
Org chartadds User.Read.AllJob title, department, manager, teamAn administrator only

When Divya switches to Org chart mode before an admin has approved it, Entra ID shows her a Need admin approval screen. Once an admin grants consent for the tenant, the same switch just works.

The flow, step by step

When Divya clicks Connect to Directory, ten steps run in about two seconds. Only step 4 needs her, and her password goes only to Entra ID.

Authorization code flow with PKCE in 10 steps

  1. Clicks Connect. Divya asks the Directory app to read the company directory for her.
  2. Makes secret + fingerprint. The app creates a random secret (code verifier) and hashes it into a fingerprint (code challenge). The secret never leaves the app yet.
  3. Sends fingerprint. The app sends Divya’s browser to Entra ID with its client ID, the scopes it wants, its redirect address, a random state value and the fingerprint.
  4. Signs in, MFA, consents. Entra ID checks Divya’s password, MFA and Conditional Access, then asks her to approve the scopes.
  5. Returns one-time code. Entra ID sends the browser back to the app’s redirect address with a short-lived code and the same state.
  6. Sends code + secret. The app posts the code and the original secret directly to Entra ID’s token endpoint.
  7. Secret matches fingerprint? Entra ID hashes the secret and compares it with the fingerprint from step 3. No match, no token.
  8. Issues access token. Entra ID returns an access token for Microsoft Graph, valid for about an hour.
  9. Calls Graph with token. The app searches the directory, showing the token as its badge.
  10. Returns directory data. Graph checks the badge and returns only what Divya herself is allowed to see.

Why PKCE matters: the attack it stops

PKCE stops a stolen code from becoming a stolen badge. Without it, anyone who grabs the code during the redirect could swap it for an access token.

The risk is real for apps that cannot hide a secret. A browser page or a mobile app ships its code to every user, so a “client secret” inside it is not secret at all. Before PKCE, a malicious app on the same phone could register the same redirect address, catch the code and redeem it.

With PKCE, the code is useless on its own:

  • The attacker sees the code and the challenge (the fingerprint), but never the verifier (the secret).
  • A SHA-256 fingerprint cannot be reversed to recover the secret.
  • Entra ID refuses to swap a code unless the verifier matches the challenge sent at the start.

PKCE began as a fix for mobile apps. It is now the recommended default for every app using the authorization code flow, including web apps that also hold a client secret. Microsoft’s MSAL libraries add it automatically.

Design decisions before you build

Five decisions shape the whole implementation. Making them first avoids most of the errors in the troubleshooting section.

1. Which flow?

A person is present in a browser and the app acts for them, so the answer is the authorization code flow with PKCE.

OptionWhy not here
Client credentialsApp-only access with no user: the app could read every user’s data, and nobody signs in
Device codeMeant for devices with no browser or keyboard
Implicit flowRetired: tokens were returned in the URL with no code swap and no PKCE
Password (ROPC)The app collects the password itself, which skips MFA and Conditional Access

2. Which client type and platform?

Entra ID decides how to treat an app from which platform its redirect URI is registered under. This single setting decides whether a secret is required.

Platform in Entra IDClient typeToken swap needsUsed in this lab for
Single-page applicationPublic, browser onlyPKCE, from a browser (cross-origin request)Employee Directory page
Mobile and desktop applicationsPublicPKCE onlyPowerShell walkthrough
WebConfidentialPKCE plus a client secret or certificateA server-side app, e.g. Next.js

One app registration can hold several platforms, as this lab does. Each redirect URI must stay unique, as the troubleshooting section shows.

3. Which scopes?

Ask for the least the app needs. Basic mode needs only User.Read and User.ReadBasic.All, which any user can consent to. Org chart mode adds User.Read.All, which needs admin consent, so it is requested only when the user switches mode.

4. Who consents?

Let users consent to low-risk scopes themselves. Keep tenant-wide or sensitive scopes behind admin consent, and consider the admin consent workflow so users can request approval instead of hitting a dead end.

5. Where do tokens live?

The directory page keeps tokens in the browser tab’s session storage, which clears when the tab closes. Access tokens last about an hour. A server-side app would keep tokens on the server instead and never send them to the browser.

Quick setup: the Employee Directory in your tenant

The whole lab runs in about 20 minutes with an Entra ID tenant (P1 or P2 trial is enough, no Microsoft 365 licence needed), PowerShell 7 and Node.js.

Lab files: index.html · New-DirectoryTestUsers.ps1 · users.csv · Invoke-AuthCodeFlow.ps1

Step 1. Register the app

  1. Entra admin center → App registrations → New registration. Name it Contoso Employee Directory, choose Accounts in this organizational directory only.
  2. Authentication → Add a platform → Single-page application. Redirect URI: http://localhost:3000.
  3. API permissions → Microsoft Graph → Delegated: add User.Read and User.ReadBasic.All. Do not grant admin consent yet.
  4. Note the Application (client) ID and Directory (tenant) ID from the Overview page.

Step 2. Create test users with a reporting line

Run the provided New-DirectoryTestUsers.ps1 with its users.csv. It creates 10 users with job titles, departments and managers, and saves their passwords to created-users.csv for the lab.

Install-Module Microsoft.Graph -Scope CurrentUser
.\New-DirectoryTestUsers.ps1            # create users and managers
.\New-DirectoryTestUsers.ps1 -Remove    # clean up after the lab

The CSV builds a four-level chart: CEO → Head of IT → IAM Team Lead (Ravi) → IAM Analyst (Divya).

Step 3. Configure and run the page

  1. Download index.html and put it in its own folder, for example C:\Labs\EmpDirectory.
  2. Near the bottom of the file, set clientId and tenantId in the CONFIG block.
  3. Start a local web server in that folder and open http://localhost:3000:
npx serve -l 3000 .

Open the file through the server, not by double-clicking it: a file:// page cannot receive the redirect from Entra ID.

Step 4. Try the four scenarios

ScenarioSign in asWhat you should see
Basic searchDivya, in a private windowConsent screen, then names and emails
Org chart without approvalDivyaNeed admin approval; the page falls back to Basic
Org chart after approvalAdmin grants consent for User.Read.All, then DivyaRavi with Vikram above and Divya below
Guest userA B2B guest403 on search: delegated access follows the user’s own rights

The page’s What just happened panel numbers every step as it runs, and The access token panel decodes the badge. Both are ready-made screenshots for your notes.

See the raw flow: PowerShell, step by step

MSAL hides the flow inside a library. The Invoke-AuthCodeFlow.ps1 script does every step by hand, so you can see the code, the verifier and the tokens yourself.

One extra platform

In the same app registration, go to Authentication → Add a platform → Mobile and desktop applications and add the custom redirect URI http://localhost:8400/callback. Then run:

.\Invoke-AuthCodeFlow.ps1 -TenantId <tenant-id> -ClientId <client-id>

What each step prints

StepWhat happensWhat you see
1. Create the secretRandom code_verifier, its SHA-256 code_challenge, and a random stateThe challenge in full, the verifier cut short
2. AuthorizeBrowser opens Entra ID’s /authorize with client ID, scopes, redirect URI, state and challengeThe full URL
3. Catch the codeDivya signs in; Entra ID redirects to localhost:8400/callback?code=…&state=…The code, and a check that state matches
4. Swap the codeScript posts the code and the verifier to /tokenWhich tokens came back
5. Read the badgeDecodes the access tokenaud, scp, upn, exp
6. Use the badgeCalls Graph /me and searches for “ravi”Divya’s name and the search results

The heart of PKCE is three lines in step 1:

$verifier  = New-RandomString 64
$hash      = [Security.Cryptography.SHA256]::Create().ComputeHash([Text.Encoding]::ASCII.GetBytes($verifier))
$challenge = [Convert]::ToBase64String($hash).TrimEnd('=').Replace('+','-').Replace('/','_')

The challenge goes out in step 2. The verifier stays in the script until step 4, where Entra ID hashes it again and compares.

The request MSAL builds for you

The directory page sends the same request, with a few extras added by MSAL:

Part of the URLGroupMeaning
client_id, response_type=code, redirect_uri, scope, stateOAuthWho is asking, for what, and where to send the code
code_challenge, code_challenge_method=S256PKCEThe fingerprint of the secret
openid profile offline_access, nonceOIDCAdded by MSAL: an ID token, a refresh token and replay protection
response_mode=fragment, prompt=select_accountBehaviourCode returns after #; always show the account picker
client-request-id, client_info, x-client-SKU, x-client-VERMicrosoft extrasCorrelation and library details, not part of the standard

What the tokens taught us

Running the script twice, once as plain OAuth and once with -Oidc, shows exactly what each scope adds.

Run 1: plain OAuthRun 2: with -Oidc
RequestedUser.Read User.ReadBasic.Alladds openid profile offline_access
Access tokenYes, for Microsoft GraphYes, for Microsoft Graph
ID tokenNoYes, for the app: who signed in
Refresh tokenNoYes, renews access without a new sign-in

Four lessons from the output

  • Requested scopes are not granted scopes. The access token lists every Graph permission already consented for this app and user, not just the ones asked for this time. That is why openid profile email appeared in Run 1 even without asking.
  • Consent is per user unless an admin grants it for everyone. User.Read.All appeared for the admin but not for a test user, because only the admin had consented.
  • offline_access is not a permission on the token. Its only effect is that a refresh token comes back.
  • Token lifetimes vary on purpose. Entra ID randomizes access token lifetime, typically 60 to 90 minutes, so tokens issued together do not all expire at once.

Reading the badge

Paste the access token into jwt.ms, or read the directory page’s token panel.

ClaimExample valueMeaning
aud00000003-0000-0000-c000-000000000000The badge is for Microsoft Graph, not for the app
scpUser.Read User.ReadBasic.AllWhat the badge allows
upndivya.pillai@contoso.onmicrosoft.comWhose behalf the app acts on
appidThe app’s client IDWhich app holds the badge
expAbout an hour after issueWhen the badge stops working

The app itself should never trust the access token as proof of who signed in. That is the ID token’s job, which is why Microsoft libraries always request OIDC alongside OAuth.

Staying connected: refresh tokens

An access token lasts about an hour. A refresh token lets the app get a new one without asking Divya to sign in again, for as long as the refresh token stays valid.

In the cloakroom story, the refresh token is a renewal slip. When the coat ticket expires, the app hands the slip to the counter and receives a fresh badge, plus a fresh slip. Divya is not disturbed.

When you get one

Only when the app asks for offline_access. That is why Run 1 returned no refresh token and Run 2 did. MSAL adds offline_access automatically, so the Employee Directory page always has one.

How the app uses it

  • Directory page. Before every Graph call, MSAL first reuses the cached access token. When that has expired, it silently swaps the refresh token for a new one. The trace panel shows Got a fresh access token silently, using the refresh token.
  • PowerShell. After running the script with -Oidc, swap the refresh token by hand:
$new = Invoke-RestMethod -Method Post -Uri "https://login.microsoftonline.com/<tenant-id>/oauth2/v2.0/token" -Body @{
  client_id     = "<client-id>"
  grant_type    = "refresh_token"
  refresh_token = $EntraToken.refresh_token
  scope         = "User.Read User.ReadBasic.All offline_access"
}
$new.access_token   # a brand-new badge, no sign-in
$new.refresh_token  # a new slip: always keep the newest one

No password, no browser and no PKCE this time: the refresh token itself is the proof.

How long it lasts

TokenTypical lifetimeNotes
Access token60 to 90 minutesRandomized; cannot be cancelled early by most APIs
Refresh token, single-page app24 hoursBrowser apps must sign in again daily
Refresh token, other appsUp to 90 daysRenewed each time it is used

Conditional Access can shorten this, for example a sign-in frequency policy that asks for a fresh sign-in every 8 hours.

Taking access away

This is the part administrators care about most. Refresh tokens stop working when:

  • an admin revokes the user’s sessions (Entra admin center → the user → Revoke sessions, or Revoke-MgUserSignInSession -UserId <user-id>);
  • the user’s password is reset or the account is disabled;
  • the consent for the app is removed.

Access tokens already issued keep working until they expire, so there can be a delay of up to an hour. Microsoft Graph supports Continuous Access Evaluation, which cuts that short for critical events such as a disabled account.

Try it: run the PowerShell refresh once, revoke Divya’s sessions, then run it again. The second swap fails with invalid_grant.

Troubleshooting: the errors we actually hit

Most errors in this flow come from one rule: Entra ID decides the client type from the platform of the redirect URI that matched. For localhost, Entra ID also ignores the port when matching.

Error or symptomCauseFix
AADSTS9002327: tokens for a Single-Page Application may only be redeemed via cross-origin requestsPowerShell sent http://localhost:8400; port ignored, so it matched the SPA URI http://localhost:3000Use a different path for the desktop redirect: http://localhost:8400/callback
AADSTS7000218: request must contain client_assertion or client_secretThe redirect URI sits under the Web platform, which is confidentialMove it to Mobile and desktop applications; if it persists, set Allow public client flows to Yes
AADSTS50011: redirect URI mismatchThe URI sent does not match any registered one exactlyCopy the exact URI, including path, into the right platform
Need admin approvalThe app asked for User.Read.All, which users cannot consent toAn admin grants consent, or the user requests it through the admin consent workflow
AADSTS65001: consent missingThe user or admin has not consented to a scopeSign in interactively once, or grant admin consent
invalid_grant on the token swapThe code was used twice, expired, or the verifier does not matchStart the flow again: codes are single-use and last minutes
Graph returns 403The token lacks the scope, or the user lacks the rightsCheck scp in the token; remember the app can do no more than the user
Page never returns from sign-inOpened as file:// instead of through a web serverRun npx serve -l 3000 . and use http://localhost:3000

Security checklist

  • PKCE with S256 on every authorization code request, including web apps with a secret.
  • A random state sent and checked on return, to stop cross-site request forgery.
  • Exact redirect URIs only, each under the right platform, no wildcards.
  • Least-privilege scopes; sensitive ones behind admin consent.
  • Secrets only in confidential (Web) apps, stored in a vault or environment variables, never in browser code.
  • Tokens kept in memory or session storage in browser apps, on the server in web apps.
  • Conditional Access and MFA left to Entra ID: the app never sees the password.
  • Test users and their passwords file removed after the lab.

Remember

  1. The code is a cloakroom ticket; the access token is the coat.
  2. PKCE makes a stolen ticket useless: only the app holding the secret can swap it.
  3. The platform of the redirect URI decides whether Entra ID wants a secret.
  4. The app’s real access is the overlap of its scopes and the user’s own rights.
  5. A refresh token renews the badge quietly, until an administrator revokes it.

Next in this series

Everything in this part had a person present: Divya signed in, consented and stayed connected through a refresh token. The next part removes the person. Client credentials is the flow for background jobs and services that run on their own, such as a nightly sync that reads the whole directory, and it shows why app-only access needs much tighter control.