Module 06 · Lesson 6.1
Authentication Versus Authorisation
On this page
- What you will learn
- Authentication and authorisation: two different questions
- 401, 403 or 404: choosing the right refusal
- Why the server must check every request
- Worked example: three checks in one handler, and how to test them
- Step-by-step workflow
- Working with an assistant on access control
- Conclusion and your next step
- Reusable prompt
- Expected output
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- References
Think of a hotel. At the desk, staff check your ID and hand you a key card. The card opens your room and the gym, but not the manager's office. Two different questions were asked: who are you, and what may you open?
Every web application asks the same two questions, and mixing them up causes real security bugs. In this lesson you learn the difference, choose the right answer for each kind of refusal, and add both checks to the Tidewell booking system. You then test them with made-up sign-ins, so you see a 401, a 403, a 404 and a 200 for yourself.
What you will learn
- Explain authentication and authorisation in plain words, with an example of each.
- Choose between 401, 403 and 404 for a refused request, and say why.
- Check sign-in, permission and ownership on the server, in the right order, on every request.
- Test both checks with fake sessions, including a refusal for every role that must be refused.
Before you start
- Completed Accessibility Basics for Forms, or have a working backend with endpoints and a problem format like the one in Error Handling and Backend Review.
- Access to any capable AI assistant.
- Optional: Node.js and the project from earlier lessons, if you want to run the examples.
Authentication and authorisation: two different questions
Until now, the Tidewell booking system trusted everyone. A stand-in function in Module 4 said "the patient is always Patient 1".
That was fine for learning. It is not fine for a real clinic, where patients, front-desk staff and physiotherapists must each see and do different things.
- Authentication
- Proving who someone is. It is the ID check at the hotel desk. The answer is an identity, such as "this is the person who owns patient.a@example.com".
- Authorisation
- Deciding what a known person may do. It is what the key card opens. The answer is yes or no for one action.
- Session
- The server's memory that a browser has already signed in, so people do not sign in on every click. The next lesson covers sessions in full.
- Role
- A job-shaped label, such as patient or physiotherapist, that carries a set of permissions.
- Ownership check
- A check that this particular record belongs to this person. A patient may cancel bookings, but only their own.
Authentication always comes first. You cannot decide what someone may do until you know who they are. But passing the first check never means passing the second.
401, 403 or 404: choosing the right refusal
A refusal should tell the caller what to do next, and nothing more. HTTP gives us status codes for this. Three of them matter here, and they are easy to mix up.
| Status | Question it answers | Tidewell example | Problem code |
|---|---|---|---|
| 401 | Do I know who you are? No. | Nobody is signed in, or the sign-in has expired. | sign-in-required |
| 403 | I know who you are. Is your role allowed to do this? No. | A physiotherapist asks for a booking's change history, which only front desk and the practice manager may see. | not-allowed |
| 404 | Does it exist, for you? No. | A patient asks for another patient's booking. It is not theirs, so it looks like it does not exist (FR-02.3). | not-found |
Why 404 for someone else's booking, and not 403? A 403 would say "that booking exists, but you may not have it".
That already leaks information. A 404 gives the same answer as for a booking that was never made, so nothing is revealed.
A 403 is fine when the thing is a feature, not a person's data. It is no secret that the clinic has a booking-history screen. Only the role is refused.
- Signed in?
No: 401
- Role allowed?
No: 403
- Input valid?
No: 400
- Is it yours?
No: 404
- Business rules
409, 422
- Do the work
200 or 201
Each check is cheaper and safer than the one after it. Stop at the first refusal.
Why the server must check every request
Suppose the menu hides the staff screens from patients. Is that enough? No.
Hiding a link is like removing a door sign: the door is still there. Anyone can type the address, or send a request with a tool, and skip your pages completely.
So the rule is simple. The interface may hide things to be helpful. The server decides, on every request, because it is the only part that nobody can change from outside.
- Every request, not just the first. People change roles, and staff leave. A check made once at sign-in goes stale. The
activeflag you meet in the next lessons is read again each time. - Sign-in required by default. A new endpoint needs a session unless someone has decided, and written down, that it is public. In Tidewell only the home page, the sign-in page and the list of clinicians are public.
- Facts come from the session, never from the request. A request body that says
"role": "practice_manager"or"patientId": 7is only a claim. The server reads the role and the patient from its own record of the session. - Both checks have tests. A test that only proves "allowed people get in" says nothing about the people who must be kept out.
Worked example: three checks in one handler, and how to test them
In Module 4, each handler received a patient id from a stand-in function. Now each handler asks for a session instead.
The first piece is the pair of new problems. They sit beside the others in problem.ts.
export const signInRequired = () =>
fail("sign-in-required", 401, "Sign-in required", "Please sign in to continue.");
export const notAllowed = (detail = "Your role is not allowed to do this.") =>
fail("not-allowed", 403, "Not allowed", detail);Next is what the rest of the code knows about a signed-in person. A session object holds only the facts the server needs: who, in which role, and which patient or clinician record they are linked to.
export interface Session {
userId: number;
role: Role;
patientId?: number;
clinicianId?: number;
}
// The sign-in library owns the cookie and the stored sessions. Handlers only see this function.
export type GetSession = (request: Request) => Promise<Session | null>;
export function requireSession(session: Session | null): Session {
if (session === null) throw signInRequired();
return session;
}Sessionis the small record handlers work with.patientIdis set only for patients, andclinicianIdonly for physiotherapists.GetSessionis a function type: give it a request, get a session ornull. The sign-in library does the real work behind it. Handlers never touch cookies.requireSessionturns "no session" into the 401 problem. After it, the code can rely on a real person being there.
The second check asks whether the role may do the action. You build the permission table in the lesson Roles and Permissions. For now, you only need to know that scopeOf looks up the role in that table and returns "any", "own" or "none".
// For handlers: throws 403 when the role may not do this at all, otherwise returns the scope.
export function requirePermission(session: Session, action: Action): Scope {
const scope = scopeOf(session.role, action);
if (scope === "none") throw notAllowed();
return scope;
}Now the handlers. Two of them use the checks: the patient's cancel, and a new staff-only endpoint for the change history from FR-05.
Look at the order in each one. The route.ts files under src/app/api are only a few lines that call these functions.
// A patient's own bookings: sign-in (401), then the role's permission (403), then the id.
async function patientContext(request: Request, deps: Deps) {
const session = requireSession(await deps.getSession(request));
requirePermission(session, "manage_own_booking");
if (session.patientId === undefined) throw notAllowed();
return { db: deps.db, patientId: session.patientId, now: deps.now() };
}// Staff only (FR-05): who changed this booking, and when.
export async function handleBookingChanges(request: Request, bookingIdText: string, deps: Deps): Promise<Response> {
try {
const session = requireSession(await deps.getSession(request));
requirePermission(session, "view_booking_history");
const parsed = parseBookingId(bookingIdText);
if (!parsed.ok) throw invalidRequest(parsed.errors);
return Response.json(await listBookingChanges(deps.db, parsed.value));
} catch (error) {
return errorResponse(error, { route: "GET /api/staff/bookings/{bookingId}/changes", log: deps.log, newRef: deps.newRef });
}
}What each part does
patientContextruns the first two checks for any patient action. It then builds the context from the session's patient id. The patient id never comes from the request.handleBookingChangeschecks sign-in, then theview_booking_historypermission, then the input. Only then does it call the service.- Every error goes to
errorResponse, so a 401 and a 403 look exactly like the 400 and 404 you already built. - The ownership check for patients is the one from Module 4:
WHERE id = $1 AND patient_id = $2. It is unchanged, but now$2comes from a trusted place.
Test both checks with fake sessions
To test without a real sign-in library, the test makes its own tiny session store. A cookie value such as patient-a maps to a session.
This is a fake for tests only. The real library does this lookup for you.
// Fake sessions: a cookie value maps to a session. The real sign-in library does this lookup for you.
const sessions = new Map<string, Session>([
["patient-a", { userId: 1, role: "patient", patientId: 1 }],
["patient-b", { userId: 2, role: "patient", patientId: 2 }],
["front-desk", { userId: 3, role: "front_desk" }],
["physio", { userId: 4, role: "physiotherapist", clinicianId: 1 }],
]);
async function getSession(request: Request): Promise<Session | null> {
const cookie = request.headers.get("cookie") ?? "";
const id = /(?:^|; )tw_session=([^;]+)/.exec(cookie)?.[1];
return id ? (sessions.get(id) ?? null) : null;
}
const db = await freshDatabase();
const deps: Deps = { db, now: () => NOW, getSession, log: () => {}, newRef: () => "ref-0001" };
function call(path: string, who: string | null, init: RequestInit = {}): Request {
const headers = new Headers({ "Content-Type": "application/json" });
if (who) headers.set("cookie", `tw_session=${who}`);
return new Request("http://localhost" + path, { ...init, headers });
}
async function show(label: string, response: Response) {
const text = await response.text();
console.log(`${label}\n ${response.status} ${text}`);
}Patient A first makes a booking on the slot that starts exactly 24 hours from the fixed test clock. Then six requests follow, one for each kind of answer.
await show("1. Nobody signed in asks for the booking's history", await handleBookingChanges(call("/api/staff/bookings/1/changes", null), "1", deps));
await show("2. Physiotherapist asks for the history", await handleBookingChanges(call("/api/staff/bookings/1/changes", "physio"), "1", deps));
await show("3. Patient A asks for the history", await handleBookingChanges(call("/api/staff/bookings/1/changes", "patient-a"), "1", deps));
await show("4. Patient B cancels Patient A's booking", await handleCancelBooking(call("/api/bookings/1/cancel", "patient-b", { method: "POST" }), "1", deps));
await show("5. Patient A cancels their own booking", await handleCancelBooking(call("/api/bookings/1/cancel", "patient-a", { method: "POST" }), "1", deps));
await show("6. Front desk asks for the history", await handleBookingChanges(call("/api/staff/bookings/1/changes", "front-desk"), "1", deps));401: nobody is signed in
1. Nobody signed in asks for the booking's history
401 {"type":"https://tidewell.example/problems/sign-in-required","title":"Sign-in required","status":401,"detail":"Please sign in to continue."}403: signed in, but the role is not allowed
2. Physiotherapist asks for the history
403 {"type":"https://tidewell.example/problems/not-allowed","title":"Not allowed","status":403,"detail":"Your role is not allowed to do this."}
3. Patient A asks for the history
403 {"type":"https://tidewell.example/problems/not-allowed","title":"Not allowed","status":403,"detail":"Your role is not allowed to do this."}404: allowed to cancel, but not this booking
4. Patient B cancels Patient A's booking
404 {"type":"https://tidewell.example/problems/not-found","title":"Not found","status":404,"detail":"We could not find that."}200: the right person, the right role
5. Patient A cancels their own booking
200 {"bookingId":1,"slotId":2,"clinicianName":"Clinician A","startsAt":"2026-12-01T10:00:00Z","endsAt":"2026-12-01T10:45:00Z","status":"cancelled"}
6. Front desk asks for the history
200 [{"action":"created","actorRole":"patient","actorId":1,"fromSlotId":null,"toSlotId":2,"changedAt":"2026-11-30T10:00:00Z"},{"action":"cancelled","actorRole":"patient","actorId":1,"fromSlotId":2,"toSlotId":null,"changedAt":"2026-11-30T10:00:00Z"}]Notice case 3. A patient is signed in, but still gets 403 for a staff-only endpoint.
Authentication proved who they are. It did not give them any staff rights.
The last line also shows FR-05 working. The change history lists the booking being created and then cancelled, with who did it. The test is deterministic: the clock is fixed, so you get the same text each time you run it.
Step-by-step workflow
Step 1: List the public endpoints
Write down every page and endpoint that needs no sign-in. Keep the list short. Everything not on it requires a session.
What you should see: A short list, such as the home page, the sign-in page and the list of clinicians.
Step 2: List the actions, not the screens
For each endpoint, name the action it performs, such as "view booking history". Permissions attach to actions, because one screen can do several things.
What you should see: One action name per endpoint.
Step 3: Add the session check first
Call
requireSessionat the top of every handler that is not public. Nothing else runs before it.What you should see: A signed-out request to any private endpoint gives 401.
Step 4: Add the permission check
Call
requirePermissionwith the action. Staff-only endpoints now refuse the wrong roles with 403.What you should see: A signed-in but wrong-role request gives 403.
Step 5: Put ownership in the lookup
For a person's own data, take the id from the session and put it in the WHERE clause, so other people's records look missing.
What you should see: Someone else's booking gives the same 404 as a missing one.
Step 6: Write the four tests for each endpoint
Signed out, wrong role, right role but wrong owner, and right role and right owner.
What you should see: Each answer in the table above is produced by a test.
- Signed out
Expect 401
- Wrong role
Expect 403
- Wrong owner
Expect 404
- Right person
Expect 200
If an endpoint has no wrong-owner case, write down why. Staff endpoints often do not need one.
Working with an assistant on access control
| Task | Assistant's part | Your part |
|---|---|---|
| List the actions behind each endpoint | Reads your contract and proposes action names. | Remove actions no requirement needs. Name the roles yourself. |
| Review a handler | Spots a missing session check, or a check in the wrong order. | Confirm each finding by reading the code and running a test. |
| Write refusal tests | Drafts the signed-out and wrong-role cases. | Make sure every test can fail, and add the wrong-owner case. |
| Choose who may do what | Nothing. It guesses from typical systems. | Take the table to the practice manager and write down the answer. |
Conclusion and your next step
Authentication asks who you are. Authorisation asks what you may do. The server asks both, on every request, in the same order: signed in, role allowed, input valid, record yours. Each refusal has its own answer, 401, 403 or 404, and each has a test.
Your next step: list the endpoints of your capstone and mark each as public or private, with its action name. Then continue to Sessions and Password Handling, where you learn how a session works and why you should never write sign-in code yourself.
For more on spotting weak spots in generated code, read STRIDE Threat Modeling with AI: A Step-by-Step Guide or use the AI-Generated Code Review Checklist.
Reusable prompt
Access-control review of an endpoint
Asks the assistant to list who may call one endpoint and what each refusal should be, then to look for missing checks, without writing code or choosing policy.
You are reviewing access control. Do not write code and do not decide business rules.
Fictional clinic: Tidewell Physiotherapy. Roles: patient, front_desk, physiotherapist, practice_manager. Stack: TypeScript, Next.js route handlers, PostgreSQL.
Endpoint: GET /api/staff/bookings/{bookingId}/changes (FR-05: who changed a booking, and when).
Intended callers: front desk and practice manager only.
Rules: the session says who the caller is and which role they have. Nothing about identity or role may be read from the request body, the address or the query string. A patient must never learn whether another patient's booking exists.
Problem codes: 401 sign-in-required, 403 not-allowed, 404 not-found, 400 invalid-request.
Tasks:
1. Make a table with one row per caller type (signed out, patient, physiotherapist, front desk, practice manager) and the status code each should get.
2. List the checks the handler needs, in the order they should run.
3. List ways this endpoint could leak information or be misused, such as a missing check, a check in the wrong order or a trusted value from the request.
4. Write the tests you would want, one line each.
5. List every decision you cannot make for me under "Decision needed", with the role who should decide.Show the reusable template
Replace each {{placeholder}} with your own details.
You are reviewing access control. Do not write code and do not decide business rules.
Context: {{organisation_roles_and_stack}}
Endpoint: {{method_and_path}} ({{requirement_id}}). Intended callers: {{intended_roles}}.
Rules: the session says who the caller is and which role they have. Nothing about identity or role may be read from the request body, the address or the query string. {{extra_rules}}
Problem codes: {{problem_codes}}.
Tasks:
1. Make a table with one row per caller type (signed out and each role) and the status code each should get.
2. List the checks the handler needs, in the order they should run.
3. List ways this endpoint could leak information or be misused, such as a missing check, a check in the wrong order or a trusted value from the request.
4. Write the tests you would want, one line each.
5. List every decision you cannot make for me under "Decision needed", with the role who should decide.Expected output and limitations
A table of caller types with the expected status, an ordered list of checks, a short list of risks, one-line tests and a list headed Decision needed. A good answer ties each row to your rules and does not add features.
1. Expected answers
Signed out -> 401 sign-in-required
Patient -> 403 not-allowed
Physiotherapist -> 403 not-allowed
Front desk -> 200 list of changes
Practice manager -> 200 list of changes
2. Checks, in order
session exists -> role has view_booking_history -> bookingId is valid -> booking exists
3. Risks
- The role must come from the session, not from a header the caller can set.
- A booking id that does not exist returns 404 for staff. That is fine, because staff may see all bookings.
5. Decision needed
Should a physiotherapist see the history of their own patients' bookings? Role: practice manager.Limitations to keep in mind
- The assistant reasons from your description, not from your code. It cannot tell whether the handler really runs the checks in that order.
- It may suggest extra roles or extra rules. Anything you did not state belongs under Decision needed.
- A neat table is not a test. Only a failing request that you run proves a check works.
Common errors and how to fix them
The menu hides a staff page, and the team assumes it is protected.
Why it happens: Hiding a link was mistaken for access control.
Fix: Make the server refuse the request with 403, and test it by sending the request without using the page.
The role or patient id is read from the request body.
Why it happens: It was the quickest way to get the value into the handler.
Fix: Read both from the session. Ignore any such field in the request.
Someone else's booking returns 403, so a patient can tell which booking numbers exist.
Why it happens: Ownership was checked after the lookup, with a separate error.
Fix: Put the owner in the lookup, so "not yours" and "not there" both return the same 404.
Validation checklist
Tick each item once you have confirmed it.
Hands-on exercise
Access rules for a Ferngate endpoint
Ferngate Cycle Repairs lets mechanics record a part taken for a job, and lets the owner correct a stock count. Choose the answer for six requests, write the order of checks for each endpoint and list the tests.
You will need
- Endpoint A: POST /api/jobs/{jobId}/parts-used. Intended caller: any mechanic.
- Endpoint B: POST /api/parts/{partId}/stock-count. Intended caller: the owner only.
- Six requests: A signed out; A by a mechanic; B by a mechanic; B by the owner; B signed out; A for a job that does not exist.
- Note: mechanics share one tablet, so each mechanic signs in with their own account. The owner has not decided what happens when two mechanics are signed in at once.
Acceptance criteria
Your work is done when every one of these is true.
Hints (2)
- Ask whether the thing being refused is a feature or a person's data. That is the difference between 403 and 404.
- A job that does not exist and a job that exists but is not allowed should look alike to the caller when the data is private.
Show a model answer
A strong answer gives 401 for both signed-out requests, 200 for a mechanic on A and for the owner on B, and 403 for a mechanic on B, because the stock count is a feature and not a person's data. A job that does not exist gives 404 on A. The order for each endpoint is session, permission, input, then the lookup. The mechanic who recorded the part is taken from the session, so the tablet's user cannot claim to be someone else. The shared tablet raises a real question for the owner: how long should a session last when the screen is left on the workbench? That belongs under 'Decision needed', and the next lesson shows how session length is set.
Knowledge check
Choose an answer, then check it. Nothing is recorded — this is for you.
Show the answer and explanation
Answer: B. The person is known, so authentication passed, and the role lacks the permission, so 403 is right. 401 is tempting because it sounds like 'not authorised', but it means the server does not know who is asking. 404 is for records that are not yours, and here no one's data is at stake.
Show the answer and explanation
Answer: B. The same 404 for 'not yours' and 'not there' tells the patient nothing about which numbers are in use. A 403 is tempting because it feels precise, but it confirms the booking exists. A 200 with fields removed still confirms it.
Show the answer and explanation
Answer: B. Only the server can refuse a request that skips the pages. Hiding a link helps tidy the screen, but it is not security. Hard-to-guess addresses are tempting, yet they leak through logs, browser history and shared links.
Frequently asked questions
What is the difference between authentication and authorisation?
Authentication proves who someone is, for example with a one-time sign-in link or a password. Authorisation decides what that person may do after that. You need both, and you always check them in that order.
Should a user who is not logged in get 401 or 403?
Use 401. The server does not know who is asking, and the fix is to sign in. Use 403 when the server knows who is asking and the answer is still no.
Why return 404 instead of 403 for someone else's data?
A 403 confirms that the record exists. A 404 gives the same answer as for a record that was never made, so an attacker cannot learn which ids are real. Use 403 for features, such as a staff-only screen, and 404 for another person's records.
Is it enough to hide buttons the user may not use?
No. Hiding buttons only makes the screen tidier. Anyone can send a request without using your pages, so the server must check the session and the permission on every request.
- Written by
- PromptFable Editorial
- Last updated 19 Nov 2026
- Review
- Reviewed by Waseem Nadir, Technical Reviewer
- Last reviewed 27 Nov 2026
References
Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.
- Authorization Cheat Sheet(opens in a new tab)
OWASP · Official documentation · Practical rules for access control, including deny by default and checking on every request.
- Authentication Cheat Sheet(opens in a new tab)
OWASP · Official documentation · What good sign-in looks like, and the mistakes to avoid.
- HTTP response status codes(opens in a new tab)
MDN Web Docs · Official documentation · The meaning of 401, 403 and 404 in the standard.
- OWASP Top 10(opens in a new tab)
OWASP · Official documentation · A widely used list of the most common web security risks. Broken access control is a long-standing entry.
PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.