Big picture
From Windows sign-in to a protected row
One purchase request, from Alice's browser to a row in PostgreSQL, and every piece that can say no on the way. Entra issues the evidence, Spring checks it, PostgreSQL checks again. On a Windows device joined to Entra the story starts earlier: Windows gets a token for the device before the app is opened.
Pick a journey: the dot is the request and its letters are what it carries. Each stop says what is decided there and which lesson goes deeper. Click any piece, or any area, for its card.
Tags say how to see a stop for yourself: KIT in the local lab, TENANT with a real Entra tenant, WINDOWS on a device joined to that tenant, MODEL only in the lessons.
A · Windows sign-in: the PRT
the device gets a token first
- Alice: Alice signs in to Windows on a device joined to the tenant, with her work password or with Windows Hello for Business. No app is open yet. Windows Lesson 10 · Windows sign-in and the Primary Refresh Token
- Windows sign-in: The sign-in screen, LogonUI, takes the credentials and hands them to LSA, the Local Security Authority. Windows Lesson 10 · Windows sign-in and the Primary Refresh Token
- CloudAP: Inside LSA, CloudAP passes them to its Microsoft Entra plugin, which gets a nonce from Entra and builds a request with the credentials and the nonce. Windows Lesson 10 · Windows sign-in and the Primary Refresh Token
- TPM: The request is signed with the private device key, inside the TPM. The key never leaves it. What the dot carries: Device keys. Windows Lesson 10 · Windows sign-in and the Primary Refresh Token
- Devices [device ✓]: Entra checks the credentials, the nonce and the signature against the public device key, and that the device is valid in the tenant. Windows Lesson 10 · Windows sign-in and the Primary Refresh Token
- Devices: It issues the PRT, and a session key encrypted with the device's public transport key. A sign-in with Windows Hello for Business gives the PRT an MFA claim, refreshed together with the PRT. What the dot carries: Primary Refresh Token (PRT), Session key. Windows Lesson 10 · Windows sign-in and the Primary Refresh Token
- CloudAP: Both reach CloudAP. Only this device can open the session key: that needs the private transport key. What the dot carries: Primary Refresh Token (PRT), Session key. Windows Lesson 10 · Windows sign-in and the Primary Refresh Token
- TPM: The TPM decrypts the session key with the transport key and wraps it again with its own key. What the dot carries: Session key. Windows Lesson 10 · Windows sign-in and the Primary Refresh Token
- CloudAP [PRT cached]: CloudAP stores the PRT and the wrapped session key in its cache, inside LSA. Nothing has reached the browser. Run as the signed-in user, dsregcmd /status shows AzureAdPrt : YES and when the PRT was last renewed. Its output names the device, the tenant and the user: keep it private. What the dot carries: Primary Refresh Token (PRT), Session key. Windows Lesson 10 · Windows sign-in and the Primary Refresh Token
dsregcmd /status
End of the journey: Before any app is opened, CloudAP holds a PRT for Alice and a session key that only this TPM can use. Neither ever reaches the browser or the app: journey B shows what the browser gets instead.
B · Open the app: no password
the browser borrows the device session
- Angular app: On the same device, Alice opens the app in Edge, whose profile is signed in to her work account, and chooses Sign in. Windows Lesson 09 · Angular and MSAL
- MSAL Browser: MSAL makes a verifier and its challenge, which journey D follows in detail, and starts loginRedirect with prompt=select_account. What the dot carries: PKCE verifier. Windows Lesson 05 · Follow the authorization code
- Browser: The browser navigates the tab to /authorize. It recognizes an Entra sign-in URL and asks Windows for a PRT cookie, passing the nonce from the URL. Edge does this for a profile signed in to the work account; Chrome needs the Microsoft Single Sign On extension. Private windows skip it. What the dot carries: PKCE verifier. Windows Lesson 10 · Windows sign-in and the Primary Refresh Token
- CloudAP: CloudAP builds a PRT cookie for that nonce from the PRT in its cache. The PRT itself stays there. What the dot carries: PRT cookie. Windows Lesson 10 · Windows sign-in and the Primary Refresh Token
- TPM: The TPM signs the PRT cookie with the session key. What the dot carries: PRT cookie. Windows Lesson 10 · Windows sign-in and the Primary Refresh Token
- Browser: The PRT cookie goes back to the browser, not to the page: MSAL and any injected script never see it. What the dot carries: PRT cookie. Windows Lesson 10 · Windows sign-in and the Primary Refresh Token
- Sign-in endpoint: The request reaches /authorize with the client, the scopes and the challenge, and the PRT cookie in the x-ms-RefreshTokenCredential header. What the dot carries: PKCE verifier, PRT cookie. Windows Lesson 10 · Windows sign-in and the Primary Refresh Token
- Devices [device ✓]: Entra validates the session key signature and the nonce, and checks that the device is valid in the tenant. Windows Lesson 10 · Windows sign-in and the Primary Refresh Token
- Sign-in endpoint [no password]: Alice is signed in from the device session. The app asked for select_account, so Entra shows its account picker; choosing her account needs no password. Entra returns the code, and a session cookie for its own site. What the dot carries: Authorization code, Entra session cookie. Windows Lesson 10 · Windows sign-in and the Primary Refresh Token
- Browser: The browser keeps Entra's session cookie for login.microsoftonline.com, bound to this device, and follows the redirect to /redirect with the code. What the dot carries: Authorization code, Entra session cookie. Windows Lesson 10 · Windows sign-in and the Primary Refresh Token
- MSAL Browser: From here it is journey D: the MSAL bridge hands the code over, and MSAL redeems it with the verifier. What the dot carries: Authorization code, PKCE verifier. Tenant Lesson 09 · Angular and MSAL
- Token endpoint [S256 ✓]: Entra checks the verifier against the challenge and issues the ID, access and refresh tokens. What the dot carries: Authorization code, PKCE verifier. Tenant Lesson 05 · Follow the authorization code
- Token cache: The three tokens land in sessionStorage, exactly as without Windows. The PRT changed how Alice proved who she is, not what the app holds. What the dot carries: ID token, Access token, Refresh token. Tenant Lesson 10 · Windows sign-in and the Primary Refresh Token
End of the journey: Every credential stayed in its place: the PRT and its session key in CloudAP, the PRT cookie on one request, Entra's session cookie in the browser, the app's tokens in sessionStorage. The API still receives only an access token for its audience.
C · A day later: three clocks
24 hours, 4 hours, 90 days
- Token cache: The tab stayed open overnight. Its refresh token was issued yesterday, and a refresh token issued to a SPA lasts 24 hours from issue, a window that does not slide. What the dot carries: Refresh token. Windows Lesson 10 · Windows sign-in and the Primary Refresh Token
- MSAL Browser [expired]: acquireTokenSilent finds the access token expired, and the refresh token too. What the dot carries: Refresh token. Windows Lesson 09 · Angular and MSAL
- Sign-in endpoint [blocked]: MSAL tries a hidden iframe to /authorize. Where the browser blocks third-party cookies, that silent attempt fails and MSAL raises InteractionRequiredAuthError. Model Lesson 10 · Windows sign-in and the Primary Refresh Token
- Angular app: The app answers with an interactive redirect, never with a loop of silent retries. Windows Lesson 09 · Angular and MSAL
- Browser: A top-level navigation to /authorize. The browser asks CloudAP for a fresh PRT cookie, for the new nonce. Windows Lesson 10 · Windows sign-in and the Primary Refresh Token
- CloudAP [PRT valid]: The PRT is still good: CloudAP renews it at Windows sign-in every 4 hours, and a PRT stays valid for 90 days while the device is used. What the dot carries: Primary Refresh Token (PRT). Windows Lesson 10 · Windows sign-in and the Primary Refresh Token
- Sign-in endpoint [no password]: With the PRT cookie and Entra's session cookie, Entra returns a new code without asking for a password. New tokens follow, as in journey B. What the dot carries: PRT cookie, Entra session cookie. Windows Lesson 10 · Windows sign-in and the Primary Refresh Token
- Devices [what ends it]: The PRT stops working when Alice or the device is deleted or disabled in Entra, or when she changes her password, if the PRT came from it. From then on it gets her nothing. Windows Lesson 10 · Windows sign-in and the Primary Refresh Token
- Token cache: None of that reaches tokens already issued: the access token in sessionStorage stays valid until its exp, as in journey K. What the dot carries: Access token. Windows Lesson 18 · Expiry, renewal and sign-out
End of the journey: Three clocks run at once: the SPA refresh token (24 hours, not sliding), the PRT (renewed at Windows sign-in every 4 hours, valid 90 days) and each access token's exp. Losing the PRT stops new sign-ins; it does not withdraw tokens already issued.
D · Sign in: a code and PKCE
a code worth nothing alone
- Alice: Alice opens the app and chooses Sign in. Nothing has been checked yet: the page is public code running in her browser. Tenant Lesson 09 · Angular and MSAL
- Angular app: The app calls loginRedirect with the API's two scopes. It will never see Alice's password. Tenant Lesson 09 · Angular and MSAL
- MSAL Browser: MSAL makes a fresh verifier, hashes it into an S256 challenge and keeps the verifier in this tab. It adds a state and a nonce to tie the answer to this request. The kit tests the hash relationship only: a different verifier never reproduces the challenge. What the dot carries: PKCE verifier. Kit Lesson 05 · Follow the authorization code
node lab.mjs pkce - Sign-in endpoint [signed in]: The tab goes to the tenant's /authorize with the client ID, the redirect URI, the scopes and the challenge. Entra signs Alice in and applies the tenant's policies. Only the challenge travels here. The verifier never leaves the browser until redemption. What the dot carries: PKCE verifier. Tenant Lesson 05 · Follow the authorization code
- App registrations [URI ✓]: Entra checks the request against the registrations: is this redirect URI registered for this client, and does the API expose these scopes? Tenant Lesson 04 · Two registrations, one application experience
- Sign-in endpoint: If consent is needed, Entra asks for it. Then it redirects to /redirect with a one-time authorization code. What the dot carries: Authorization code. Tenant Lesson 07 · Scopes and consent
- MSAL Browser: The /redirect page runs only the MSAL bridge, which hands the code to the app's MSAL instance. A captured code is useless without the verifier. What the dot carries: Authorization code, PKCE verifier. Tenant Lesson 09 · Angular and MSAL
- Token endpoint [S256 ✓]: MSAL redeems the code with the original verifier. Entra hashes the verifier and compares it with the challenge it saw at /authorize. What the dot carries: Authorization code, PKCE verifier. Tenant Lesson 05 · Follow the authorization code
- Signing keys: Entra signs the new tokens with its private key. Only the public half is ever published. Tenant Lesson 11 · Validate before trusting
- Token endpoint: Three tokens come back: an ID token for the app, an access token for the purchase API and a refresh token for MSAL. What the dot carries: ID token, Access token, Refresh token. Tenant Lesson 06 · Three token jobs
- MSAL Browser: MSAL matches the answer with the state and nonce it sent, sets Alice as the active account and stores the three tokens. What the dot carries: ID token, Access token, Refresh token. Tenant Lesson 09 · Angular and MSAL
- Token cache: They wait in this tab's sessionStorage: gone when the tab closes, but readable by any script running in this origin. What the dot carries: ID token, Access token, Refresh token. Tenant Lesson 21 · Browser threats and architecture choices
End of the journey: Alice is signed in to the app and MSAL holds three tokens. Nothing has reached the API yet: a sign-in is not an authorization. Journey E sends the first request.
E · Read my own request: 200
four checks, then one row
- Angular app: Alice asks for request 41. Before calling the API, the app asks MSAL for a token for exactly the API's scopes. In the kit, fixture mode, the app asks the token dispenser instead; from the API boundary on, everything is the same. Kit Lesson 09 · Angular and MSAL
- MSAL Browser: acquireTokenSilent looks in the cache first, for this account and these scopes. Tenant Lesson 09 · Angular and MSAL
- Token cache: A valid access token for this API is there. No network call is needed. What the dot carries: Access token. Tenant Lesson 09 · Angular and MSAL
- MSAL Browser: MSAL hands it to the app. Had it expired, MSAL would renew it with the refresh token: journey K. What the dot carries: Access token. Tenant Lesson 18 · Expiry, renewal and sign-out
- Angular app: The app attaches the token to one fixed URL, http://localhost:18095/api/requests/41, and to no other destination. What the dot carries: Access token. Kit Lesson 09 · Angular and MSAL
- CORS and bearer filter: First CORS: the browser's preflight asks whether localhost:18094 may send an Authorization header, and the API names that exact origin. Then the bearer filter takes the token. What the dot carries: Access token. Kit Lesson 21 · Browser threats and architecture choices
node lab.mjs cors - JwtDecoder [valid]: The decoder checks the signature with the cached public key, then issuer, expiry and not-before, audience, tenant, version 2.0, the allowed client and a well-formed oid. What the dot carries: Access token, Public signing keys. Kit Lesson 11 · Validate before trusting
node lab.mjs tokens - Authorities converter: Claims become authorities: scp gives SCOPE_Requests.Read and SCOPE_Requests.Approve. Alice has no role, so there is no ROLE_Approver. What the dot carries: Access token. Kit Lesson 12 · From claims to Spring authorities
- Method rule [scope ✓]: Reading needs SCOPE_Requests.Read. Alice has it. Kit Lesson 07 · Scopes and consent
- Controller: In one transaction, the controller sets app.tenant and app.subject from tid and oid, and app.approver from the role. All three are transaction-local. What the dot carries: Transaction context. Kit Lesson 17 · Transactions, pools and races
- Connection pool: It borrows one of three pooled connections. Every one of them is app_runtime, never the administrator. What the dot carries: Transaction context. Kit Lesson 15 · PostgreSQL authenticates the API
- app_runtime: PostgreSQL authenticates app_runtime: no superuser, no BYPASSRLS, SELECT and UPDATE of the status column only. What the dot carries: Transaction context. Kit Lesson 15 · PostgreSQL authenticates the API
node lab.mjs database - RLS policy [RLS ✓]: The SQL already says id = 41 and tenant and owner from the token. The policy adds its own condition: same tenant, and owner or approver. What the dot carries: Transaction context. Kit Lesson 16 · Row-level security as a second boundary
node lab.mjs rls - purchase_request [1 row]: Row 41 is Alice's, in Alice's tenant: it matches both the query and the policy. What the dot carries: Transaction context. Kit Lesson 14 · Ownership is an authorization rule
- Controller: The row comes back. COMMIT ends the transaction, and the context disappears with it. Kit Lesson 17 · Transactions, pools and races
- Angular app [200]: HTTP 200 with request 41. The app shows it; it decided nothing. Kit Lesson 13 · Read a denial correctly
node lab.mjs boundary
End of the journey: One read crossed four independent checks: the token, the operation, the endpoint's query and the row policy. Removing any one of them is a test that should fail.
F · Approve a colleague's request
200 once, then 404
- node lab.mjs: The lab asks for the approver case: Alice's identity, with the Approver role. Kit Lesson 08 · Roles and resource rules
node lab.mjs atomic - Token dispenser: The dispenser signs it with the kit's key: scp lists both scopes, roles lists Approver. What the dot carries: Test token. Kit Lesson 08 · Roles and resource rules
- node lab.mjs: Two POST /api/requests/42/approve leave at the same moment. Request 42 is Bob's, and PENDING. What the dot carries: Test token. Kit Lesson 17 · Transactions, pools and races
- CORS and bearer filter: No browser, so no Origin and no preflight: CORS plays no part. The bearer filter takes the token. What the dot carries: Test token. Kit Lesson 21 · Browser threats and architecture choices
- JwtDecoder [valid]: In fixture mode the decoder trusts the kit's key, and only it. Signature, issuer, time and contract: valid. What the dot carries: Test token, Public signing keys. Kit Lesson 11 · Validate before trusting
- Authorities converter: SCOPE_Requests.Approve from scp, and ROLE_Approver from roles. What the dot carries: Test token. Kit Lesson 12 · From claims to Spring authorities
- Method rule [scope + role ✓]: Approval needs SCOPE_Requests.Approve and ROLE_Approver, both. An OR here would let an app-only token act as a person. Kit Lesson 08 · Roles and resource rules
- Controller: One statement checks and changes together: UPDATE purchase_request SET status = 'APPROVED' WHERE id = 42 AND the tenant matches AND owner_oid is not the caller AND status = 'PENDING'. What the dot carries: Transaction context. Kit Lesson 17 · Transactions, pools and races
- RLS policy [WITH CHECK ✓]: Through a pooled app_runtime connection. The policy's WITH CHECK lets an approver change a row of their tenant. What the dot carries: Transaction context. Kit Lesson 16 · Row-level security as a second boundary
- purchase_request [1 row, then 0]: The first UPDATE turns 42 into APPROVED. The second finds no PENDING row: 0 rows changed. What the dot carries: Transaction context. Kit Lesson 17 · Transactions, pools and races
- Controller [200 and 404]: One row changed: 200 APPROVED. No row: 404, the same answer as for a request that does not exist. Kit Lesson 13 · Read a denial correctly
- node lab.mjs [200 + 404]: The lab sees exactly one 200 and one 404, and PostgreSQL says APPROVED. Approving her own request 41 also gives 404: the owner may not approve. Kit Lesson 08 · Roles and resource rules
node lab.mjs roles
End of the journey: A role is one condition among several. The method rule checks scope and role; one SQL statement checks tenant, not-the-owner and PENDING together, so a race cannot approve twice.
G · 401: the token is not accepted
nine broken tokens, one gate
- node lab.mjs: The lab asks the dispenser for broken tokens, one case at a time. Kit Lesson 11 · Validate before trusting
node lab.mjs signature - Token dispenser: Each case breaks one thing: expired, valid only in the future, signed by a stranger's key, another issuer, another audience, an ID token, another client, no oid, another tenant. What the dot carries: Test token. Kit Lesson 11 · Validate before trusting
- node lab.mjs: Each one goes out as GET /api/requests/41. What the dot carries: Test token. Kit Lesson 13 · Read a denial correctly
- CORS and bearer filter: The bearer filter passes the token to the decoder. What the dot carries: Test token. Kit Lesson 13 · Read a denial correctly
- JwtDecoder [rejected]: Each case fails exactly one check: signature, issuer, exp or nbf, aud (the ID token too: its audience is the SPA), tid, azp or oid. Reading a payload proves nothing: the decoder verifies before it trusts a single claim, and its keys come from configuration, never from the token. What the dot carries: Test token, Public signing keys. Kit Lesson 11 · Validate before trusting
node lab.mjs time - CORS and bearer filter [401]: The filter chain answers 401 with WWW-Authenticate: Bearer. No controller ran and no SQL was sent. Kit Lesson 13 · Read a denial correctly
node lab.mjs http - node lab.mjs [401 ✓]: The lab expects 401 for every case, and still 200 for Alice's valid token. Kit Lesson 22 · Debug without leaking credentials
node lab.mjs audience
End of the journey: 401 means the API did not accept the credential. Signing in again does not fix a wrong audience: configuration does. Every fix keeps its negative test.
H · 403: accepted, not allowed
a genuine token missing one authority
- node lab.mjs: Two genuine tokens that each lack something: no-role has the scopes but not Approver; app-only has Approver but no scp, because no user signed in. Kit Lesson 12 · From claims to Spring authorities
node lab.mjs delegation - Token dispenser: Both are signed with the kit's key, for the right audience, tenant and client. What the dot carries: Test token. Kit Lesson 12 · From claims to Spring authorities
- node lab.mjs: Each one asks to approve request 42. What the dot carries: Test token. Kit Lesson 13 · Read a denial correctly
- CORS and bearer filter: The bearer filter takes the token. What the dot carries: Test token. Kit Lesson 13 · Read a denial correctly
- JwtDecoder [valid]: Both pass every check. Authentication succeeds. What the dot carries: Test token, Public signing keys. Kit Lesson 11 · Validate before trusting
- Authorities converter: no-role yields only SCOPE_ authorities. app-only yields ROLE_Approver and no SCOPE_ at all. What the dot carries: Test token. Kit Lesson 12 · From claims to Spring authorities
- Method rule [403]: Approval needs SCOPE_Requests.Approve and ROLE_Approver. Each token misses one of the two. Kit Lesson 08 · Roles and resource rules
node lab.mjs roles - CORS and bearer filter [403]: The filter chain turns the refusal into 403. The controller never ran. Kit Lesson 13 · Read a denial correctly
- node lab.mjs [403 ✓]: Both get 403. A token with only Requests.Read gets 403 to approve and still 200 to read: scopes are per operation. Kit Lesson 07 · Scopes and consent
node lab.mjs scopes
End of the journey: 403: the API knows who is calling and refuses this operation. A hidden button never protected anything; this rule does.
I · 404: Alice asks for Bob's request
identity from the token, never the URL
- Angular app: Alice types 42 instead of 41. The page lets her: the input is not the boundary. Kit Lesson 14 · Ownership is an authorization rule
- CORS and bearer filter: A genuine token for Alice reaches the API. What the dot carries: Test token. Kit Lesson 14 · Ownership is an authorization rule
- Method rule [scope ✓]: Valid, with SCOPE_Requests.Read: the operation is allowed. Allowed to read is not allowed to read everything. Kit Lesson 13 · Read a denial correctly
- Controller: The id comes from the URL; tenant and owner come only from the token: WHERE id = 42 AND tenant_id = tid AND owner_oid = Alice's oid. What the dot carries: Transaction context. Kit Lesson 14 · Ownership is an authorization rule
- RLS policy: Even a query that forgot its WHERE would be filtered here: the row is not Alice's, and she is not an approver. What the dot carries: Transaction context. Kit Lesson 16 · Row-level security as a second boundary
- purchase_request [0 rows]: No row matches. Kit Lesson 14 · Ownership is an authorization rule
- Controller [404]: No row: 404, the same answer as for a number that does not exist, so the API does not reveal which requests exist. Kit Lesson 13 · Read a denial correctly
- Angular app [404]: Alice sees 404. Bob, with his own token, gets 200 for 42. Request 43 lives in another tenant: Alice gets 404 for it, and a token from that tenant gets 401. Kit Lesson 14 · Ownership is an authorization rule
node lab.mjs owner
End of the journey: Ownership is an authorization rule, enforced with identity taken from the validated token and never from the request. RLS repeats it underneath.
J · RLS, the second boundary
the database without the API
- node lab.mjs: The lab connects to PostgreSQL directly and switches to app_runtime, the role the API uses. Kit Lesson 16 · Row-level security as a second boundary
node lab.mjs rls - RLS policy [0 rows]: No context has been set, so the policy compares tenant_id with NULL: no row qualifies. Kit Lesson 16 · Row-level security as a second boundary
- purchase_request [count 0]: SELECT count(*) returns 0. Not an error: an empty, safe answer. Kit Lesson 16 · Row-level security as a second boundary
- RLS policy: Now inside a transaction with Alice's tenant and subject set, the lab runs a SELECT with no WHERE at all. What the dot carries: Transaction context. Kit Lesson 16 · Row-level security as a second boundary
- purchase_request [41 only]: Only row 41 comes back. Bob's 42 and the other tenant's 43 stay invisible. What the dot carries: Transaction context. Kit Lesson 16 · Row-level security as a second boundary
- RLS policy [context gone]: After COMMIT, the same connection sees 0 rows again: set_config(name, value, true) belonged to that transaction only. Kit Lesson 17 · Transactions, pools and races
node lab.mjs pool - app_runtime [no bypass]: And the role itself is neither superuser nor BYPASSRLS, the table forces RLS, and app_runtime may not rewrite owner_oid. Kit Lesson 15 · PostgreSQL authenticates the API
node lab.mjs database
End of the journey: RLS is a second boundary, not the first: it trusts the context the API sets. What it buys is that a forgotten WHERE returns nothing instead of everything.
K · A removed role meets an older token
expiry, renewal and sign-out
- Administrator: Alice approved requests yesterday. Today the administrator removes her Approver assignment. Tenant Lesson 18 · Expiry, renewal and sign-out
- Enterprise applications: The assignment is gone from the API's enterprise application. Nothing is pushed to tokens already issued. Tenant Lesson 08 · Roles and resource rules
- Token endpoint [next tokens]: Entra will leave roles: Approver out of the next access token it issues for Alice. Tenant Lesson 18 · Expiry, renewal and sign-out
- Token cache: Meanwhile, Alice's cached access token still says roles: Approver, and stays valid until its exp. What the dot carries: Access token, Refresh token. Tenant Lesson 18 · Expiry, renewal and sign-out
- Method rule [still allowed]: Her next approval arrives with that token. The API validates locally: signature, time and claims are fine, and the old role still passes. Spring does not re-read assignments on every request. Faster withdrawal has to be designed: shorter lifetimes, a check against a source of truth, or continuous access evaluation where it applies. What the dot carries: Access token. Tenant Lesson 18 · Expiry, renewal and sign-out
- MSAL Browser: Later the access token expires. Before the next call, acquireTokenSilent sees that and uses the refresh token. What the dot carries: Refresh token. Tenant Lesson 18 · Expiry, renewal and sign-out
- Token endpoint [no role]: Entra issues a new access token. The assignment is gone, so roles is empty. What the dot carries: Refresh token. Tenant Lesson 06 · Three token jobs
- MSAL Browser: MSAL caches the new token and gives it to the app. What the dot carries: Access token. Tenant Lesson 09 · Angular and MSAL
- Method rule [403]: The same approval now gets 403: the token is valid, the role is not in it. What the dot carries: Access token. Tenant Lesson 08 · Roles and resource rules
- Angular app: Alice signs out. logoutRedirect clears MSAL's cache for her account. Tenant Lesson 18 · Expiry, renewal and sign-out
- Sign-in endpoint [session ended]: Entra ends her session at its sign-out endpoint. Tokens already issued are not recalled: they stay valid until they expire. Tenant Lesson 18 · Expiry, renewal and sign-out
End of the journey: Three different things: a token's lifetime, a session and an assignment. Renewal connects them; nothing withdraws a token already issued, so lifetimes matter.
L · Set up the tenant
two registrations, consent, one role
- Administrator: In the Entra admin center, the administrator registers two applications, not one: the token's recipient must be visible. Tenant Lesson 04 · Two registrations, one application experience
- App registrations: The API registration: Application ID URI api://API_CLIENT_ID, delegated scopes Requests.Read and Requests.Approve, the user app role Approver, v2 access tokens. The SPA registration: a public client with the redirect URI http://localhost:18094/redirect, no secret. Tenant Lesson 04 · Two registrations, one application experience
- Enterprise applications: Each registration gets a service principal in the tenant: its enterprise application. Tenant Lesson 03 · Tenant, application, service principal
- Enterprise applications: There the administrator assigns Approver to one test user, and grants consent if users may not consent themselves. Tenant Lesson 08 · Roles and resource rules
- Token endpoint [scp, roles]: From now on, an access token for that user and this API lists the consented scopes in scp and Approver in roles. Tenant Lesson 07 · Scopes and consent
- Signing keys: Spring will verify those tokens with the keys published for the fixed tenant issuer. Tenant Lesson 19 · Connect a real Entra tenant
- JwtDecoder [Entra mode]: With AUTH_MODE=entra, the decoder trusts only https://login.microsoftonline.com/TENANT_ID/v2.0 and its keys. The kit's key is no longer trusted. Tenant Lesson 19 · Connect a real Entra tenant
node configure.mjs entra TENANT_ID SPA_CLIENT_ID API_CLIENT_ID ALICE_OID BOB_OID - Token dispenser [401]: A test token now gets 401. The probe proves the switch, not that a real person signed in. Tenant Lesson 19 · Connect a real Entra tenant
node tenant-probe.mjs
End of the journey: Registrations are configuration, not proof. The tenant workbook records only what you observed: a sign-in, an own read, a role denial and a permitted approval.
M · What CORS and PKCE do not stop
a script inside, a caller outside
- Injected script: A script slips into the page through unsafe rendering or a compromised dependency. It runs with the page's origin. Model Lesson 21 · Browser threats and architecture choices
- MSAL Browser [same origin]: It can ask MSAL for a token just as the app does. PKCE protected the code exchange; it does nothing against code already running in the page. Model Lesson 21 · Browser threats and architecture choices
- Injected script: Now it holds a valid access token. What the dot carries: Access token. Model Lesson 21 · Browser threats and architecture choices
- Angular app: Or it simply drives the app's own code to send requests. What the dot carries: Access token. Model Lesson 21 · Browser threats and architecture choices
- CORS and bearer filter [looks valid]: The API sees a valid token from an allowed origin. Nothing distinguishes this request from Alice's own. Defenses: a strict CSP, safe rendering, maintained dependencies. A backend for frontend keeps tokens on a server behind an HttpOnly cookie, yet a script can still act through that session. What the dot carries: Access token. Model Lesson 21 · Browser threats and architecture choices
- node lab.mjs [no Origin]: CORS is a rule that browsers follow. The lab calls with no Origin header at all, and the API answers as it would anyone: 401 without a token, 200 with a valid one. Kit Lesson 21 · Browser threats and architecture choices
node lab.mjs cors - CORS and bearer filter [preflight 403]: A preflight from https://stranger.invalid gets 403: a browser would block that page. CORS never replaced the token. Kit Lesson 21 · Browser threats and architecture choices
node lab.mjs cors
End of the journey: CORS and PKCE each close one door. Neither protects the API from a caller that holds a valid token: validation and authorization do, and prevention keeps scripts out.
N · Another API, another audience
no forwarding; on-behalf-of
- Controller: Suppose the controller must read Alice's manager from Microsoft Graph. Model Lesson 20 · Users, workloads and downstream APIs
- Another API [wrong aud]: Forwarding the incoming token fails: its audience is the purchase API, and Graph must reject it. What the dot carries: Access token. Model Lesson 20 · Users, workloads and downstream APIs
- Controller: The right design: a confidential middle tier uses the on-behalf-of flow at Entra's token endpoint to get a token whose audience is Graph. Model Lesson 20 · Users, workloads and downstream APIs
- Another API [not in the kit]: That token is for Graph, under Graph's consent. A nightly job with no user would instead use client credentials and its own endpoint policy. Model Lesson 20 · Users, workloads and downstream APIs
End of the journey: A token is for one audience. Reaching another API on the user's behalf is a separate design, with its own consent and threat model; the kit leaves it as an exercise.
Areas
- Your computer
- Alice's computer: Windows with its TPM, the browser and the tab where the application runs. On a device joined to Entra, the first token of the day is obtained here, at Windows sign-in, before any app opens. What it does not do: Nothing here decides what Alice may do in the application. The computer is controlled by its user, or by whoever controls that session: the API and PostgreSQL decide again on the server, with their own rules. Lesson 01 · Four components, four responsibilities, Lesson 10 · Windows sign-in and the Primary Refresh Token
- Windows
- The operating system of a device joined to the tenant. At Windows sign-in, LogonUI hands Alice's credentials to LSA, whose CloudAP provider signs her in to Entra and keeps the Primary Refresh Token in its cache, protected with the TPM. Single sign-on to the app starts here. What it does not do: Windows never gives the PRT to the browser or to an application, and it decides nothing about purchase requests. On a device that is not joined to Entra there is no PRT, and the browser asks for credentials. Lesson 10 · Windows sign-in and the Primary Refresh Token
- Browser tab · localhost:18094
- The application page, served from localhost:18094: Angular, MSAL and the token cache in this tab's sessionStorage. The page starts the sign-in, asks MSAL for a token before each call and sends it to the API. What it does not do: The tab is not a boundary of the API. Every script that runs in it shares its origin and its powers, an injected one included, and the user can change the page or call the API without it. Lesson 09 · Angular and MSAL, Lesson 21 · Browser threats and architecture choices
- Microsoft Entra ID · your tenant
- Your tenant is your organization's own instance of Microsoft Entra ID: a directory, identified by its tenant ID, with its users, groups, devices and applications. Here each application has its registration and its service principal, consent and role assignments are recorded, people and devices are authenticated under the tenant's policies, and tokens are issued from /authorize and /token, signed with keys that Entra publishes. The API trusts only tokens whose issuer is this tenant: https://login.microsoftonline.com/TENANT_ID/v2.0. What it does not do: It does not know the application's data: who owns request 42, whether it is pending and who may approve it are decided by the API and PostgreSQL. Once it has issued a token, it does not see the requests that carry it and cannot take it back. Another tenant is another directory, with other users: its tokens carry another issuer and another tid, and the API rejects them. Lesson 03 · Tenant, application, service principal, Lesson 04 · Two registrations, one application experience, Lesson 19 · Connect a real Entra tenant
- Tenant admin
- A person with directory permissions working in the Entra admin center. Before any request, they register the API and the SPA, expose the scopes, grant consent when users cannot and assign the Approver role to users. What it does not do: The administrator is not in the path of any request and approves no purchase. A directory administrator role does not make anyone an approver in this application: that is the app role Approver, assigned on the API. Lesson 04 · Two registrations, one application experience, Lesson 08 · Roles and resource rules, Lesson 19 · Connect a real Entra tenant
- Beyond the kit
- Resources the course names but the kit never calls, such as Microsoft Graph: another API, with its own audience and its own permissions. They show where a design would continue: on-behalf-of to act for a user, client credentials for a job without one. What it does not do: Nothing here runs in the kit or in the activities; the journey that reaches it is a model. A token issued for the purchase API is not valid here. Lesson 20 · Users, workloads and downstream APIs
- The API · Spring Boot · localhost:18095
- The Spring Boot resource server at localhost:18095. Each request crosses the security filter chain, then the method rule, then a controller that opens one transaction and runs SQL whose tenant and owner come from the validated token. The business decisions are made here. What it does not do: It keeps no session and stores no token: each request is judged on its own. It does not authenticate people; it verifies evidence that Entra issued, and it never forwards that token to the database. Lesson 01 · Four components, four responsibilities, Lesson 11 · Validate before trusting, Lesson 14 · Ownership is an authorization rule
- Security filter chain
- The part of Spring Security that every request crosses before any controller: CORS for the exact origin, the bearer filter, the JwtDecoder that verifies the token and the converter that turns its claims into authorities. It writes every 401 and every 403. What it does not do: It does not know who owns a row or whether a request is pending: that is decided after it, in the controller and in PostgreSQL. The CORS in it is a rule that browsers follow, not authentication. Lesson 11 · Validate before trusting, Lesson 12 · From claims to Spring authorities, Lesson 13 · Read a denial correctly
- Local kit only
- Pieces that exist only in the local lab: the token dispenser, which signs test tokens with the kit's own key, and lab.mjs, the runner that sends requests and checks PostgreSQL. With them you can watch the API and the database decide without a tenant. What it does not do: Neither is Entra, and neither authenticates anyone. In Entra mode the API stops trusting the kit's key, and the runner refuses to run. Lesson 00 · Before you start, Lesson 19 · Connect a real Entra tenant
- PostgreSQL 18
- The database of the purchase requests. The API connects as app_runtime, a restricted role, through a pool of connections; row-level security filters every row with the tenant and the subject that the API sets for each transaction. What it does not do: It never sees a token or the browser user: it authenticates the API's database role. Its policy trusts the context that the API sets; it is a second boundary, not the first. Lesson 15 · PostgreSQL authenticates the API, Lesson 16 · Row-level security as a second boundary, Lesson 17 · Transactions, pools and races
Pieces
- Token cache · sessionStorage of this tab
- Where MSAL keeps the ID, access and refresh tokens, and the PKCE verifier while a sign-in is in flight. Session storage disappears with the tab. What it does not do: It is not a vault: any script running in this origin can read it. Session storage reduces how long tokens persist, not who in the page can reach them. The PRT and Entra's own session cookie are never here. Lesson 09 · Angular and MSAL, Lesson 21 · Browser threats and architecture choices
- MSAL Browser · PublicClientApplication
- Microsoft's library inside the page. It runs the authorization code flow with PKCE, handles the redirect, caches tokens and renews them silently. What it does not do: It keeps no secret, because a browser cannot, and it makes no business decision. It cannot tell the app's own code from a script injected into the same page. Lesson 09 · Angular and MSAL, Lesson 05 · Follow the authorization code
- Injected script
- Code that should not be in the page: an XSS payload or a compromised dependency. It runs with the page's origin and with every power the page has. What it does not do: It does not need a password and it does not break PKCE: it acts with what the page can already do. Only prevention addresses it: a strict CSP, safe rendering, maintained dependencies. Lesson 21 · Browser threats and architecture choices
- Angular app · presents, decides nothing
- The single-page application on localhost:18094. It loads public configuration, starts sign-in, asks for a token before each call and sends it to one fixed API URL. What it does not do: It enforces no permission. A hidden button is a convenience: anyone can change the bundle, or call the API without it. Lesson 01 · Four components, four responsibilities, Lesson 09 · Angular and MSAL
- Alice · a person with a work account
- The person the system acts for. Entra authenticates her when she signs in to Windows on a joined device, and when the app signs her in; after that, the API only ever sees evidence about her: a token with her tenant ID and object ID. What it does not do: She never gives her password to the app, and nothing she can change in her browser decides what she may read or approve. Lesson 00 · Before you start, Lesson 02 · Authentication and authorization, Lesson 10 · Windows sign-in and the Primary Refresh Token
- Windows sign-in · LogonUI, LSA
- The Windows sign-in screen, LogonUI. It takes Alice's credentials, her work password or Windows Hello for Business, and hands them to LSA, the Local Security Authority, where CloudAP signs her in to Entra. What it does not do: It does not talk to Entra itself, and the app never sees what Alice types here. Lesson 10 · Windows sign-in and the Primary Refresh Token
- TPM · private keys
- The Trusted Platform Module, a hardware component. It keeps the private device key, which signs the PRT request, and the private transport key, which opens the session key that Entra sends. Then it wraps the session key with a key of its own. What it does not do: It never hands out a private key, and no other component of Windows can use the session key it protects. Where a device has no usable TPM, the keys cannot be bound to hardware. Lesson 10 · Windows sign-in and the Primary Refresh Token
- CloudAP · in LSA, Entra plugin
- The Windows sign-in provider inside the Local Security Authority (LSA). Its Microsoft Entra plugin turns Alice's Windows sign-in into a PRT, keeps the PRT and the session key in its cache, renews the PRT at Windows sign-in every 4 hours, and builds a PRT cookie when the browser asks for one. What it does not do: It never hands the PRT or the session key to the browser or to an application. Native applications ask WAM, the Windows token broker, which uses the same PRT and keeps their refresh tokens encrypted with DPAPI; this browser app does not. See it: dsregcmd /status, run as the signed-in user: AzureAdPrt : YES under SSO State, and the time of the last renewal. The output names the device, the tenant and the user. Lesson 10 · Windows sign-in and the Primary Refresh Token
- Browser · navigation, Entra's cookies, SSO
- The browser itself, not the page. It navigates the tab to Entra and back and keeps Entra's session cookie for login.microsoftonline.com. On a device joined to Entra, when it opens an Entra sign-in URL it asks Windows for a PRT cookie: Edge does it for a profile signed in to the work account, Chrome through the Microsoft Single Sign On extension. What it does not do: Page scripts, MSAL included, never see the PRT cookie or Entra's cookies: they belong to another site. Private windows do not ask Windows for a PRT cookie. Lesson 10 · Windows sign-in and the Primary Refresh Token
- Sign-in endpoint · /authorize
- Where the browser goes to sign in. Entra authenticates the person, applies the tenant's policies, asks for consent when needed and returns a one-time code to a registered redirect URI. On a device joined to Entra, the browser can bring a PRT cookie instead of a password. Entra sets its own session cookie; sign-out ends that session at a sibling endpoint. What it does not do: In this flow it never hands tokens to the page, and it does not know the purchase rules: who owns request 42 is not Entra's business. Lesson 05 · Follow the authorization code, Lesson 07 · Scopes and consent, Lesson 10 · Windows sign-in and the Primary Refresh Token
- Devices · issues the PRT
- Entra's record of each joined device: the public halves of its device key and transport key, registered at join, and whether the device is enabled. When CloudAP signs in, Entra checks the credentials, the nonce and the device signature against it, and issues the PRT with a session key that only that device can open. What it does not do: The app never calls it: only the device's sign-in broker does. A known device proves which computer is asking, not who may approve a purchase. Lesson 10 · Windows sign-in and the Primary Refresh Token
- App registrations · SPA: redirect URI · API: scopes, role
- Two application objects. The API one defines the resource: its Application ID URI, the delegated scopes Requests.Read and Requests.Approve, the user app role Approver and v2 access tokens. The SPA one defines a public client and its redirect URI. What it does not do: A registration is configuration, not proof of anything at runtime. The SPA registration holds no secret, and must not. Lesson 04 · Two registrations, one application experience, Lesson 03 · Tenant, application, service principal
- Token endpoint · /token
- Redeems the authorization code with the PKCE verifier, renews with the refresh token, and issues signed tokens: an ID token for the client, an access token for the API. What it does not do: It never sees the API's requests. Once a token is issued, the API checks it on its own, and nothing recalls it. Lesson 05 · Follow the authorization code, Lesson 06 · Three token jobs, Lesson 18 · Expiry, renewal and sign-out
- Signing keys · JWKS
- Entra signs tokens with private keys and publishes the public halves, with the issuer metadata, so any resource can verify a signature. Keys rotate. What it does not do: A public key cannot sign. And a resource finds the keys from its configured issuer, never from a URL written inside a token. Lesson 11 · Validate before trusting
- Enterprise applications · consent, role assignment
- The service principals: how each application exists in this tenant. Consent grants, and the assignment of Approver to users, live here. What it does not do: An assignment does not reach into tokens already issued; it shapes the next ones. Lesson 03 · Tenant, application, service principal, Lesson 08 · Roles and resource rules, Lesson 07 · Scopes and consent
- Administrator · Entra admin center
- A person with directory permissions who registers the two applications, grants consent and assigns the Approver role. What it does not do: A directory administrator role is not purchase approval: administering the tenant and approving requests are different authorities. Lesson 04 · Two registrations, one application experience, Lesson 08 · Roles and resource rules, Lesson 19 · Connect a real Entra tenant
- CORS and bearer filter · the front door
- The front door of the API. CORS answers preflights for the exact origin localhost:18094; the bearer filter takes the token from the Authorization header and asks the decoder. The chain writes every 401 and 403. What it does not do: There is no session and no cookie login, so CSRF protection is off on purpose. CORS authenticates nobody. Lesson 13 · Read a denial correctly, Lesson 21 · Browser threats and architecture choices
- JwtDecoder · verify, then trust
- Verifies the signature with the configured issuer's public keys, then issuer and time, then the API's contract: audience, tenant, version 2.0, the allowed client (azp) and a well-formed oid. What it does not do: It never takes an issuer or a key URL from the token, and it does not authorize: a valid token can still get 403 or 404. Lesson 11 · Validate before trusting
- Authorities converter · scp, roles
- Turns the validated token into Spring authorities: each scp value becomes SCOPE_ plus its name, and the recognized role Approver becomes ROLE_Approver. What it does not do: It maps nothing else: no directory role, no group and no browser state becomes a purchase permission. Lesson 12 · From claims to Spring authorities
- Method rule · @PreAuthorize
- One requirement per operation. Read needs SCOPE_Requests.Read. Approve needs SCOPE_Requests.Approve and ROLE_Approver, both. Exact strings, with hasAuthority. What it does not do: It does not know who owns a row: that is the job of the query, and of the policy underneath. Lesson 08 · Roles and resource rules, Lesson 12 · From claims to Spring authorities
- Controller · one transaction, one SQL
- Opens a transaction, sets app.tenant, app.subject and app.approver with set_config(name, value, true), and runs one parameterized statement whose tenant and owner come from the validated token. What it does not do: It never takes identity from the URL, a header or the body: only the number of the request comes from the caller. Lesson 14 · Ownership is an authorization rule, Lesson 17 · Transactions, pools and races
- Connection pool · 3 connections
- Hikari keeps three connections open and lends one for each transaction. Every connection logs in as app_runtime. What it does not do: It does not clear session settings between borrowers: that is why the context is set inside the transaction and dies with it. Lesson 15 · PostgreSQL authenticates the API, Lesson 17 · Transactions, pools and races
- node lab.mjs · no browser
- The kit's test runner on your computer. It calls the API with named test tokens, inspects PostgreSQL roles and policies, and asserts every expected status. What it does not do: It refuses to run against Entra mode, and it never tests a real sign-in. Lesson 00 · Before you start, Lesson 22 · Debug without leaking credentials, Lesson 24 · Capstone: defend one request
- Token dispenser · :18096
- A tiny service that signs JWTs with the kit's own key, one per named case: alice, bob, approver, expired, forged, no-scope, app-only and more. It serves that public key as /jwks, and in fixture mode the Angular app asks it for tokens instead of MSAL. What it does not do: It is not an OpenID provider and not Entra: it authenticates nobody. Never expose it beyond your machine. Lesson 00 · Before you start, Lesson 11 · Validate before trusting
- Another API · Microsoft Graph
- A downstream resource with its own audience and its own permissions. What it does not do: It must not accept a token issued for the purchase API. The kit makes no downstream call. Lesson 20 · Users, workloads and downstream APIs
- purchase_request · 41 Alice · 42 Bob · 43 another tenant
- The practice rows: 41 is Alice's, 42 is Bob's, 43 belongs to another tenant. Each has a tenant, an owner oid and a status, PENDING or APPROVED. What it does not do: Nothing in a row says who may see it: the query and the policy decide that. Lesson 14 · Ownership is an authorization rule, Lesson 16 · Row-level security as a second boundary
- app_runtime · no BYPASSRLS
- The database principal of the API: neither superuser nor BYPASSRLS, it may SELECT the table and UPDATE only the status column. Migrations use another role. What it does not do: It knows nothing about Alice: PostgreSQL authenticates the connection, not the browser user. The API's token never reaches the database. Lesson 15 · PostgreSQL authenticates the API
- RLS policy · request_boundary
- Row-level security on purchase_request, forced even for the table owner. To read: same tenant, and owner or approver. To change: same tenant and approver. What it does not do: It trusts the context strings the API sets. It is a second boundary, not cryptographic proof. Lesson 16 · Row-level security as a second boundary
Tokens, keys, cookies
- D · Device keys
- Two key pairs Windows creates when the device joins Entra. The device key signs the device's requests; the transport key lets Entra encrypt the session key for this device only. Comes from: The device itself, when it joins Entra. Ends up: The private halves stay in the TPM; the public halves are registered with the device in Entra. Where it is, moment by moment: When the device joins: Windows creates both pairs and registers the public halves with Entra. From then on: The private halves stay in the TPM and never leave it. At every PRT request: The TPM signs with the private device key; Entra checks the signature with the public half.
- P · Primary Refresh Token (PRT)
- A token Entra issues to the device's sign-in broker, not to an application. With it, CloudAP can get Alice a session at Entra without asking her for credentials again. Comes from: Entra, at Windows sign-in, after checking the credentials, the nonce and the device. Ends up: CloudAP's cache inside LSA, on this device only: valid 90 days, renewed while the device is used. Where it is, moment by moment: At Windows sign-in: Entra issues it to CloudAP, which keeps it in its cache inside LSA. While Alice works: It stays in that cache. CloudAP renews it at Windows sign-in every 4 hours. When an app signs in: It still stays in CloudAP: the browser only receives a PRT cookie made from it. When it stops working: After 90 days without renewal, or when Entra invalidates it: user or device deleted or disabled, or a password change if the PRT came from the password.
- S · Session key
- A key Entra issues with the PRT. Requests that use the PRT are signed with it, which proves they come from the device that received the PRT. Comes from: Entra, with the PRT, encrypted with the device's public transport key. Ends up: CloudAP's cache, wrapped by the TPM; no other component can use it. Where it is, moment by moment: At Windows sign-in: It arrives encrypted for the transport key. The TPM decrypts it and wraps it again with its own key. Afterwards: CloudAP keeps the wrapped key next to the PRT. On each use: The TPM signs with it, for example a PRT cookie. The key itself never leaves the device.
- W · PRT cookie
- A value CloudAP builds for one sign-in request, with the nonce Entra put in the sign-in URL, signed with the session key. Entra accepts it as proof that Alice is signed in on this device. Comes from: CloudAP, when the browser opens an Entra sign-in URL. Ends up: The x-ms-RefreshTokenCredential header of that one request to /authorize. Where it is, moment by moment: When the tab goes to Entra: The browser asks CloudAP for it, with the nonce from the URL. Moments later: CloudAP builds it and the TPM signs it with the session key. For one request: It travels in the x-ms-RefreshTokenCredential header to /authorize. Page scripts never see it. Afterwards: It is tied to that nonce: the next sign-in asks for a new one.
- E · Entra session cookie
- The cookie Entra sets for its own site after a sign-in. Later visits to /authorize can skip the credentials. When the sign-in used a PRT cookie, it is bound to the device's session key, so a copy does not work from another device. Comes from: /authorize, after Alice signs in. Ends up: The browser's cookies for login.microsoftonline.com, out of reach of the app's scripts. Where it is, moment by moment: After sign-in: Entra sets it for login.microsoftonline.com. It lives in the browser's cookie store, not in sessionStorage. At the next visit to /authorize: The browser sends it back, and Entra can answer without asking for credentials. At sign-out: Entra ends that session at its sign-out endpoint.
- C · Authorization code
- A one-time code that Entra returns to the registered redirect URI after sign-in. Short-lived, and useless without the verifier. Comes from: Entra's sign-in endpoint, after sign-in. Ends up: Redeemed once by MSAL at the token endpoint. Where it is, moment by moment: After sign-in: In the redirect from /authorize back to /redirect. Moments later: The MSAL bridge hands it to MSAL, which redeems it at /token with the verifier. After redemption: Worthless: a code is redeemed once.
- V · PKCE verifier
- A random secret MSAL creates for each sign-in, and its S256 hash, the challenge. The hash travels first; the verifier only at redemption. Comes from: MSAL, in the browser. Ends up: The token endpoint compares it with the challenge. Where it is, moment by moment: Before /authorize: MSAL creates it and keeps it in the tab while the sign-in is in flight. Only its hash goes to /authorize. At /token: Sent once, with the code. Entra hashes it and compares. Afterwards: Not needed again: the next sign-in makes a new one.
- I · ID token
- The sign-in result for the app: who signed in, for this client. Its audience is the SPA, not the API. Comes from: Entra's token endpoint. Ends up: MSAL's cache, to show the account. The API rejects it. Where it is, moment by moment: At /token: Issued with the access and refresh tokens. Then: In the tab's sessionStorage, where MSAL reads the account from it. When the tab closes: Gone with sessionStorage.
- A · Access token
- A signed JWT for the purchase API: audience, tenant, oid, scp, roles and time limits. A bearer credential: whoever holds it can use it. Comes from: Entra's token endpoint, for the API's scopes. Ends up: The Authorization header of each call; Spring checks it every time. Where it is, moment by moment: At /token: Issued for the API's scopes and audience. Until it expires: In the tab's sessionStorage, where acquireTokenSilent finds it. On each call: Copied into the Authorization header of one request. The API validates it and keeps nothing: there is no session. After sign-out: Gone from the tab, yet any copy stays valid until its exp.
- R · Refresh token
- Lets MSAL get new tokens from Entra without a new sign-in, within the tenant's policies. Issued to a SPA, it lasts 24 hours from issue, a window that does not slide. Comes from: Entra's token endpoint, at sign-in. Ends up: MSAL's cache; only Entra ever receives it back. Where it is, moment by moment: At /token: Issued with the other tokens. For 24 hours: In the tab's sessionStorage. MSAL sends it only to /token, to renew. After 24 hours: Expired. MSAL tries a hidden iframe to /authorize; where third-party cookies are blocked that fails, and a redirect gets a new code.
- K · Public signing keys
- The public halves of the signing keys, published as JWKS. With them anyone can verify a signature; nobody can sign. Comes from: Entra's metadata; in fixture mode, the kit's /jwks. Ends up: The decoder's cache, refreshed when a new key ID appears. Where it is, moment by moment: Published: In Entra's metadata for the tenant's issuer. In the API: Cached by the decoder, and fetched again when a token names an unknown key ID.
- T · Test token
- A JWT signed by the kit's own key, with one thing changed per case: expired, forged, another audience, no scope, no user... Comes from: The token dispenser at :18096. Ends up: The API in fixture mode. In Entra mode it gets 401. Where it is, moment by moment: On request: Signed by the dispenser for one named case. For one call: Held by the lab runner, which sends it in the Authorization header. Afterwards: Nothing keeps it: the API stores no token.
- X · Transaction context
- app.tenant, app.subject and app.approver, set with set_config(name, value, true). They exist only inside the current transaction. Comes from: The controller, from tid, oid and ROLE_Approver. Ends up: Read by the RLS policy; erased by COMMIT or ROLLBACK. Where it is, moment by moment: Inside the transaction: Set by the controller on the borrowed connection. During the SQL: Read by the RLS policy. At COMMIT or ROLLBACK: Erased: the next borrower of the connection sees none of it.
Panorama
Del inicio de sesión de Windows a una fila protegida
Una solicitud de compra, desde el navegador de Alice hasta una fila de PostgreSQL, y cada pieza que puede decir que no en el camino. Entra emite la evidencia, Spring la verifica y PostgreSQL vuelve a verificar. En un Windows unido a Entra la historia empieza antes: Windows consigue un token para el dispositivo antes de que se abra la app.
Elegí un recorrido: el punto es el pedido y sus letras son lo que lleva. Cada parada dice qué se decide ahí y qué lección profundiza. Hacé clic en cualquier pieza, o en cualquier zona, para ver su ficha.
Las etiquetas dicen cómo ver una parada por tu cuenta: KIT en el laboratorio local, TENANT con un tenant real de Entra, WINDOWS en un dispositivo unido a ese tenant, MODELO solo en las lecciones.
A · Inicio de sesión de Windows: el PRT
el dispositivo consigue un token primero
- Alice: Alice inicia sesión en Windows en un dispositivo unido al tenant, con su contraseña de trabajo o con Windows Hello for Business. Todavía no hay ninguna app abierta. Windows Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- Login de Windows: La pantalla de inicio de sesión, LogonUI, toma las credenciales y se las pasa a LSA, la Local Security Authority. Windows Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- CloudAP: Dentro de LSA, CloudAP se las pasa a su plugin de Microsoft Entra, que le pide un nonce a Entra y arma un pedido con las credenciales y el nonce. Windows Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- TPM: El pedido se firma con la clave privada del dispositivo, dentro del TPM. La clave nunca sale de ahí. Qué lleva el punto: Claves del dispositivo. Windows Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- Devices [dispositivo ✓]: Entra verifica las credenciales, el nonce y la firma contra la clave pública del dispositivo, y que el dispositivo sea válido en el tenant. Windows Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- Devices: Emite el PRT, y una session key cifrada con la clave pública de transporte del dispositivo. Un inicio de sesión con Windows Hello for Business le da al PRT un claim de MFA, que se renueva junto con el PRT. Qué lleva el punto: Primary Refresh Token (PRT), Session key. Windows Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- CloudAP: Los dos llegan a CloudAP. Solo este dispositivo puede abrir la session key: hace falta la clave privada de transporte. Qué lleva el punto: Primary Refresh Token (PRT), Session key. Windows Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- TPM: El TPM descifra la session key con la clave de transporte y la vuelve a envolver con su propia clave. Qué lleva el punto: Session key. Windows Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- CloudAP [PRT en caché]: CloudAP guarda el PRT y la session key envuelta en su caché, dentro de LSA. Al navegador no llegó nada. Ejecutado como el usuario con la sesión iniciada, dsregcmd /status muestra AzureAdPrt : YES y cuándo se renovó el PRT por última vez. Su salida nombra el dispositivo, el tenant y el usuario: guardala en privado. Qué lleva el punto: Primary Refresh Token (PRT), Session key. Windows Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
dsregcmd /status
Fin del recorrido: Antes de que se abra cualquier app, CloudAP tiene un PRT para Alice y una session key que solo este TPM puede usar. Ninguno de los dos llega nunca al navegador ni a la app: el recorrido B muestra lo que recibe el navegador en su lugar.
B · Abrir la app: sin contraseña
el navegador toma prestada la sesión del dispositivo
- App Angular: En el mismo dispositivo, Alice abre la app en Edge, con un perfil que tiene iniciada la sesión de su cuenta de trabajo, y elige Sign in. Windows Lección 09 · Angular y MSAL
- MSAL Browser: MSAL arma un verifier y su challenge, que el recorrido D sigue en detalle, y arranca loginRedirect con prompt=select_account. Qué lleva el punto: Verifier de PKCE. Windows Lección 05 · Seguí el authorization code
- Navegador: El navegador lleva la pestaña a /authorize. Reconoce una URL de inicio de sesión de Entra y le pide a Windows una PRT cookie, pasándole el nonce de la URL. Edge lo hace con un perfil que tiene iniciada la sesión de la cuenta de trabajo; Chrome necesita la extensión Microsoft Single Sign On. Las ventanas privadas lo saltean. Qué lleva el punto: Verifier de PKCE. Windows Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- CloudAP: CloudAP arma una PRT cookie para ese nonce a partir del PRT de su caché. El PRT mismo se queda ahí. Qué lleva el punto: PRT cookie. Windows Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- TPM: El TPM firma la PRT cookie con la session key. Qué lleva el punto: PRT cookie. Windows Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- Navegador: La PRT cookie vuelve al navegador, no a la página: MSAL y cualquier script inyectado nunca la ven. Qué lleva el punto: PRT cookie. Windows Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- Endpoint de login: El pedido llega a /authorize con el cliente, los scopes y el challenge, y la PRT cookie en el header x-ms-RefreshTokenCredential. Qué lleva el punto: Verifier de PKCE, PRT cookie. Windows Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- Devices [dispositivo ✓]: Entra valida la firma de la session key y el nonce, y verifica que el dispositivo sea válido en el tenant. Windows Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- Endpoint de login [sin contraseña]: Alice queda con la sesión iniciada a partir de la sesión del dispositivo. La app pidió select_account, así que Entra muestra su selector de cuentas; elegir su cuenta no pide contraseña. Entra devuelve el code, y una cookie de sesión para su propio sitio. Qué lleva el punto: Authorization code, Cookie de sesión de Entra. Windows Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- Navegador: El navegador guarda la cookie de sesión de Entra para login.microsoftonline.com, atada a este dispositivo, y sigue el redirect a /redirect con el code. Qué lleva el punto: Authorization code, Cookie de sesión de Entra. Windows Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- MSAL Browser: Desde acá es el recorrido D: el bridge de MSAL entrega el code, y MSAL lo canjea con el verifier. Qué lleva el punto: Authorization code, Verifier de PKCE. Tenant Lección 09 · Angular y MSAL
- Token endpoint [S256 ✓]: Entra compara el verifier con el challenge y emite el ID token, el access token y el refresh token. Qué lleva el punto: Authorization code, Verifier de PKCE. Tenant Lección 05 · Seguí el authorization code
- Caché de tokens: Los tres tokens llegan al sessionStorage, igual que sin Windows. El PRT cambió cómo probó Alice quién es, no lo que guarda la app. Qué lleva el punto: ID token, Access token, Refresh token. Tenant Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
Fin del recorrido: Cada credencial se quedó en su lugar: el PRT y su session key en CloudAP, la PRT cookie en un solo pedido, la cookie de sesión de Entra en el navegador, los tokens de la app en sessionStorage. La API sigue recibiendo solo un access token para su audiencia.
C · Un día después: tres relojes
24 horas, 4 horas, 90 días
- Caché de tokens: La pestaña quedó abierta toda la noche. Su refresh token se emitió ayer, y un refresh token emitido para una SPA dura 24 horas desde que se emite, en una ventana que no se corre. Qué lleva el punto: Refresh token. Windows Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- MSAL Browser [vencido]: acquireTokenSilent encuentra vencido el access token, y también el refresh token. Qué lleva el punto: Refresh token. Windows Lección 09 · Angular y MSAL
- Endpoint de login [bloqueado]: MSAL prueba un iframe oculto contra /authorize. Donde el navegador bloquea las cookies de terceros, ese intento sin interacción falla y MSAL lanza InteractionRequiredAuthError. Modelo Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- App Angular: La app responde con un redirect interactivo, nunca con una serie de reintentos sin interacción. Windows Lección 09 · Angular y MSAL
- Navegador: Una navegación de nivel superior a /authorize. El navegador le pide a CloudAP una PRT cookie nueva, para el nonce nuevo. Windows Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- CloudAP [PRT vigente]: El PRT sigue sirviendo: CloudAP lo renueva al iniciar sesión en Windows cada 4 horas, y un PRT vale 90 días mientras se usa el dispositivo. Qué lleva el punto: Primary Refresh Token (PRT). Windows Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- Endpoint de login [sin contraseña]: Con la PRT cookie y la cookie de sesión de Entra, Entra devuelve un code nuevo sin pedir contraseña. Siguen los tokens nuevos, como en el recorrido B. Qué lleva el punto: PRT cookie, Cookie de sesión de Entra. Windows Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- Devices [qué lo termina]: El PRT deja de servir cuando Alice o el dispositivo se borran o se deshabilitan en Entra, o cuando ella cambia su contraseña, si el PRT salió de ella. Desde ese momento no le consigue nada. Windows Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- Caché de tokens: Nada de eso llega a los tokens ya emitidos: el access token del sessionStorage sigue valiendo hasta su exp, como en el recorrido K. Qué lleva el punto: Access token. Windows Lección 18 · Vencimiento, renovación y cierre de sesión
Fin del recorrido: Corren tres relojes a la vez: el refresh token de la SPA (24 horas, sin correrse), el PRT (se renueva al iniciar sesión en Windows cada 4 horas, vale 90 días) y el exp de cada access token. Perder el PRT frena los inicios de sesión nuevos; no retira los tokens ya emitidos.
D · Iniciar sesión: un code y PKCE
un code que solo no vale nada
- Alice: Alice abre la app y elige Sign in. Todavía no se verificó nada: la página es código público que corre en su navegador. Tenant Lección 09 · Angular y MSAL
- App Angular: La app llama a loginRedirect con los dos scopes de la API. Nunca va a ver la contraseña de Alice. Tenant Lección 09 · Angular y MSAL
- MSAL Browser: MSAL arma un verifier nuevo, calcula su hash para obtener un challenge S256 y guarda el verifier en esta pestaña. Agrega un state y un nonce para atar la respuesta a este pedido. El kit prueba solo la relación del hash: un verifier distinto nunca reproduce el challenge. Qué lleva el punto: Verifier de PKCE. Kit Lección 05 · Seguí el authorization code
node lab.mjs pkce - Endpoint de login [sesión iniciada]: La pestaña va al /authorize del tenant con el client ID, la redirect URI, los scopes y el challenge. Entra le inicia la sesión a Alice y aplica las políticas del tenant. Acá viaja solo el challenge. El verifier no sale del navegador hasta el canje. Qué lleva el punto: Verifier de PKCE. Tenant Lección 05 · Seguí el authorization code
- App registrations [URI ✓]: Entra contrasta el pedido con los registros: ¿esta redirect URI está registrada para este cliente, y la API expone estos scopes? Tenant Lección 04 · Dos registros, una experiencia de aplicación
- Endpoint de login: Si hace falta consentimiento, Entra lo pide. Después redirige a /redirect con un authorization code de un solo uso. Qué lleva el punto: Authorization code. Tenant Lección 07 · Scopes y consentimiento
- MSAL Browser: La página /redirect ejecuta solo el bridge de MSAL, que le pasa el code a la instancia de MSAL de la app. Un code capturado no sirve sin el verifier. Qué lleva el punto: Authorization code, Verifier de PKCE. Tenant Lección 09 · Angular y MSAL
- Token endpoint [S256 ✓]: MSAL canjea el code con el verifier original. Entra calcula el hash del verifier y lo compara con el challenge que vio en /authorize. Qué lleva el punto: Authorization code, Verifier de PKCE. Tenant Lección 05 · Seguí el authorization code
- Claves de firma: Entra firma los tokens nuevos con su clave privada. Solo se publica la mitad pública. Tenant Lección 11 · Validá antes de confiar
- Token endpoint: Vuelven tres tokens: un ID token para la app, un access token para la API de compras y un refresh token para MSAL. Qué lleva el punto: ID token, Access token, Refresh token. Tenant Lección 06 · Tres trabajos de los tokens
- MSAL Browser: MSAL compara la respuesta con el state y el nonce que mandó, marca a Alice como la cuenta activa y guarda los tres tokens. Qué lleva el punto: ID token, Access token, Refresh token. Tenant Lección 09 · Angular y MSAL
- Caché de tokens: Esperan en el sessionStorage de esta pestaña: desaparecen cuando se cierra la pestaña, pero cualquier script que corra en este origen los puede leer. Qué lleva el punto: ID token, Access token, Refresh token. Tenant Lección 21 · Amenazas en el navegador y decisiones de arquitectura
Fin del recorrido: Alice tiene la sesión iniciada en la app y MSAL guarda tres tokens. Todavía no llegó nada a la API: un inicio de sesión no es una autorización. El recorrido E manda el primer pedido.
E · Leer mi propia solicitud: 200
cuatro verificaciones, después una fila
- App Angular: Alice pide la solicitud 41. Antes de llamar a la API, la app le pide a MSAL un token para exactamente los scopes de la API. En el kit, en modo fixture, la app se lo pide al emisor de tokens; desde el límite de la API en adelante, todo es igual. Kit Lección 09 · Angular y MSAL
- MSAL Browser: acquireTokenSilent busca primero en la caché, para esta cuenta y estos scopes. Tenant Lección 09 · Angular y MSAL
- Caché de tokens: Ahí hay un access token válido para esta API. No hace falta ninguna llamada de red. Qué lleva el punto: Access token. Tenant Lección 09 · Angular y MSAL
- MSAL Browser: MSAL se lo entrega a la app. Si hubiera vencido, MSAL lo renovaría con el refresh token: recorrido K. Qué lleva el punto: Access token. Tenant Lección 18 · Vencimiento, renovación y cierre de sesión
- App Angular: La app agrega el token a una URL fija, http://localhost:18095/api/requests/41, y a ningún otro destino. Qué lleva el punto: Access token. Kit Lección 09 · Angular y MSAL
- CORS y filtro bearer: Primero CORS: el preflight del navegador pregunta si localhost:18094 puede mandar un header Authorization, y la API nombra ese origen exacto. Después el filtro bearer toma el token. Qué lleva el punto: Access token. Kit Lección 21 · Amenazas en el navegador y decisiones de arquitectura
node lab.mjs cors - JwtDecoder [válido]: El decoder verifica la firma con la clave pública en caché, después el issuer, el vencimiento y el not-before, la audiencia, el tenant, la versión 2.0, el cliente permitido y un oid bien formado. Qué lleva el punto: Access token, Claves públicas de firma. Kit Lección 11 · Validá antes de confiar
node lab.mjs tokens - Conversor de authorities: Los claims se convierten en authorities: scp da SCOPE_Requests.Read y SCOPE_Requests.Approve. Alice no tiene rol, así que no hay ROLE_Approver. Qué lleva el punto: Access token. Kit Lección 12 · De los claims a las authorities de Spring
- Regla del método [scope ✓]: Leer necesita SCOPE_Requests.Read. Alice lo tiene. Kit Lección 07 · Scopes y consentimiento
- Controlador: En una transacción, el controlador fija app.tenant y app.subject a partir de tid y oid, y app.approver a partir del rol. Los tres son locales a la transacción. Qué lleva el punto: Contexto de la transacción. Kit Lección 17 · Transacciones, pools y carreras
- Pool de conexiones: Toma prestada una de las tres conexiones del pool. Todas son app_runtime, nunca el administrador. Qué lleva el punto: Contexto de la transacción. Kit Lección 15 · PostgreSQL autentica a la API
- app_runtime: PostgreSQL autentica a app_runtime: sin superusuario, sin BYPASSRLS, solo SELECT y UPDATE de la columna de estado. Qué lleva el punto: Contexto de la transacción. Kit Lección 15 · PostgreSQL autentica a la API
node lab.mjs database - Política RLS [RLS ✓]: El SQL ya dice id = 41, y el tenant y el dueño salen del token. La política agrega su propia condición: el mismo tenant, y ser dueño o aprobador. Qué lleva el punto: Contexto de la transacción. Kit Lección 16 · Row-level security como segundo límite
node lab.mjs rls - purchase_request [1 fila]: La fila 41 es de Alice, en el tenant de Alice: cumple tanto la consulta como la política. Qué lleva el punto: Contexto de la transacción. Kit Lección 14 · La propiedad es una regla de autorización
- Controlador: Vuelve la fila. El COMMIT termina la transacción, y el contexto desaparece con ella. Kit Lección 17 · Transacciones, pools y carreras
- App Angular [200]: HTTP 200 con la solicitud 41. La app la muestra; no decidió nada. Kit Lección 13 · Leé bien un rechazo
node lab.mjs boundary
Fin del recorrido: Una lectura cruzó cuatro verificaciones independientes: el token, la operación, la consulta del endpoint y la política de filas. Sacar cualquiera de ellas es una prueba que tendría que fallar.
F · Aprobar la solicitud de un colega
200 una vez, después 404
- node lab.mjs: El lab pide el caso approver: la identidad de Alice, con el rol Approver. Kit Lección 08 · Roles y reglas del recurso
node lab.mjs atomic - Emisor de tokens: El emisor lo firma con la clave del kit: scp trae los dos scopes, roles trae Approver. Qué lleva el punto: Token de prueba. Kit Lección 08 · Roles y reglas del recurso
- node lab.mjs: Salen dos POST /api/requests/42/approve en el mismo momento. La solicitud 42 es de Bob, y está PENDING. Qué lleva el punto: Token de prueba. Kit Lección 17 · Transacciones, pools y carreras
- CORS y filtro bearer: Sin navegador no hay Origin ni preflight: CORS no participa. El filtro bearer toma el token. Qué lleva el punto: Token de prueba. Kit Lección 21 · Amenazas en el navegador y decisiones de arquitectura
- JwtDecoder [válido]: En modo fixture el decoder confía en la clave del kit, y solo en ella. Firma, issuer, tiempo y contrato: válidos. Qué lleva el punto: Token de prueba, Claves públicas de firma. Kit Lección 11 · Validá antes de confiar
- Conversor de authorities: SCOPE_Requests.Approve a partir de scp, y ROLE_Approver a partir de roles. Qué lleva el punto: Token de prueba. Kit Lección 12 · De los claims a las authorities de Spring
- Regla del método [scope + rol ✓]: Aprobar necesita SCOPE_Requests.Approve y ROLE_Approver, los dos. Un OR acá dejaría que un token app-only actúe como una persona. Kit Lección 08 · Roles y reglas del recurso
- Controlador: Una sola sentencia verifica y cambia a la vez: UPDATE purchase_request SET status = 'APPROVED' WHERE id = 42 AND el tenant coincide AND owner_oid no es quien llama AND status = 'PENDING'. Qué lleva el punto: Contexto de la transacción. Kit Lección 17 · Transacciones, pools y carreras
- Política RLS [WITH CHECK ✓]: A través de una conexión app_runtime del pool. El WITH CHECK de la política deja que un aprobador cambie una fila de su tenant. Qué lleva el punto: Contexto de la transacción. Kit Lección 16 · Row-level security como segundo límite
- purchase_request [1 fila, después 0]: El primer UPDATE pasa la 42 a APPROVED. El segundo no encuentra ninguna fila PENDING: cambian 0 filas. Qué lleva el punto: Contexto de la transacción. Kit Lección 17 · Transacciones, pools y carreras
- Controlador [200 y 404]: Cambió una fila: 200 APPROVED. Ninguna fila: 404, la misma respuesta que para una solicitud que no existe. Kit Lección 13 · Leé bien un rechazo
- node lab.mjs [200 + 404]: El lab ve exactamente un 200 y un 404, y PostgreSQL dice APPROVED. Aprobar su propia solicitud 41 también da 404: el dueño no puede aprobar. Kit Lección 08 · Roles y reglas del recurso
node lab.mjs roles
Fin del recorrido: Un rol es una condición entre varias. La regla del método verifica scope y rol; una sola sentencia SQL verifica juntos el tenant, que no sea el dueño y PENDING, así que una carrera no puede aprobar dos veces.
G · 401: el token no se acepta
nueve tokens rotos, una puerta
- node lab.mjs: El lab le pide al emisor tokens rotos, un caso por vez. Kit Lección 11 · Validá antes de confiar
node lab.mjs signature - Emisor de tokens: Cada caso rompe una sola cosa: vencido, válido solo en el futuro, firmado con la clave de un desconocido, otro issuer, otra audiencia, un ID token, otro cliente, sin oid, otro tenant. Qué lleva el punto: Token de prueba. Kit Lección 11 · Validá antes de confiar
- node lab.mjs: Cada uno sale como GET /api/requests/41. Qué lleva el punto: Token de prueba. Kit Lección 13 · Leé bien un rechazo
- CORS y filtro bearer: El filtro bearer le pasa el token al decoder. Qué lleva el punto: Token de prueba. Kit Lección 13 · Leé bien un rechazo
- JwtDecoder [rechazado]: Cada caso falla exactamente una verificación: firma, issuer, exp o nbf, aud (también el ID token: su audiencia es la SPA), tid, azp u oid. Leer un payload no prueba nada: el decoder verifica antes de confiar en un solo claim, y sus claves salen de la configuración, nunca del token. Qué lleva el punto: Token de prueba, Claves públicas de firma. Kit Lección 11 · Validá antes de confiar
node lab.mjs time - CORS y filtro bearer [401]: La cadena de filtros responde 401 con WWW-Authenticate: Bearer. No se ejecutó ningún controlador y no se mandó ningún SQL. Kit Lección 13 · Leé bien un rechazo
node lab.mjs http - node lab.mjs [401 ✓]: El lab espera 401 para cada caso, y sigue esperando 200 para el token válido de Alice. Kit Lección 22 · Depurá sin filtrar credenciales
node lab.mjs audience
Fin del recorrido: 401 significa que la API no aceptó la credencial. Volver a iniciar sesión no arregla una audiencia equivocada: la arregla la configuración. Cada arreglo conserva su prueba negativa.
H · 403: aceptado, no permitido
un token genuino al que le falta una authority
- node lab.mjs: Dos tokens genuinos a los que les falta algo a cada uno: no-role tiene los scopes pero no Approver; app-only tiene Approver pero no scp, porque no inició sesión ningún usuario. Kit Lección 12 · De los claims a las authorities de Spring
node lab.mjs delegation - Emisor de tokens: Los dos están firmados con la clave del kit, para la audiencia, el tenant y el cliente correctos. Qué lleva el punto: Token de prueba. Kit Lección 12 · De los claims a las authorities de Spring
- node lab.mjs: Cada uno pide aprobar la solicitud 42. Qué lleva el punto: Token de prueba. Kit Lección 13 · Leé bien un rechazo
- CORS y filtro bearer: El filtro bearer toma el token. Qué lleva el punto: Token de prueba. Kit Lección 13 · Leé bien un rechazo
- JwtDecoder [válido]: Los dos pasan todas las verificaciones. La autenticación se cumple. Qué lleva el punto: Token de prueba, Claves públicas de firma. Kit Lección 11 · Validá antes de confiar
- Conversor de authorities: no-role da solo authorities SCOPE_. app-only da ROLE_Approver y ningún SCOPE_. Qué lleva el punto: Token de prueba. Kit Lección 12 · De los claims a las authorities de Spring
- Regla del método [403]: Aprobar necesita SCOPE_Requests.Approve y ROLE_Approver. A cada token le falta una de las dos. Kit Lección 08 · Roles y reglas del recurso
node lab.mjs roles - CORS y filtro bearer [403]: La cadena de filtros convierte el rechazo en 403. El controlador nunca se ejecutó. Kit Lección 13 · Leé bien un rechazo
- node lab.mjs [403 ✓]: Los dos reciben 403. Un token con solo Requests.Read recibe 403 para aprobar y sigue recibiendo 200 para leer: los scopes son por operación. Kit Lección 07 · Scopes y consentimiento
node lab.mjs scopes
Fin del recorrido: 403: la API sabe quién llama y rechaza esta operación. Un botón oculto nunca protegió nada; esta regla sí.
I · 404: Alice pide la solicitud de Bob
la identidad sale del token, nunca de la URL
- App Angular: Alice escribe 42 en lugar de 41. La página la deja: el campo de texto no es el límite. Kit Lección 14 · La propiedad es una regla de autorización
- CORS y filtro bearer: Un token genuino de Alice llega a la API. Qué lleva el punto: Token de prueba. Kit Lección 14 · La propiedad es una regla de autorización
- Regla del método [scope ✓]: Válido, con SCOPE_Requests.Read: la operación está permitida. Tener permiso para leer no es tener permiso para leer todo. Kit Lección 13 · Leé bien un rechazo
- Controlador: El id sale de la URL; el tenant y el dueño salen solo del token: WHERE id = 42 AND tenant_id = tid AND owner_oid = el oid de Alice. Qué lleva el punto: Contexto de la transacción. Kit Lección 14 · La propiedad es una regla de autorización
- Política RLS: Hasta una consulta que se olvidó el WHERE quedaría filtrada acá: la fila no es de Alice, y ella no es aprobadora. Qué lleva el punto: Contexto de la transacción. Kit Lección 16 · Row-level security como segundo límite
- purchase_request [0 filas]: Ninguna fila coincide. Kit Lección 14 · La propiedad es una regla de autorización
- Controlador [404]: Ninguna fila: 404, la misma respuesta que para un número que no existe, así la API no revela qué solicitudes existen. Kit Lección 13 · Leé bien un rechazo
- App Angular [404]: Alice ve 404. Bob, con su propio token, recibe 200 para la 42. La solicitud 43 vive en otro tenant: Alice recibe 404, y un token de ese tenant recibe 401. Kit Lección 14 · La propiedad es una regla de autorización
node lab.mjs owner
Fin del recorrido: La propiedad es una regla de autorización, que se aplica con la identidad tomada del token validado y nunca del pedido. RLS la repite debajo.
J · RLS, el segundo límite
la base de datos sin la API
- node lab.mjs: El lab se conecta directo a PostgreSQL y pasa a app_runtime, el rol que usa la API. Kit Lección 16 · Row-level security como segundo límite
node lab.mjs rls - Política RLS [0 filas]: No se fijó ningún contexto, así que la política compara tenant_id con NULL: ninguna fila califica. Kit Lección 16 · Row-level security como segundo límite
- purchase_request [count 0]: SELECT count(*) devuelve 0. No es un error: es una respuesta vacía y segura. Kit Lección 16 · Row-level security como segundo límite
- Política RLS: Ahora, dentro de una transacción con el tenant y el sujeto de Alice fijados, el lab ejecuta un SELECT sin ningún WHERE. Qué lleva el punto: Contexto de la transacción. Kit Lección 16 · Row-level security como segundo límite
- purchase_request [solo la 41]: Vuelve solo la fila 41. La 42 de Bob y la 43 del otro tenant siguen invisibles. Qué lleva el punto: Contexto de la transacción. Kit Lección 16 · Row-level security como segundo límite
- Política RLS [sin contexto]: Después del COMMIT, la misma conexión vuelve a ver 0 filas: set_config(name, value, true) era solo de esa transacción. Kit Lección 17 · Transacciones, pools y carreras
node lab.mjs pool - app_runtime [sin bypass]: Y el rol en sí no es superusuario ni BYPASSRLS, la tabla fuerza RLS, y app_runtime no puede reescribir owner_oid. Kit Lección 15 · PostgreSQL autentica a la API
node lab.mjs database
Fin del recorrido: RLS es un segundo límite, no el primero: confía en el contexto que fija la API. Lo que aporta es que un WHERE olvidado no devuelve nada en lugar de devolver todo.
K · Un rol quitado contra un token anterior
vencimiento, renovación y cierre de sesión
- Administrador: Ayer Alice aprobó solicitudes. Hoy el administrador le quita la asignación de Approver. Tenant Lección 18 · Vencimiento, renovación y cierre de sesión
- Enterprise applications: La asignación ya no está en la enterprise application de la API. No se empuja nada a los tokens ya emitidos. Tenant Lección 08 · Roles y reglas del recurso
- Token endpoint [próximos tokens]: Entra va a dejar afuera roles: Approver en el próximo access token que emita para Alice. Tenant Lección 18 · Vencimiento, renovación y cierre de sesión
- Caché de tokens: Mientras tanto, el access token de Alice en caché sigue diciendo roles: Approver, y vale hasta su exp. Qué lleva el punto: Access token, Refresh token. Tenant Lección 18 · Vencimiento, renovación y cierre de sesión
- Regla del método [todavía permitido]: Su próxima aprobación llega con ese token. La API valida localmente: la firma, el tiempo y los claims están bien, y el rol viejo todavía pasa. Spring no vuelve a leer las asignaciones en cada pedido. Un retiro más rápido hay que diseñarlo: duraciones más cortas, una consulta a una fuente de verdad, o continuous access evaluation donde aplique. Qué lleva el punto: Access token. Tenant Lección 18 · Vencimiento, renovación y cierre de sesión
- MSAL Browser: Más tarde vence el access token. Antes de la próxima llamada, acquireTokenSilent lo nota y usa el refresh token. Qué lleva el punto: Refresh token. Tenant Lección 18 · Vencimiento, renovación y cierre de sesión
- Token endpoint [sin rol]: Entra emite un access token nuevo. La asignación ya no está, así que roles viene vacío. Qué lleva el punto: Refresh token. Tenant Lección 06 · Tres trabajos de los tokens
- MSAL Browser: MSAL guarda el token nuevo en caché y se lo da a la app. Qué lleva el punto: Access token. Tenant Lección 09 · Angular y MSAL
- Regla del método [403]: La misma aprobación ahora recibe 403: el token es válido, pero el rol no está en él. Qué lleva el punto: Access token. Tenant Lección 08 · Roles y reglas del recurso
- App Angular: Alice cierra sesión. logoutRedirect limpia la caché de MSAL para su cuenta. Tenant Lección 18 · Vencimiento, renovación y cierre de sesión
- Endpoint de login [sesión terminada]: Entra termina su sesión en su endpoint de cierre de sesión. Los tokens ya emitidos no se retiran: siguen valiendo hasta que vencen. Tenant Lección 18 · Vencimiento, renovación y cierre de sesión
Fin del recorrido: Tres cosas distintas: la vida de un token, una sesión y una asignación. La renovación las conecta; nada retira un token ya emitido, por eso las duraciones importan.
L · Configurar el tenant
dos registros, consentimiento, un rol
- Administrador: En el Entra admin center, el administrador registra dos aplicaciones, no una: el destinatario del token tiene que quedar a la vista. Tenant Lección 04 · Dos registros, una experiencia de aplicación
- App registrations: El registro de la API: Application ID URI api://API_CLIENT_ID, scopes delegados Requests.Read y Requests.Approve, el app role de usuario Approver, access tokens v2. El registro de la SPA: un cliente público con la redirect URI http://localhost:18094/redirect, sin secreto. Tenant Lección 04 · Dos registros, una experiencia de aplicación
- Enterprise applications: Cada registro recibe un service principal en el tenant: su enterprise application. Tenant Lección 03 · Tenant, aplicación, service principal
- Enterprise applications: Ahí el administrador le asigna Approver a un usuario de prueba, y otorga el consentimiento si los usuarios no pueden consentir por su cuenta. Tenant Lección 08 · Roles y reglas del recurso
- Token endpoint [scp, roles]: Desde ahora, un access token para ese usuario y esta API trae los scopes consentidos en scp y Approver en roles. Tenant Lección 07 · Scopes y consentimiento
- Claves de firma: Spring va a verificar esos tokens con las claves publicadas para el issuer fijo del tenant. Tenant Lección 19 · Conectá un tenant real de Entra
- JwtDecoder [Modo Entra]: Con AUTH_MODE=entra, el decoder confía solo en https://login.microsoftonline.com/TENANT_ID/v2.0 y en sus claves. La clave del kit deja de ser de confianza. Tenant Lección 19 · Conectá un tenant real de Entra
node configure.mjs entra TENANT_ID SPA_CLIENT_ID API_CLIENT_ID ALICE_OID BOB_OID - Emisor de tokens [401]: Un token de prueba ahora recibe 401. La sonda prueba el cambio, no que una persona real haya iniciado sesión. Tenant Lección 19 · Conectá un tenant real de Entra
node tenant-probe.mjs
Fin del recorrido: Los registros son configuración, no prueba. El recorrido del tenant registra solo lo que observaste: un inicio de sesión, una lectura propia, un rechazo por rol y una aprobación permitida.
M · Lo que CORS y PKCE no frenan
un script adentro, alguien que llama desde afuera
- Script inyectado: Un script se mete en la página por un renderizado inseguro o una dependencia comprometida. Corre con el origen de la página. Modelo Lección 21 · Amenazas en el navegador y decisiones de arquitectura
- MSAL Browser [mismo origen]: Le puede pedir un token a MSAL igual que la app. PKCE protegió el canje del code; no hace nada contra código que ya corre en la página. Modelo Lección 21 · Amenazas en el navegador y decisiones de arquitectura
- Script inyectado: Ahora tiene un access token válido. Qué lleva el punto: Access token. Modelo Lección 21 · Amenazas en el navegador y decisiones de arquitectura
- App Angular: O simplemente maneja el código propio de la app para mandar pedidos. Qué lleva el punto: Access token. Modelo Lección 21 · Amenazas en el navegador y decisiones de arquitectura
- CORS y filtro bearer [parece válido]: La API ve un token válido desde un origen permitido. Nada distingue este pedido de uno de la propia Alice. Defensas: una CSP estricta, un renderizado seguro y dependencias mantenidas. Un backend for frontend guarda los tokens en un servidor detrás de una cookie HttpOnly, pero un script igual puede actuar a través de esa sesión. Qué lleva el punto: Access token. Modelo Lección 21 · Amenazas en el navegador y decisiones de arquitectura
- node lab.mjs [sin Origin]: CORS es una regla que cumplen los navegadores. El lab llama sin ningún header Origin, y la API responde como le respondería a cualquiera: 401 sin token, 200 con uno válido. Kit Lección 21 · Amenazas en el navegador y decisiones de arquitectura
node lab.mjs cors - CORS y filtro bearer [preflight 403]: Un preflight desde https://stranger.invalid recibe 403: un navegador bloquearía esa página. CORS nunca reemplazó al token. Kit Lección 21 · Amenazas en el navegador y decisiones de arquitectura
node lab.mjs cors
Fin del recorrido: CORS y PKCE cierran una puerta cada uno. Ninguno protege la API de alguien que tiene un token válido: eso lo hacen la validación y la autorización, y la prevención deja afuera a los scripts.
N · Otra API, otra audiencia
sin reenviar; on-behalf-of
- Controlador: Supongamos que el controlador tiene que leer el jefe de Alice desde Microsoft Graph. Modelo Lección 20 · Usuarios, workloads y APIs de más abajo
- Otra API [aud equivocada]: Reenviar el token entrante falla: su audiencia es la API de compras, y Graph lo tiene que rechazar. Qué lleva el punto: Access token. Modelo Lección 20 · Usuarios, workloads y APIs de más abajo
- Controlador: El diseño correcto: un servicio intermedio confidencial usa el flujo on-behalf-of en el token endpoint de Entra para obtener un token cuya audiencia sea Graph. Modelo Lección 20 · Usuarios, workloads y APIs de más abajo
- Otra API [no está en el kit]: Ese token es para Graph, bajo el consentimiento de Graph. Un proceso nocturno sin usuario usaría en cambio client credentials y su propia política de endpoints. Modelo Lección 20 · Usuarios, workloads y APIs de más abajo
Fin del recorrido: Un token es para una audiencia. Llegar a otra API en nombre del usuario es otro diseño, con su propio consentimiento y su propio modelo de amenazas; el kit lo deja como ejercicio.
Zonas
- Tu computadora
- La computadora de Alice: Windows con su TPM, el navegador y la pestaña donde corre la aplicación. En un dispositivo unido a Entra, el primer token del día se obtiene acá, al iniciar sesión en Windows, antes de que se abra ninguna app. Qué no hace: Nada de lo que hay acá decide qué puede hacer Alice en la aplicación. La computadora la controla su usuario, o quien controle esa sesión: la API y PostgreSQL vuelven a decidir en el servidor, con sus propias reglas. Lección 01 · Cuatro componentes, cuatro responsabilidades, Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- Windows
- El sistema operativo de un dispositivo unido al tenant. Al iniciar sesión en Windows, LogonUI le pasa las credenciales de Alice a LSA, cuyo proveedor CloudAP le inicia la sesión en Entra y guarda el Primary Refresh Token en su caché, protegido con el TPM. Acá empieza el single sign-on a la app. Qué no hace: Windows nunca le entrega el PRT al navegador ni a una aplicación, y no decide nada sobre las solicitudes de compra. En un dispositivo que no está unido a Entra no hay PRT, y el navegador pide credenciales. Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- Pestaña del navegador · localhost:18094
- La página de la aplicación, servida desde localhost:18094: Angular, MSAL y la caché de tokens en el sessionStorage de esta pestaña. La página inicia la sesión, le pide un token a MSAL antes de cada llamada y lo manda a la API. Qué no hace: La pestaña no es un límite de la API. Todo script que corre en ella comparte su origen y sus poderes, incluido uno inyectado, y el usuario puede cambiar la página o llamar a la API sin ella. Lección 09 · Angular y MSAL, Lección 21 · Amenazas en el navegador y decisiones de arquitectura
- Microsoft Entra ID · tu tenant
- Tu tenant es la instancia propia de Microsoft Entra ID de tu organización: un directorio, identificado por su tenant ID, con sus usuarios, grupos, dispositivos y aplicaciones. Acá cada aplicación tiene su registro y su service principal, se guardan los consentimientos y las asignaciones de roles, se autentica a las personas y a los dispositivos según las políticas del tenant, y se emiten los tokens desde /authorize y /token, firmados con claves que Entra publica. La API confía solo en tokens cuyo issuer es este tenant: https://login.microsoftonline.com/TENANT_ID/v2.0. Qué no hace: No conoce los datos de la aplicación: de quién es la solicitud 42, si está pendiente y quién la puede aprobar lo deciden la API y PostgreSQL. Una vez que emitió un token, no ve los pedidos que lo llevan y no lo puede retirar. Otro tenant es otro directorio, con otros usuarios: sus tokens traen otro issuer y otro tid, y la API los rechaza. Lección 03 · Tenant, aplicación, service principal, Lección 04 · Dos registros, una experiencia de aplicación, Lección 19 · Conectá un tenant real de Entra
- Admin del tenant
- Una persona con permisos sobre el directorio que trabaja en el Entra admin center. Antes de cualquier pedido, registra la API y la SPA, expone los scopes, otorga el consentimiento cuando los usuarios no pueden darlo y les asigna el rol Approver a los usuarios. Qué no hace: El administrador no está en el camino de ningún pedido y no aprueba ninguna compra. Un rol de administrador del directorio no vuelve aprobador a nadie en esta aplicación: eso es el app role Approver, asignado en la API. Lección 04 · Dos registros, una experiencia de aplicación, Lección 08 · Roles y reglas del recurso, Lección 19 · Conectá un tenant real de Entra
- Fuera del kit
- Recursos que el curso nombra pero el kit nunca llama, como Microsoft Graph: otra API, con su propia audiencia y sus propios permisos. Muestran por dónde seguiría un diseño: on-behalf-of para actuar en nombre de un usuario, client credentials para un proceso sin usuario. Qué no hace: Nada de esto corre en el kit ni en las actividades; el recorrido que llega acá es un modelo. Un token emitido para la API de compras no vale acá. Lección 20 · Usuarios, workloads y APIs de más abajo
- La API · Spring Boot · localhost:18095
- El resource server de Spring Boot en localhost:18095. Cada pedido cruza la cadena de filtros de seguridad, después la regla del método y después un controlador que abre una transacción y ejecuta un SQL cuyo tenant y cuyo dueño salen del token validado. Acá se toman las decisiones de negocio. Qué no hace: No guarda sesión ni tokens: cada pedido se juzga por su cuenta. No autentica personas; verifica la evidencia que emitió Entra, y nunca le reenvía ese token a la base de datos. Lección 01 · Cuatro componentes, cuatro responsabilidades, Lección 11 · Validá antes de confiar, Lección 14 · La propiedad es una regla de autorización
- Cadena de filtros de seguridad
- La parte de Spring Security que cruza cada pedido antes de cualquier controlador: CORS para el origen exacto, el filtro bearer, el JwtDecoder que verifica el token y el conversor que transforma sus claims en authorities. Escribe cada 401 y cada 403. Qué no hace: No sabe de quién es una fila ni si una solicitud está pendiente: eso se decide después, en el controlador y en PostgreSQL. El CORS que tiene es una regla que cumplen los navegadores, no autenticación. Lección 11 · Validá antes de confiar, Lección 12 · De los claims a las authorities de Spring, Lección 13 · Leé bien un rechazo
- Solo en el kit
- Piezas que existen solo en el lab local: el emisor de tokens, que firma tokens de prueba con la clave propia del kit, y lab.mjs, el ejecutor que manda pedidos y verifica PostgreSQL. Con ellas podés ver decidir a la API y a la base de datos sin un tenant. Qué no hace: Ninguna de las dos es Entra ni autentica a nadie. En modo Entra, la API deja de confiar en la clave del kit y el ejecutor se niega a correr. Lección 00 · Antes de empezar, Lección 19 · Conectá un tenant real de Entra
- PostgreSQL 18
- La base de datos de las solicitudes de compra. La API se conecta como app_runtime, un rol restringido, a través de un pool de conexiones; el row-level security filtra cada fila con el tenant y el sujeto que la API fija en cada transacción. Qué no hace: Nunca ve un token ni al usuario del navegador: autentica el rol de base de datos de la API. Su política confía en el contexto que fija la API; es un segundo límite, no el primero. Lección 15 · PostgreSQL autentica a la API, Lección 16 · Row-level security como segundo límite, Lección 17 · Transacciones, pools y carreras
Piezas
- Caché de tokens · sessionStorage de esta pestaña
- Donde MSAL guarda el ID token, el access token y el refresh token, y el verifier de PKCE mientras un inicio de sesión está en curso. El sessionStorage desaparece con la pestaña. Qué no hace: No es una bóveda: cualquier script que corra en este origen lo puede leer. El sessionStorage acorta cuánto duran los tokens, no quién los puede alcanzar en la página. El PRT y la cookie de sesión de Entra nunca están acá. Lección 09 · Angular y MSAL, Lección 21 · Amenazas en el navegador y decisiones de arquitectura
- MSAL Browser · PublicClientApplication
- La biblioteca de Microsoft dentro de la página. Ejecuta el flujo authorization code con PKCE, procesa el redirect, guarda los tokens en caché y los renueva sin interacción. Qué no hace: No guarda ningún secreto, porque un navegador no puede, y no toma decisiones de negocio. No puede distinguir el código propio de la app de un script inyectado en la misma página. Lección 09 · Angular y MSAL, Lección 05 · Seguí el authorization code
- Script inyectado
- Código que no debería estar en la página: un payload de XSS o una dependencia comprometida. Corre con el origen de la página y con todo el poder que ella tiene. Qué no hace: No necesita una contraseña ni rompe PKCE: actúa con lo que la página ya puede hacer. Solo lo frena la prevención: una CSP estricta, un renderizado seguro y dependencias mantenidas. Lección 21 · Amenazas en el navegador y decisiones de arquitectura
- App Angular · presenta, no decide nada
- La aplicación de una sola página en localhost:18094. Carga configuración pública, inicia la sesión, pide un token antes de cada llamada y lo envía a una URL fija de la API. Qué no hace: No hace cumplir ningún permiso. Un botón oculto es una comodidad: cualquiera puede cambiar el bundle, o llamar a la API sin él. Lección 01 · Cuatro componentes, cuatro responsabilidades, Lección 09 · Angular y MSAL
- Alice · una persona con una cuenta de trabajo
- La persona para la que actúa el sistema. Entra la autentica cuando inicia sesión en Windows en un dispositivo unido, y cuando la app le inicia la sesión; después, la API solo ve evidencia sobre ella: un token con su tenant ID y su object ID. Qué no hace: Nunca le da su contraseña a la app, y nada que pueda cambiar en su navegador decide qué puede leer o aprobar. Lección 00 · Antes de empezar, Lección 02 · Autenticación y autorización, Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- Login de Windows · LogonUI, LSA
- La pantalla de inicio de sesión de Windows, LogonUI. Toma las credenciales de Alice, su contraseña de trabajo o Windows Hello for Business, y se las pasa a LSA, la Local Security Authority, donde CloudAP le inicia la sesión en Entra. Qué no hace: No habla con Entra por su cuenta, y la app nunca ve lo que Alice escribe acá. Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- TPM · claves privadas
- El Trusted Platform Module, un componente de hardware. Guarda la clave privada del dispositivo, que firma el pedido del PRT, y la clave privada de transporte, que abre la session key que manda Entra. Después envuelve la session key con una clave propia. Qué no hace: Nunca entrega una clave privada, y ningún otro componente de Windows puede usar la session key que protege. Donde un dispositivo no tiene un TPM utilizable, las claves no se pueden atar al hardware. Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- CloudAP · en LSA, plugin de Entra
- El proveedor de inicio de sesión de Windows dentro de la Local Security Authority (LSA). Su plugin de Microsoft Entra convierte el inicio de sesión de Alice en Windows en un PRT, guarda el PRT y la session key en su caché, renueva el PRT al iniciar sesión en Windows cada 4 horas y arma una PRT cookie cuando el navegador la pide. Qué no hace: Nunca le entrega el PRT ni la session key al navegador ni a una aplicación. Las aplicaciones nativas le piden a WAM, el intermediario de tokens de Windows, que usa el mismo PRT y guarda sus refresh tokens cifrados con DPAPI; esta app de navegador no. Cómo verlo: dsregcmd /status, ejecutado como el usuario con la sesión iniciada: AzureAdPrt : YES en SSO State, y la hora de la última renovación. La salida nombra el dispositivo, el tenant y el usuario. Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- Navegador · navegación, cookies de Entra, SSO
- El navegador mismo, no la página. Lleva la pestaña a Entra y de vuelta, y guarda la cookie de sesión de Entra para login.microsoftonline.com. En un dispositivo unido a Entra, cuando abre una URL de inicio de sesión de Entra le pide a Windows una PRT cookie: Edge lo hace con un perfil que tiene iniciada la sesión de la cuenta de trabajo, y Chrome, con la extensión Microsoft Single Sign On. Qué no hace: Los scripts de la página, MSAL incluido, nunca ven la PRT cookie ni las cookies de Entra: son de otro sitio. Las ventanas privadas no le piden a Windows una PRT cookie. Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- Endpoint de login · /authorize
- Adonde va el navegador para iniciar sesión. Entra autentica a la persona, aplica las políticas del tenant, pide consentimiento cuando hace falta y devuelve un code de un solo uso a una redirect URI registrada. En un dispositivo unido a Entra, el navegador puede traer una PRT cookie en lugar de una contraseña. Entra fija su propia cookie de sesión; cerrar sesión termina esa sesión en un endpoint hermano. Qué no hace: En este flujo nunca le entrega tokens a la página, y no conoce las reglas de compra: de quién es la solicitud 42 no es asunto de Entra. Lección 05 · Seguí el authorization code, Lección 07 · Scopes y consentimiento, Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- Devices · emite el PRT
- El registro que Entra tiene de cada dispositivo unido: las mitades públicas de su clave de dispositivo y de su clave de transporte, registradas al unirlo, y si el dispositivo está habilitado. Cuando CloudAP inicia sesión, Entra verifica contra ese registro las credenciales, el nonce y la firma del dispositivo, y emite el PRT con una session key que solo ese dispositivo puede abrir. Qué no hace: La app nunca lo llama: solo lo hace el intermediario de inicio de sesión del dispositivo. Un dispositivo conocido prueba qué computadora pregunta, no quién puede aprobar una compra. Lección 10 · Inicio de sesión de Windows y Primary Refresh Token
- App registrations · SPA: redirect URI · API: scopes, rol
- Dos objetos de aplicación. El de la API define el recurso: su Application ID URI, los scopes delegados Requests.Read y Requests.Approve, el app role de usuario Approver y los access tokens v2. El de la SPA define un cliente público y su redirect URI. Qué no hace: Un registro es configuración, no prueba de nada en tiempo de ejecución. El registro de la SPA no guarda ningún secreto, y no tiene que guardarlo. Lección 04 · Dos registros, una experiencia de aplicación, Lección 03 · Tenant, aplicación, service principal
- Token endpoint · /token
- Canjea el authorization code con el verifier de PKCE, renueva con el refresh token y emite tokens firmados: un ID token para el cliente y un access token para la API. Qué no hace: Nunca ve los pedidos a la API. Una vez emitido un token, la API lo verifica por su cuenta, y nada lo retira. Lección 05 · Seguí el authorization code, Lección 06 · Tres trabajos de los tokens, Lección 18 · Vencimiento, renovación y cierre de sesión
- Claves de firma · JWKS
- Entra firma los tokens con claves privadas y publica las mitades públicas, con los metadatos del issuer, para que cualquier recurso pueda verificar una firma. Las claves rotan. Qué no hace: Una clave pública no puede firmar. Y un recurso encuentra las claves a partir de su issuer configurado, nunca de una URL escrita dentro de un token. Lección 11 · Validá antes de confiar
- Enterprise applications · consentimiento, asignación de roles
- Los service principals: cómo existe cada aplicación en este tenant. Acá viven los consentimientos y la asignación de Approver a usuarios. Qué no hace: Una asignación no llega a los tokens ya emitidos; da forma a los siguientes. Lección 03 · Tenant, aplicación, service principal, Lección 08 · Roles y reglas del recurso, Lección 07 · Scopes y consentimiento
- Administrador · Entra admin center
- Una persona con permisos de directorio que registra las dos aplicaciones, otorga el consentimiento y asigna el rol Approver. Qué no hace: Un rol de administrador del directorio no es aprobación de compras: administrar el tenant y aprobar solicitudes son autoridades distintas. Lección 04 · Dos registros, una experiencia de aplicación, Lección 08 · Roles y reglas del recurso, Lección 19 · Conectá un tenant real de Entra
- CORS y filtro bearer · la puerta de entrada
- La puerta de entrada de la API. CORS responde los preflights para el origen exacto localhost:18094; el filtro bearer toma el token del header Authorization y se lo pasa al decoder. La cadena escribe cada 401 y cada 403. Qué no hace: No hay sesión ni login con cookie, así que la protección CSRF está apagada a propósito. CORS no autentica a nadie. Lección 13 · Leé bien un rechazo, Lección 21 · Amenazas en el navegador y decisiones de arquitectura
- JwtDecoder · verificar, después confiar
- Verifica la firma con las claves públicas del issuer configurado, después el issuer y el tiempo, y después el contrato de la API: audiencia, tenant, versión 2.0, el cliente permitido (azp) y un oid bien formado. Qué no hace: Nunca toma un issuer ni una URL de claves del token, y no autoriza: un token válido igual puede recibir 403 o 404. Lección 11 · Validá antes de confiar
- Conversor de authorities · scp, roles
- Convierte el token validado en authorities de Spring: cada valor de scp pasa a ser SCOPE_ más su nombre, y el rol reconocido Approver pasa a ser ROLE_Approver. Qué no hace: No mapea nada más: ningún rol de directorio, ningún grupo y ningún estado del navegador se convierte en un permiso de compra. Lección 12 · De los claims a las authorities de Spring
- Regla del método · @PreAuthorize
- Un requisito por operación. Leer necesita SCOPE_Requests.Read. Aprobar necesita SCOPE_Requests.Approve y ROLE_Approver, los dos. Textos exactos, con hasAuthority. Qué no hace: No sabe de quién es una fila: eso le toca a la consulta, y a la política de abajo. Lección 08 · Roles y reglas del recurso, Lección 12 · De los claims a las authorities de Spring
- Controlador · una transacción, un SQL
- Abre una transacción, fija app.tenant, app.subject y app.approver con set_config(name, value, true) y ejecuta una sentencia parametrizada cuyo tenant y cuyo dueño salen del token validado. Qué no hace: Nunca toma la identidad de la URL, de un header ni del cuerpo: de quien llama sale solo el número de la solicitud. Lección 14 · La propiedad es una regla de autorización, Lección 17 · Transacciones, pools y carreras
- Pool de conexiones · 3 conexiones
- Hikari mantiene tres conexiones abiertas y presta una para cada transacción. Todas las conexiones entran como app_runtime. Qué no hace: No limpia los settings de sesión entre un préstamo y otro: por eso el contexto se fija dentro de la transacción y muere con ella. Lección 15 · PostgreSQL autentica a la API, Lección 17 · Transacciones, pools y carreras
- node lab.mjs · sin navegador
- El ejecutor de pruebas del kit, en tu computadora. Llama a la API con tokens de prueba con nombre, inspecciona los roles y las políticas de PostgreSQL y verifica cada estado esperado. Qué no hace: Se niega a correr contra el modo Entra, y nunca prueba un inicio de sesión real. Lección 00 · Antes de empezar, Lección 22 · Depurá sin filtrar credenciales, Lección 24 · Trabajo final: defendé un pedido
- Emisor de tokens · :18096
- Un servicio chiquito que firma JWT con la clave propia del kit, uno por caso con nombre: alice, bob, approver, expired, forged, no-scope, app-only y más. Publica esa clave pública en /jwks, y en modo fixture la app Angular le pide los tokens a él en lugar de a MSAL. Qué no hace: No es un proveedor OpenID ni es Entra: no autentica a nadie. Nunca lo expongas fuera de tu máquina. Lección 00 · Antes de empezar, Lección 11 · Validá antes de confiar
- Otra API · Microsoft Graph
- Un recurso de más abajo, con su propia audiencia y sus propios permisos. Qué no hace: No tiene que aceptar un token emitido para la API de compras. El kit no hace ninguna llamada hacia abajo. Lección 20 · Usuarios, workloads y APIs de más abajo
- purchase_request · 41 Alice · 42 Bob · 43 otro tenant
- Las filas de práctica: la 41 es de Alice, la 42 es de Bob, la 43 es de otro tenant. Cada una tiene un tenant, el oid de un dueño y un estado, PENDING o APPROVED. Qué no hace: Nada en una fila dice quién la puede ver: eso lo deciden la consulta y la política. Lección 14 · La propiedad es una regla de autorización, Lección 16 · Row-level security como segundo límite
- app_runtime · sin BYPASSRLS
- El principal de base de datos de la API: no es superusuario ni BYPASSRLS, puede hacer SELECT de la tabla y UPDATE solo de la columna de estado. Las migraciones usan otro rol. Qué no hace: No sabe nada de Alice: PostgreSQL autentica la conexión, no al usuario del navegador. El token de la API nunca llega a la base de datos. Lección 15 · PostgreSQL autentica a la API
- Política RLS · request_boundary
- Row-level security sobre purchase_request, forzada incluso para el dueño de la tabla. Para leer: el mismo tenant, y ser dueño o aprobador. Para cambiar: el mismo tenant y ser aprobador. Qué no hace: Confía en los textos de contexto que fija la API. Es un segundo límite, no una prueba criptográfica. Lección 16 · Row-level security como segundo límite
Tokens, claves, cookies
- D · Claves del dispositivo
- Dos pares de claves que Windows crea cuando el dispositivo se une a Entra. La clave del dispositivo firma sus pedidos; la clave de transporte le permite a Entra cifrar la session key solo para este dispositivo. De dónde viene: El dispositivo mismo, cuando se une a Entra. Dónde termina: Las mitades privadas quedan en el TPM; las públicas se registran con el dispositivo en Entra. Dónde está, momento a momento: Cuando el dispositivo se une: Windows crea los dos pares y registra las mitades públicas en Entra. Desde entonces: Las mitades privadas quedan en el TPM y nunca salen de ahí. En cada pedido del PRT: El TPM firma con la clave privada del dispositivo; Entra verifica la firma con la mitad pública.
- P · Primary Refresh Token (PRT)
- Un token que Entra le emite al intermediario de inicio de sesión del dispositivo, no a una aplicación. Con él, CloudAP le puede conseguir a Alice una sesión en Entra sin volver a pedirle credenciales. De dónde viene: Entra, al iniciar sesión en Windows, después de verificar las credenciales, el nonce y el dispositivo. Dónde termina: La caché de CloudAP dentro de LSA, solo en este dispositivo: vale 90 días y se renueva mientras se usa el dispositivo. Dónde está, momento a momento: Al iniciar sesión en Windows: Entra se lo emite a CloudAP, que lo guarda en su caché dentro de LSA. Mientras Alice trabaja: Se queda en esa caché. CloudAP lo renueva al iniciar sesión en Windows cada 4 horas. Cuando una app inicia sesión: Sigue en CloudAP: el navegador solo recibe una PRT cookie hecha a partir de él. Cuando deja de servir: A los 90 días sin renovarse, o cuando Entra lo invalida: usuario o dispositivo borrado o deshabilitado, o un cambio de contraseña si el PRT salió de la contraseña.
- S · Session key
- Una clave que Entra emite con el PRT. Los pedidos que usan el PRT se firman con ella, y eso prueba que vienen del dispositivo que recibió el PRT. De dónde viene: Entra, con el PRT, cifrada con la clave pública de transporte del dispositivo. Dónde termina: La caché de CloudAP, envuelta por el TPM; ningún otro componente la puede usar. Dónde está, momento a momento: Al iniciar sesión en Windows: Llega cifrada para la clave de transporte. El TPM la descifra y la vuelve a envolver con su propia clave. Después: CloudAP guarda la clave envuelta junto al PRT. En cada uso: El TPM firma con ella, por ejemplo una PRT cookie. La clave misma nunca sale del dispositivo.
- W · PRT cookie
- Un valor que CloudAP arma para un único pedido de inicio de sesión, con el nonce que Entra puso en la URL de inicio de sesión, firmado con la session key. Entra lo acepta como prueba de que Alice tiene la sesión iniciada en este dispositivo. De dónde viene: CloudAP, cuando el navegador abre una URL de inicio de sesión de Entra. Dónde termina: El header x-ms-RefreshTokenCredential de ese único pedido a /authorize. Dónde está, momento a momento: Cuando la pestaña va a Entra: El navegador se la pide a CloudAP, con el nonce de la URL. Un momento después: CloudAP la arma y el TPM la firma con la session key. Para un solo pedido: Viaja en el header x-ms-RefreshTokenCredential hacia /authorize. Los scripts de la página nunca la ven. Después: Está atada a ese nonce: el próximo inicio de sesión pide una nueva.
- E · Cookie de sesión de Entra
- La cookie que Entra fija para su propio sitio después de un inicio de sesión. Las visitas siguientes a /authorize pueden saltear las credenciales. Si el inicio de sesión usó una PRT cookie, queda atada a la session key del dispositivo, así que una copia no sirve desde otro dispositivo. De dónde viene: /authorize, después de que Alice inicia sesión. Dónde termina: Las cookies del navegador para login.microsoftonline.com, fuera del alcance de los scripts de la app. Dónde está, momento a momento: Después del inicio de sesión: Entra la fija para login.microsoftonline.com. Vive en el almacén de cookies del navegador, no en sessionStorage. En la próxima visita a /authorize: El navegador la manda de vuelta, y Entra puede responder sin pedir credenciales. Al cerrar sesión: Entra termina esa sesión en su endpoint de cierre de sesión.
- C · Authorization code
- Un code de un solo uso que Entra devuelve a la redirect URI registrada después del inicio de sesión. Dura poco y no sirve sin el verifier. De dónde viene: El endpoint de inicio de sesión de Entra, después del inicio de sesión. Dónde termina: MSAL lo canjea una vez en el token endpoint. Dónde está, momento a momento: Después del inicio de sesión: En el redirect de /authorize de vuelta a /redirect. Un momento después: El bridge de MSAL se lo pasa a MSAL, que lo canjea en /token con el verifier. Después del canje: Ya no sirve: un code se canjea una sola vez.
- V · Verifier de PKCE
- Un secreto al azar que MSAL crea para cada inicio de sesión, y su hash S256, el challenge. Primero viaja el hash; el verifier, solo en el canje. De dónde viene: MSAL, en el navegador. Dónde termina: El token endpoint lo compara con el challenge. Dónde está, momento a momento: Antes de /authorize: MSAL lo crea y lo guarda en la pestaña mientras el inicio de sesión está en curso. A /authorize va solo su hash. En /token: Se manda una vez, con el code. Entra calcula su hash y compara. Después: No se vuelve a necesitar: el próximo inicio de sesión hace uno nuevo.
- I · ID token
- El resultado del inicio de sesión para la app: quién inició sesión, para este cliente. Su audiencia es la SPA, no la API. De dónde viene: El token endpoint de Entra. Dónde termina: La caché de MSAL, para mostrar la cuenta. La API lo rechaza. Dónde está, momento a momento: En /token: Se emite con el access token y el refresh token. Después: En el sessionStorage de la pestaña, de donde MSAL lee la cuenta. Cuando se cierra la pestaña: Desaparece con el sessionStorage.
- A · Access token
- Un JWT firmado para la API de compras: audiencia, tenant, oid, scp, roles y límites de tiempo. Una credencial bearer: quien la tiene la puede usar. De dónde viene: El token endpoint de Entra, para los scopes de la API. Dónde termina: El header Authorization de cada llamada; Spring lo verifica cada vez. Dónde está, momento a momento: En /token: Se emite para los scopes y la audiencia de la API. Hasta que vence: En el sessionStorage de la pestaña, donde lo encuentra acquireTokenSilent. En cada llamada: Se copia en el header Authorization de un pedido. La API lo valida y no guarda nada: no hay sesión. Después de cerrar sesión: Ya no está en la pestaña, pero cualquier copia sigue valiendo hasta su exp.
- R · Refresh token
- Le permite a MSAL obtener tokens nuevos de Entra sin un nuevo inicio de sesión, dentro de las políticas del tenant. Emitido para una SPA, dura 24 horas desde que se emite, en una ventana que no se corre. De dónde viene: El token endpoint de Entra, al iniciar sesión. Dónde termina: La caché de MSAL; solo Entra lo vuelve a recibir. Dónde está, momento a momento: En /token: Se emite con los otros tokens. Durante 24 horas: En el sessionStorage de la pestaña. MSAL lo manda solo a /token, para renovar. Pasadas 24 horas: Vencido. MSAL prueba un iframe oculto contra /authorize; donde las cookies de terceros están bloqueadas eso falla, y un redirect consigue un code nuevo.
- K · Claves públicas de firma
- Las mitades públicas de las claves de firma, publicadas como JWKS. Con ellas cualquiera puede verificar una firma; nadie puede firmar. De dónde viene: Los metadatos de Entra; en modo fixture, el /jwks del kit. Dónde termina: La caché del decoder, que se refresca cuando aparece un key ID nuevo. Dónde está, momento a momento: Publicadas: En los metadatos de Entra para el issuer del tenant. En la API: En la caché del decoder, que las vuelve a buscar cuando un token nombra un key ID desconocido.
- T · Token de prueba
- Un JWT firmado con la clave propia del kit, con una sola cosa cambiada por caso: vencido, falsificado, otra audiencia, sin scope, sin usuario... De dónde viene: El emisor de tokens en :18096. Dónde termina: La API en modo fixture. En modo Entra recibe 401. Dónde está, momento a momento: A pedido: Lo firma el emisor para un caso con nombre. Durante una llamada: Lo tiene el ejecutor del lab, que lo manda en el header Authorization. Después: Nadie lo guarda: la API no almacena ningún token.
- X · Contexto de la transacción
- app.tenant, app.subject y app.approver, fijados con set_config(name, value, true). Existen solo dentro de la transacción actual. De dónde viene: El controlador, a partir de tid, oid y ROLE_Approver. Dónde termina: Lo lee la política RLS; lo borra el COMMIT o el ROLLBACK. Dónde está, momento a momento: Dentro de la transacción: Lo fija el controlador en la conexión prestada. Durante el SQL: Lo lee la política RLS. En el COMMIT o el ROLLBACK: Se borra: quien tome la conexión después no ve nada de él.