Sign-In, Permissions and Access¶
Summary¶
Separates authentication from authorization and teaches server-side checks on every route and every object, roles, least privilege and safe invite flows.
Concepts Covered¶
This chapter covers the following 25 concepts from the learning graph:
| Concept | Concept Impact Score |
|---|---|
| Authentication | 74 |
| Authorization | 48 |
| Identity | 1 |
| Session | 16 |
| Cookie | 6 |
| Auth Token | 9 |
| OAuth Sign-In | 2 |
| Auth Provider | 1 |
| Magic Link Sign-In | 1 |
| Multi-Factor Authentication | 1 |
| Role | 8 |
| Role-Based Access Control | 6 |
| Admin Account | 1 |
| Least Privilege | 2 |
| Least Privilege Key | 1 |
| Protected Route | 6 |
| Server-Side Check | 10 |
| Client-Only Check Gap | 6 |
| Object Ownership Check | 3 |
| Insecure Direct Object Ref | 2 |
| 404 Instead of 403 | 1 |
| Share Code Access | 1 |
| Invite Flow | 3 |
| Invite Token | 1 |
| Plaintext Password in Email | 1 |
Prerequisites¶
This chapter builds on concepts from:
The Hotel Key Card¶
A traveler reaches a hotel late at night. At the front desk the clerk asks for a photo ID and the card the room was booked with. She looks at the face, looks at the photo, types for a moment, and slides a plastic key card across the counter. "You're in 714. The gym is on the second floor, and the card works there too."
The traveler rides up, taps the card on the lock of 714, and the light turns green. On the way to the ice machine he taps it on 712 out of curiosity. The light turns red. He is a paying guest with a valid card, and the door still stays shut. The card says who he is, and the lock decides which doors that person may open.
Who Gets Through Which Door
Gate or wall? Who may see what is a wall. Once a stranger has read a member's scan, no fix can make them forget it. By the end of this chapter you'll know how to find the doors in your app that have a sign on them but no lock, and how to get your agent to fit the lock.
Down the hall a housekeeper pushes a cart. Her card opens every room on the floor, but only during her shift. The night manager carries a master card that opens every door in the building, and she keeps it on a lanyard and never lends it out. At checkout the traveler's card stops working, even though it is still in his wallet.
The hotel gets two more things right. The door marked "Staff Only" next to the elevator has a lock on it, because a sign alone stops only polite people. A stranger calls the desk to ask which room a certain guest is in. The clerk doesn't say "she's in 712, but I can't let you up." The clerk says "I can't give out that information," and the caller learns nothing at all.
Your app has the same jobs as that hotel. It checks who someone is, decides which doors they may open, and puts the lock on the door rather than trusting a sign. It guards the master cards, and it never confirms a guest to a stranger. The AI agent that built your app probably got some of these right and may have skipped others.
Who Are You, and What May You Do?¶
A front desk and a door lock answer two different questions. Software gives each question its own name, and mixing them up is one of the most common causes of data leaks in web apps.
Authentication is the work of proving who someone is. When a member types an email and password, taps "Sign in with Google," or clicks a link sent to their inbox, the app is authenticating them. Authentication ends with a confident answer to one question: which account is this?
That answer is an identity: the account the app believes it is talking to, usually stored as a user ID such as user_381. Everything the app does for a signed-in person hangs off that ID. A member's scans, payments and settings all carry it, and later checks compare against it.
Authorization is the work of deciding what a known identity is allowed to do. Can this member open this scan? Can this teammate change the app's settings? Can this person refund a payment? Authentication happens once at sign-in, and after that the server only re-checks the proof of sign-in each request carries. Authorization runs in full on every single request, because each request asks for something different.
These two jobs fail in different ways, and that is why the split matters. A broken authentication check lets a stranger in. A broken authorization check lets a member who signed in properly reach things that belong to someone else. This second kind is far more common in apps built quickly, because the sign-in screen is visible and gets tested, while the authorization checks are invisible and easy to forget.
Three Requests¶
Here are three requests that reach the dating-safety app's server in the same minute. Walk through what each question needs.
- A request arrives for the list of scans, with no sign-in attached. Authentication fails, because the app can't say who this is. Here the server should refuse and ask the person to sign in. Chapter 2 introduced the HTTP status code for this, 401, which means "I don't know who you are."
- A request arrives from Maya, signed in, asking for scan 1042, which Maya ran last week. Authentication passes: this is Maya. Authorization passes: scan 1042 belongs to Maya. The server sends it back.
- A request arrives from Maya, signed in, asking for scan 1043, which belongs to another member. Authentication passes, since this is still Maya. Authorization fails, because the scan isn't hers. The server must refuse.
Request three is the one that matters. Maya is signed in, the screen looks normal, and nothing in the request looks like an attack. Only an authorization check on the server stops it.
| Authentication | Authorization | |
|---|---|---|
| The question | Who are you? | May you do this? |
| Hotel version | ID at the front desk | The lock on each door |
| When it runs | Once at sign-in; each request then carries proof of it | On every request |
| What it produces | An identity, such as user_381 |
A yes or a no for one action on one thing |
| Status code when it fails | 401 | 403, or 404 for someone else's object |
| How it usually breaks in AI-built apps | Rarely; sign-in libraries are mature | Often; checks are missing on some routes or objects |
Tell your agent
"List every route in the server. For each one, tell me two things in a table: does it require the person to be signed in, and after that, what does it check about whether this person may do this particular thing? Mark any route where the second answer is 'nothing.' Don't change any code yet."
Staying Signed In: Sessions, Cookies and Tokens¶
A member signs in once, and then clicks around the app for twenty minutes without typing a password again. Something has to carry the proof of sign-in from one request to the next, because web servers don't remember anything between requests on their own. Chapter 2 showed that each HTTP request arrives as a separate message. The server has to be told, every time, who is asking.
A session is the app's record that a particular identity signed in and is still allowed to act. When the member signs in, the server creates a session. It is a row in the database, or an entry in memory, that says "session a8f3... belongs to user_381 and expires at 11 p.m." The session ID is a long random string that nobody could guess. As long as the session exists and hasn't expired, the member stays signed in. Signing out deletes the session. Expiring it is how the hotel card stops working at checkout.
Next, the browser needs somewhere to keep the session ID so it can send it back. A cookie is a small piece of data that a server asks the browser to store and to send back automatically with every later request to the same site. After sign-in, the server's response includes a line asking the browser to keep a cookie holding the session ID. From then on, the browser attaches that cookie to each request without any code in the app having to remember it.
Cookies have settings that matter for safety. Three are worth knowing by name, because you will see them in code your agent writes.
- HttpOnly means scripts running in the page can't read the cookie. If an attacker manages to run code in the page, they still can't copy the session ID.
- Secure means the browser sends the cookie only over HTTPS, the encrypted form of web traffic that Chapter 8 covers, never over a plain connection someone could listen to.
- SameSite limits when the browser sends the cookie on requests that start from other websites. Chapter 16 explains the attack this defends against.
An auth token is a string that proves who the bearer is and is sent with each request in place of, or alongside, a session cookie. Some apps put the token in a request header instead of a cookie, especially apps with a mobile client. Some tokens carry the user ID and an expiry inside them, signed by the server so they can't be altered. Others are random strings the server looks up, just like a session ID. Either way, whoever holds the token is treated as that user. That makes a token as sensitive as a password for as long as it is valid. Chapter 6 covered how secrets leak, and every one of those leaks applies to tokens too.
What the Browser Sends¶
Here is what happens when Maya signs in to the dating-safety app and then opens her scan list. Both blocks below are trimmed to the parts that matter. The first block is the server's reply to a correct password. The Set-Cookie line asks the browser to store the session ID with the three safety settings. In the second block, Maya asks for her scan list, and the browser sends the cookie back on its own.
HTTP/1.1 200 OK
Set-Cookie: sid=a8f3c19e77b2...; HttpOnly; Secure; SameSite=Lax; Max-Age=28800
GET /api/scans HTTP/1.1
Cookie: sid=a8f3c19e77b2...
The server reads sid, looks up the session, finds user_381, and now knows it is talking to Maya. Max-Age=28800 means the cookie lasts eight hours. Nothing in the second request says "Maya." That cookie stands in for her, which is why a stolen cookie is as good as a stolen password until it expires.
Follow the same path one step at a time in this diagram.
Diagram: From Sign-In to Every Request¶
Run the From Sign-In to Every Request MicroSim Fullscreen
From Sign-In to Every Request
Type: workflow
sim-id: sign-in-to-every-request
Library: Mermaid
Status: Specified
Bloom Level: Understand
Bloom Verb: explain
Learning Objective: The learner will explain how a session ID created at sign-in travels in a cookie and lets the server identify the member on each later request, and where authorization happens in that path.
Prerequisites: authentication, identity, authorization, session, cookie, HttpOnly, Secure, status code 401 (all defined in the sections above).
Evidence of Mastery: After exploring the flowchart, the learner answers four multiple-choice questions shown below it. An answer is correct when it matches the answer key. Mastery is 4 of 4. Clicking nodes is exploration, not evidence.
Misconceptions: (1) The server remembers who you are between requests without being told. (2) Once a member is signed in, every request they make is allowed. (3) The cookie holds the member's password.
Instructional Rationale: Explaining a process needs the learner to see each step in order and say what it does. A clickable flowchart lets the learner open each step's job, and the questions check that they can explain the path, not just recognize it.
Content:
Nodes, in order, with the text shown when each is clicked:
- "Member enters email and password" — The browser sends the email and password to the server once, over HTTPS.
- "Server checks the password" — Authentication. The server compares what was typed against the stored record. Wrong password: the flow goes to node 10.
- "Server creates a session" — The server stores a record: a random session ID, the member's user ID, and an expiry time.
- "Server sends Set-Cookie" — The response asks the browser to keep a cookie holding the session ID, marked HttpOnly and Secure. The password is never put in the cookie.
- "Browser stores the cookie" — Scripts in the page can't read it because it is HttpOnly.
- "Browser sends the cookie with each request" — This happens on every request to the same site without any app code.
- "Server looks up the session" — If the session is found and not expired, the server now knows the identity. If it is missing or expired, the flow goes to node 10.
- "Server checks authorization" — For this route and this object, may this identity do this? If not, the flow goes to node 11.
- "Server sends the data" — Status 200.
- "Status 401: please sign in" — The server doesn't know who is asking.
- "Status 403 or 404: refused" — The server knows who is asking, and the answer is no.
Edges: 1→2; 2→3 (password correct); 2→10 (password wrong); 3→4; 4→5; 5→6; 6→7; 7→8 (session valid); 7→10 (session missing or expired); 8→9 (allowed); 8→11 (not allowed); 9→6 (next request); 10→1 (sign in again).
Questions:
- "What does the browser send on each request to prove who the member is?" Options: the password; the session ID in a cookie; the member's email. Correct: the session ID in a cookie. Feedback: "The password is sent once, at sign-in. After that the cookie carries the session ID."
- "Maya's session expired an hour ago. She clicks her scan list. What happens?" Options: she sees her scans; status 401 and a sign-in screen; status 403. Correct: status 401 and a sign-in screen. Feedback: "An expired session means the server no longer knows who is asking, which is a 401."
- "Maya is signed in and asks for another member's scan. Which step refuses her?" Options: node 2, the password check; node 7, the session lookup; node 8, the authorization check. Correct: node 8. Feedback: "Her session is valid. Only the authorization check knows the scan isn't hers."
- "Why is the cookie marked HttpOnly?" Options: so it loads faster; so scripts in the page can't read the session ID; so it works on phones. Correct: so scripts in the page can't read the session ID. Feedback: "HttpOnly keeps the session ID away from any code running in the page."
Provenance: Flow and cookie settings from the section "Staying Signed In: Sessions, Cookies and Tokens." Member name Maya is illustrative.
Rules: Every node is clickable and shows its text. Each question allows one answer; correct is the option named above.
Learner Activity:
- The learner clicks each node from 1 to 11 and reads its text.
- The learner follows the two branches into node 10 and the one branch into node 11.
- The learner answers the four questions.
Feedback: Four questions, fixed order, one attempt each. Correct: "Right. " followed by the feedback text. Incorrect: "Not quite. " followed by the feedback text. The correct answer is revealed after each attempt. A count "n of 4" is shown at the end.
Starting State: The flowchart is shown with no node selected. A line above it reads "Click any step to see what it does."
Chapter Anchors: The cookie in the worked example lasts eight hours (Max-Age=28800). Status 401 means the server doesn't know who is asking. The three cookie settings named are HttpOnly, Secure and SameSite.
Tell your agent
"Show me exactly how this app keeps a member signed in. Where is the session or token stored, how long does it last, and what happens on sign-out? If it uses cookies, show me the cookie settings and tell me whether HttpOnly, Secure and SameSite are set. If it stores a token in localStorage (storage in the browser that any script on the page can read), tell me that too and explain the risk. Don't change anything yet."
Ways to Sign In¶
Most apps built with AI agents don't write their own sign-in from scratch, and that is a good choice. Checking passwords safely, storing them properly, handling resets and blocking guessing attacks is a lot of detail, and a mistake in any of it is a one-way door. Most builders instead hand the work to a service that does nothing else.
OAuth and Auth Providers¶
OAuth sign-in is the "Sign in with Google" or "Sign in with Apple" button. The member is sent to Google, signs in there, and Google sends them back with a token saying "this is the person with this Google account." The app never sees the member's Google password. OAuth is the name of the standard that defines how these hand-offs work, and a layer on top of it called OpenID Connect adds the part that says who the person is.
An auth provider is an outside service that handles sign-in for your app. Some, like Google and Apple, are the identity itself. Others, like Clerk, Auth0, Supabase Auth or Firebase Authentication, work in front of your app and offer passwords, OAuth buttons, magic links and the rest in one package. Using one moves the hardest parts of authentication onto a team that does it full time. It also makes the provider a vendor your app depends on, which Chapter 9 covers.
Magic Links¶
Magic link sign-in means the member types an email address, the app emails a link with a one-time token in it, and clicking the link signs them in. There is no password to forget or leak. Everything here rests on the token in the link, so it should be long and random, work only once, and expire within minutes. A magic link is only as safe as the member's email account. That is fine for most apps. It is worth thinking about in a safety app, where an abuser might share an inbox with the person they are watching.
Multi-Factor Authentication¶
Multi-factor authentication, or MFA, asks for a second proof after the first: a code from an authenticator app, a text message, or a tap on a security key. A stolen password alone is then not enough. MFA matters most on the accounts that can do the most damage. For the dating-safety app, that means the builder's own accounts on the hosting platform, the database, Stripe and GitHub, and any admin account inside the app itself.
Here is how the options compare for an app like the dating-safety app.
| Method | What the member does | What can go wrong | Good fit when |
|---|---|---|---|
| Email and password, built in-house | Types a password | Weak storage, no guess limits, risky reset emails | Rarely the best choice for a small team |
| OAuth through Google or Apple | Taps a button | Member loses access to that account | Most consumer apps |
| Auth provider with passwords | Types a password the provider stores | Provider outage or misconfiguration | You want passwords without building them |
| Magic link | Clicks a link in email | Long-lived or reusable links; shared inboxes | Members sign in rarely |
| Any of the above plus MFA | Adds a code or a tap | Lost phone needs a recovery path | Admin accounts, always |
Tell your agent
"Tell me how members sign in to this app and which library or provider does it. If we wrote any password checking or storage ourselves, list those files. Then list every account that can change production: hosting, database, payments, GitHub, and admin accounts in our own app. Tell me which of them don't have multi-factor authentication turned on."
Roles and Least Privilege¶
Not everyone who signs in should be able to do the same things. In the hotel, a guest, a housekeeper and the night manager all carry cards, and each card opens a different set of doors.
A role is a named set of permissions given to an account, such as "member," "viewer" or "admin." Instead of listing every permission for every person, the app gives each account a role, and the role decides what the account may do. When a new teammate joins, you choose a role and you are done.
Role-based access control, often shortened to RBAC, is the practice of making every authorization decision by checking the role of the identity making the request. A route that changes app settings asks "is this person's role allowed to change settings?" rather than "is this person Alex?" RBAC keeps the rules in one place where you can read them.
An admin account is an account whose role can do almost anything: change settings, see every member's records, issue refunds, delete accounts. Admin accounts are the master card on the lanyard. They should be few, they should always have MFA, and nobody should use one for everyday work when a smaller role would do.
Least privilege is the rule that every person, program and key gets only the access it needs for its job, and no more. A teammate who answers support email gets a viewer role, not admin. A background job that sends reminder texts gets permission to read phone numbers, not to delete scans. When something goes wrong, least privilege limits the blast radius from Chapter 1: a stolen viewer account can see some things, and a stolen admin account can do everything.
A least privilege key applies the same rule to the API keys from Chapter 6. Many services let you create a key that can do only certain things. Stripe offers restricted keys that can create charges but not issue payouts. A database can have a user that can read and write rows but can't drop tables. A storage bucket can have a key that uploads to one folder. If the key leaks, the damage stops at what that key could do.
The Dating-Safety App's Roles¶
The dating-safety app has members who run scans, and a small team area where the builder and helpers can look at reports and change settings. Inside it are two roles, admin and viewer. Here is what each role should be allowed to do, written as the rule the code must follow.
| Action | Member | Viewer | Admin |
|---|---|---|---|
| Run a scan and see own results | Yes | No | No |
| See the team reports | No | Yes | Yes |
| Change app settings | No | No | Yes |
| Invite a teammate | No | No | Yes |
| Refund a payment | No | No | Yes |
Writing the table down is half the work. The other half is making sure the server enforces every "No" in it. That is where the dating-safety app had a gap. The viewer role existed, and the screens for viewers hid the buttons for changing settings. The server, though, never checked the role on those routes. Any signed-in teammate who sent the request directly could change settings, whatever their role said. Next we look at why this gap is so common and how to close it.
Tell your agent
"Write down every role this app has and what each one is supposed to be allowed to do, as a table of actions against roles. Then, for every row, show me the line of server code that enforces it. Mark any row where the only thing stopping a role is that a button is hidden in the browser."
The Lock Belongs on the Server¶
The "Staff Only" sign in the hotel stops polite guests. The lock stops everyone. Web apps have both kinds of barrier, and it is easy to mistake one for the other because they look the same from the outside.
A protected route is a route on the server that refuses requests unless the person is signed in and allowed to use it. Chapter 2 described routes as the addresses the server answers, such as /api/scans or /api/admin/settings. A route is protected only if code on the server runs a check before doing the work. A route that does the work for anyone who asks is open, no matter how hidden the button that calls it.
A server-side check is an authorization decision made by code running on the server, using the identity from the session and data the server trusts. It is the lock on the door. Nobody outside can change it, skip it or switch it off, because it runs on a machine they don't control.
The client-only check gap is what happens when an app hides or disables something in the browser but the server doesn't check the same rule. A browser front end, which Chapter 2 introduced, runs on the member's own device. Anyone can open the browser's developer tools, read the requests the page sends, and send their own. The tools are free and take minutes to learn. A hidden button is only the sign on the door.
AI agents create this gap often, and for an understandable reason. When asked to "make sure viewers can't change settings," the quickest visible fix is to hide the button for viewers. The page then looks right, the builder clicks through it as a viewer, and the button is gone. Nothing on screen shows that the route behind the button still says yes to anyone.
Closing the Viewer Gap¶
Here is the shape of the fix for the dating-safety app's viewer gap. The code below is middleware, the shared step from Chapter 3 that runs before a route's main work. requireRole("admin") returns a function that looks at req.user, the identity the server found from the session. If there is no identity, it answers 401. If the role is wrong, it answers 403. Only if both checks pass does next() let the request through to the route.
// Runs before the route. Stops anyone who isn't signed in or lacks the role.
function requireRole(...allowed) {
return (req, res, next) => {
if (!req.user) return res.status(401).json({ error: "Please sign in" });
if (!allowed.includes(req.user.role)) {
return res.status(403).json({ error: "Not allowed" });
}
next();
};
}
app.get("/api/team/reports", requireRole("viewer", "admin"), listReports);
app.patch("/api/team/settings", requireRole("admin"), updateSettings);
With this in place, a viewer who sends a settings change gets a 403, no matter what the browser shows or hides. That hidden button can stay hidden, because a page that shows people only what they can use is good design. It is just no longer the only thing in the way.
Two Jobs, Two Places
Notice that the page and the server now do different jobs. The page decides what to show, which is a gate you can change any day. The server decides what to allow, which is a wall, so that rule has to live there even when the page already hides the button.
The fix also needs a test, or it will quietly come undone the next time an agent adds a route. The test signs in as a viewer, sends the settings change straight to the server, and expects a 403. Chapter 10 covers writing tests like this one, and Chapter 17 shows how to make one run on every change.
Diagram: Access Matrix Gap Finder¶
Run the Access Matrix Gap Finder MicroSim Fullscreen
Access Matrix Gap Finder
Type: diagram
sim-id: access-matrix-gap-finder
Library: html
Status: Specified
Bloom Level: Analyze
Bloom Verb: differentiate
Learning Objective: The learner will differentiate, in a matrix of actions against roles, the cells where only the browser blocks an action (a client-only check gap) from cells that are safe or only inconvenient.
Prerequisites: role, role-based access control, admin account, protected route, server-side check, client-only check gap (all defined in the sections above).
Evidence of Mastery: The learner flags every cell that is a client-only check gap and no other cell. A cell is a gap when the browser hides the action and the server allows it for a role that the rule says should be refused. Mastery is all 3 gaps flagged with 0 wrong flags, within two attempts.
Misconceptions: (1) If the button is hidden, the action is blocked. (2) Any mismatch between browser and server is a security hole. (3) Admins can't have gaps because they are allowed everything.
Instructional Rationale: Differentiating needs the learner to compare two signals in each cell against a rule. A matrix puts the browser's behavior and the server's behavior side by side, so the learner must read both, and the distractor cell (shown but refused) checks that they can tell a broken button from a leak.
Content:
The matrix has 6 actions as rows and 3 roles as columns: "Signed-out visitor," "Viewer," "Admin." Each cell shows two labels: "Browser: shown" or "Browser: hidden," and "Server: allows" or "Server: refuses." Clicking a cell reveals the role rule for that cell.
| Action | Signed-out visitor | Viewer | Admin |
|---|---|---|---|
| 1. See the team reports | hidden / refuses — rule: refuse | shown / allows — rule: allow | shown / allows — rule: allow |
| 2. Change app settings | hidden / refuses — rule: refuse | hidden / allows — rule: refuse (GAP) | shown / allows — rule: allow |
| 3. Invite a teammate | hidden / refuses — rule: refuse | hidden / allows — rule: refuse (GAP) | shown / allows — rule: allow |
| 4. Delete a member account | hidden / refuses — rule: refuse | hidden / refuses — rule: refuse | shown / refuses — rule: allow (broken button, not a gap) |
| 5. Export all scans | hidden / refuses — rule: refuse | hidden / refuses — rule: refuse | shown / allows — rule: allow |
| 6. Refund a payment | hidden / refuses — rule: refuse | hidden / allows — rule: refuse (GAP) | shown / allows — rule: allow |
Each kind of cell has its own feedback text.
- Gap cell (rows 2, 3 and 6, Viewer): "Gap. The browser hides this from viewers, but the server still says yes. Anyone who sends the request directly gets through."
- Broken-button cell (row 4, Admin): "Not a security gap. The button shows but the server refuses, so the admin can't do something they should. That is a bug to fix, and nothing leaks."
- Safe cell (every other cell): "Safe. The server enforces the rule."
Provenance: Row 2, Viewer, is the dating-safety app's gap from research/seed-notes.md ("viewer role never enforced on server"). Rows 3, 4, 5 and 6 and all other cell values are illustrative and must be labeled "illustrative."
Rules: A cell is a gap if and only if Browser is "hidden," Server is "allows," and the rule is "refuse." The total is 18 cells: 3 gaps, 1 broken button, 14 safe.
Learner Activity:
- The learner reads the role table above the matrix.
- The learner clicks any cell to flag or unflag it as a gap.
- The learner presses Check.
- Each flagged or missed cell shows its feedback text.
- The learner should notice that all three gaps are in the Viewer column and all have "Browser: hidden."
Feedback: Two attempts. After the first Check, correct flags are confirmed, wrong flags show the safe or broken-button text, and the number of missed gaps is shown without naming them. After the second Check, all three gaps are revealed. The result "n of 3 gaps found, m wrong flags" is shown each time.
Starting State: All 18 cells unflagged. The prompt reads "Which cells let a role do something only the browser was stopping?"
Chapter Anchors: The dating-safety app has two team roles, admin and viewer. The viewer gap was on changing settings. Status 403 is the answer a viewer should get.
Tell your agent
"For every route under the team or admin area, write a test that signs in as each role and calls the route directly, without going through the page. Each test should expect the status code our role table says it should get. Run them and show me any that fail. Then show me your plan to fix each failure with a server-side role check, not by changing the page, and wait for my go-ahead."
Every Object, Not Just Every Route¶
Checking the route is not enough on its own. A member is allowed to use /api/scans/:id, the route that returns one scan. But which scans? A role check says yes to every member, and that is correct. A second check has to ask whether this member owns this particular scan.
An object ownership check is a server-side check that the specific record being requested belongs to the identity making the request, or that the identity has been given access to it. "Object" here means any single record: one scan, one photo, one payment, one report. The check usually happens in the database lookup itself, by asking for the scan with this ID and this owner.
An insecure direct object reference, often shortened to IDOR, is the gap that opens when a route looks up a record by the ID in the request and returns it without an ownership check. Record IDs are often numbers that count up, so a member who sees /api/scans/1042 in their address bar can try 1043, 1044 and so on. If the server answers, the member is reading strangers' scans. For a dating-safety app, each of those scans holds photos, voice clips and messages about someone's private life. IDOR is one of the most common serious flaws on the web, and it needs no special skill to find.
Scan 1043¶
Here is the difference in code. In the first version below, the code looks up the scan by its ID alone. In the second, it adds the owner to the query using Drizzle, the database library the dating-safety app uses. eq means "equals" and and means both conditions must hold, so the query finds a scan only if the ID matches and the owner is the person asking.
// Gap: returns any scan to any signed-in member who knows the ID.
const scan = await db.query.scans.findFirst({
where: eq(scans.id, req.params.id),
});
// Fixed: returns the scan only if it belongs to the person asking.
const scan = await db.query.scans.findFirst({
where: and(eq(scans.id, req.params.id), eq(scans.ownerId, req.user.id)),
});
if (!scan) return res.status(404).json({ error: "Not found" });
The dating-safety app got this right. Members can reach only their own scans, and a wrong ID gets the same answer as a scan that doesn't exist.
A Two-Minute Test
Sign in as a test member, open one of your own records, and change the ID in the address bar by one. If you see anything other than "not found," you have an IDOR, and you found it the same way an attacker would.
Why 404 Instead of 403¶
That last detail is a deliberate choice. Status 403 means "this exists, and you may not have it." Status 404 means "there is nothing here." 404 instead of 403 is the practice of answering "not found" when someone asks for an object that exists but isn't theirs. That answer reveals nothing about whether the object exists.
It matters because a 403 leaks information. If scan 1043 returns 403 and scan 99999 returns 404, an outsider learns which IDs exist, how many scans the app holds, and roughly how fast it is growing. In some apps, knowing that a record exists is itself private. This is the hotel clerk who says "I can't give out that information" instead of confirming the guest is upstairs. The dating-safety app returns 404 for someone else's scan, which is the safer choice. A 403 is still the right answer when the route itself is off limits, such as a viewer trying to change settings, because the route's existence is no secret.
Tell your agent
"Find every route that takes a record ID from the URL or the request body: scans, photos, reports, payments, anything. For each one, show me where the code checks that the record belongs to the signed-in person. Mark every route where the check is missing. For those, show me your plan: add the check to the database lookup itself, return 404 when the record isn't theirs, and add a test that signs in as one member and asks for another member's record by ID. Wait for my go-ahead before changing code."
Sharing Without Signing In: The 6-Digit Code¶
Sometimes a member wants to show a result to someone without an account, such as a friend or a sister who is worried about the same match. The dating-safety app lets members share a report, and anyone opening the shared report must type a 6-digit code.
Share code access is authorization by something the visitor knows instead of who they are. Visitors don't sign in. They present the code, and if it matches the one stored for that report, the server shows it. The member passes the code along separately, by text or in person, so the link alone isn't enough.
A code like this is only as strong as the limits around it. Six digits give one million possible codes:
That sounds like a lot until you count how fast a script can guess. A script trying 100 codes a second with no limit would try all of them in under three hours:
If the server instead locks a shared report after 5 wrong guesses, an attacker's chance of getting in falls to 5 in a million, with the same six-digit code.
So a share code needs three things around it to be good enough:
- A limit on wrong guesses for each report, after which the report locks or the code must be reissued.
- An expiry, so a report shared to help with one decision doesn't stay open for a year.
- The same 404 rule as scans: a wrong code gets "not found," never "wrong code for report R7," so a guesser can't learn which reports exist.
A member should also be able to turn sharing off for a report at any time.
You now have every rule a server needs to answer a request about a scan or a shared report. Try being the server yourself. This game hands you twelve requests and asks you to choose the status code for each.
Diagram: Play the Server¶
Run the Play the Server MicroSim Fullscreen
Play the Server
Type: microsim
sim-id: play-the-server-access
Library: p5.js
Status: Specified
Bloom Level: Apply
Bloom Verb: apply
Learning Objective: The learner will apply authentication, role, ownership and share-code rules to choose the correct status code (200, 401, 403 or 404) for each of twelve requests to the dating-safety app.
Prerequisites: authentication, authorization, session, role, protected route, object ownership check, insecure direct object reference, 404 instead of 403, share code access (all defined in the sections above).
Evidence of Mastery: For each of 12 request cards, the learner picks one status code. A card is correct when the pick matches the answer below. Mastery is 10 of 12 correct on the first attempt.
Misconceptions: (1) A signed-in member is allowed everything. (2) Someone else's scan should get 403. (3) An expired session is a 403. (4) A wrong share code should say "wrong code," which confirms the report exists.
Instructional Rationale: Applying a set of rules to new cases is the evidence for Apply. Each card is a fresh case, and the four possible answers force the learner to tell authentication failures (401) from authorization failures (403 or 404).
Content:
The people in the game are all illustrative. Maya is a member who owns scans 1042 and 1044. Jordan is a member who owns scan 1043. Sam has the team viewer role, and Alex has the team admin role. Report R7 is a shared copy of Maya's scan 1042 with share code 481920.
| Card | Who is asking | Request | Correct code | Why (feedback) |
|---|---|---|---|---|
| 1 | Nobody signed in | GET /api/scans/1042 | 401 | The server doesn't know who is asking. |
| 2 | Maya, signed in | GET /api/scans/1042 | 200 | Signed in, and the scan is hers. |
| 3 | Maya, signed in | GET /api/scans/1043 | 404 | The scan is Jordan's. Answer as if it doesn't exist. |
| 4 | Maya, signed in | GET /api/scans/99999 | 404 | No such scan. Same answer as card 3, so Maya can't tell the two apart. |
| 5 | Sam (viewer), signed in | GET /api/team/reports | 200 | Viewers may see team reports. |
| 6 | Sam (viewer), signed in | PATCH /api/team/settings | 403 | Signed in, but the viewer role may not change settings. The route's existence is no secret. |
| 7 | Alex (admin), signed in | PATCH /api/team/settings | 200 | Admins may change settings. |
| 8 | Maya, signed in | GET /api/team/reports | 403 | Members aren't on the team. |
| 9 | Nobody signed in | GET /api/shared/R7?code=481920 | 200 | The share code is correct. |
| 10 | Nobody signed in | GET /api/shared/R7?code=481921 | 404 | Wrong code. Don't confirm that report R7 exists. |
| 11 | Maya, session expired | GET /api/scans/1042 | 401 | An expired session means the server no longer knows who this is. |
| 12 | Maya, signed in | DELETE /api/scans/1043 | 404 | Deleting someone else's scan needs the same ownership check as reading it. |
Provenance: The 404-for-someone-else's-scan rule and the 6-digit share code are from the dating-safety app in research/seed-notes.md. The people, IDs, routes and the code 481920 are illustrative and must be labeled "illustrative."
Rules: No valid session and the route needs one: 401. Valid session, but the role may not use the route: 403. Valid session and role, but the object doesn't exist or isn't the requester's: 404. Shared route with a wrong code: 404. Otherwise: 200. Rules are applied in that order.
Learner Activity:
- The learner sees card 1 with four buttons: 200, 401, 403, 404.
- The learner picks one. The card shows correct or incorrect and its Why text.
- Cards come in the fixed order 1 to 12.
- After card 12, a summary shows the score and repeats the five rules.
- The learner should notice that cards 3 and 4 get the same answer.
Feedback: Twelve cards, one attempt each, fixed order. Correct: "Right. " followed by the Why text. Incorrect: "The server should answer [code]. " followed by the Why text. A running count "n of 12" is shown, with "Mastery reached" at 10 or more.
Starting State: Card 1 is shown with no answer picked. The prompt reads "You are the server. What do you answer?"
Chapter Anchors: The dating-safety app returns 404 for someone else's scan. Shared reports need a 6-digit code. Status 401 means the server doesn't know who is asking; 403 means it knows and the answer is no.
Tell your agent
"Show me how the shared-report code is checked. How many wrong guesses does the server allow before it stops answering for that report? Does the code expire? What does a wrong code return? If there is no guess limit, propose one, with a test that proves that after five wrong guesses even the right code is refused. Show me the plan before you change anything."
Inviting People In¶
Every team area needs a way to add people. An invite flow is the steps an app takes to bring a new person into an account or team. Someone with the right role enters an email address, and the app sends a message. When it works, the new person ends up with a working account and the role they were given. Every step is part of authentication, because the invite is how the new person proves they are the one who was invited.
The dating-safety app's invite flow had a gap that is common in apps built fast. When an admin invited a teammate, the app created the account with a password and put that password in the invite email.
A plaintext password in email is any password sent in readable form through email. It is a problem for several reasons at once. Email is stored on several servers and kept for years, so the password stays in the sender's sent folder, the recipient's inbox and any backup of either. Anyone who later gets into either mailbox gets the password too. Many people never change a password they were given, so the emailed one stays live. And the app had to know the password in readable form to send it, outside the safe, one-way storage that Chapter 8 describes.
The Old Emails Are Still Out There
Switching to invite tokens protects the next invite, not the last one. Every password already sent by email still works until someone changes it. Find the accounts that were created that way and force a password reset on their next sign-in.
The Fix: Invite Tokens¶
An invite token is a long random string, sent in an invite link, that lets one specific person finish creating their own account once. It is a kind of auth token, built for a single use. The new teammate clicks the link, the server checks the token, and the teammate sets their own password, or signs in with Google, on the spot. No password ever travels by email, and the app never knows the teammate's password at all.
A good invite token has five properties:
- It is long and random, so nobody can guess it.
- It works once. After the account is set up, the token is used up.
- It expires, usually within a few days.
- It is tied to the email address and role it was issued for.
- The server stores a hash of it rather than the token itself, so a database leak doesn't hand out live invites. Chapter 8 explains hashing.
Here are the two flows side by side, step by step.
| Step | Password in the email | Invite token |
|---|---|---|
| Admin invites a teammate | App makes up a password | App makes a random one-time token |
| What the email holds | The password, readable | A link with the token |
| Who chooses the password | The app | The teammate |
| If the mailbox is breached a year later | The password may still work | The token expired long ago |
| If the email is forwarded by mistake | The recipient can sign in as the teammate | The link works once, and only until it is used or expires |
Tell your agent
"Read our invite flow from start to finish and tell me exactly what goes in the invite email. If it contains a password, plan a switch to invite tokens: a random single-use token in the link, stored hashed, expiring in 72 hours, tied to the email and role, with the teammate setting their own password when they click. Include a test that a used or expired token is refused. Show me the plan before changing code. Also tell me which accounts were created with emailed passwords so I can ask those people to reset them."
Putting It Together: An Access Review¶
Everything in this chapter fits into one short review you can run on any app. It takes an afternoon with an agent, and it covers the must-be-right parts of sign-in and access that Chapter 1 named.
- Sign-in. Who handles it? Is any password logic home-grown? Do all production accounts and in-app admin accounts have MFA?
- Sessions. Where is the session kept, how long does it last, and are the cookie settings right?
- Routes. Does every route that needs sign-in check for it on the server?
- Roles. Is there a written table of what each role may do, and does the server enforce every "No" in it?
- Objects. Does every route that takes an ID check ownership in the query, and return 404 when the record isn't the requester's?
- Sharing. Are share codes limited, expiring and silent about whether a report exists?
- Invites. Do invites use single-use tokens, with no password in any email?
- Keys. Does each API key have only the access its job needs?
Each "no" is a gap in a must-be-right part, in Chapter 1's terms. Most are cheap to fix once found, and a test keeps each fix in place.
Tell your agent
"Run an access review of this app using these eight questions: sign-in, sessions, routes, roles, objects, sharing, invites and keys. For each one, answer yes or no, show me the code that proves the answer, and list what's missing. Put the result in docs/access-review.md. Don't change any code until I've read it."
Back to the Hotel¶
The traveler in room 714 never thought about any of this. His card opened his door and the gym and nothing else, the clerk told a stranger nothing, and at checkout the card went dead. Your members should get the same quiet experience, and they will if someone has written down who may do what and put the lock on the server. Chapter 8 turns to the data behind those doors: what to keep, how long to keep it, and how to protect the people it describes.
The Locks Are on the Doors
You can now tell a sign from a lock in your own app. You know to check the role on every route and the owner on every record, and to send invites that carry no password. Next, Chapter 8 asks which data behind those doors you should keep at all.
Key Takeaways¶
- Authentication proves who someone is. Authorization decides what that identity may do, and it runs on every request.
- A session cookie or auth token is as good as a password while it lasts. Set cookies HttpOnly, Secure and SameSite, and put multi-factor authentication on every account that can change production.
- Give each role only what its job needs (least privilege), and enforce every "No" in the role table with a server-side check. A hidden button is a client-only check gap.
- Check ownership of every object, not just every route, and answer 404 instead of 403 for someone else's record.
- A share code needs a guess limit and an expiry. An invite needs a single-use invite token, never a plaintext password in email.