Authentication and Authorization Basics
Distinguish identity from permission, inspect sessions and ownership checks, and apply least privilege to real code review decisions.
Authentication establishes who is acting. Authorization decides whether that actor may perform this action on this resource now. A valid session answers only the first question.
Follow identity through the server, review object ownership and tenant boundaries, and test both the allowed and the denied case.
What you should be able to do
- Separate identity, action permission, and object scope.
- Inspect server-side sessions and the principal they establish.
- Review ownership, batch access, and least privilege.
- Write a two-principal denial test for a missing check.
Three separate security decisions in one request
Imagine a customer opens an invoice PDF. The browser sends a session cookie to an API. Middleware validates the cookie and resolves a user ID. The handler reads an invoice ID from the URL. The service fetches an invoice and returns its bytes. There are at least three different decisions:
| Decision | Example question | Evidence to find |
|---|---|---|
| Authentication | Is this session valid and bound to a real user? | Server-verified session, expiration, revocation, identity |
| Authorization | May this user read this invoice? | Tenant or owner predicate, policy check, denied cross-user test |
| Data handling | May the response include these fields and file bytes? | Safe projection, file access policy, response behavior |
A route can authenticate correctly and still leak another customer's invoice. It can authorize the invoice record and still leak an unrelated attachment if the attachment lookup lacks the same scope. It can hide a button in the UI and still accept a direct API request. Review each decision at the operation it protects.
The terms are sometimes compressed into "auth." That shorthand is dangerous in review comments. Write "authentication" when discussing identity, "authorization" when discussing permission, and "session management" when discussing how identity survives multiple requests. The distinction makes findings and fixes precise.
A request trace
Read this simplified TypeScript route without deciding yet whether it is safe:
export async function GET(request: Request, context: { params: { invoiceId: string } }) {
const session = await requireSession(request);
const invoice = await db.invoice.findUnique({
where: { id: context.params.invoiceId },
});
if (!invoice) return new Response('Not found', { status: 404 });
return new Response(await renderPdf(invoice));
}
requireSession may prove that the caller has a valid account. It does not, from its name alone, prove the account can read the selected invoice. The query proves only that an invoice with that ID exists. The sensitive operation is returning its PDF. The missing link is a rule binding the invoice to session.userId or to an authorized tenant or role. A review should inspect requireSession and any database-level policy before declaring a finding, but the route does not show the object decision.
A safer pattern makes the scope explicit in the data access:
const invoice = await db.invoice.findFirst({
where: {
id: context.params.invoiceId,
tenantId: session.tenantId,
},
});
if (!invoice) return new Response('Not found', { status: 404 });
return new Response(await renderPdf(invoice));
This assumes session.tenantId came from validated server state and the invoice's tenantId is reliable. If multiple users in a tenant have different permissions, a tenant match alone is insufficient. If invoices can be shared across tenants, the policy may need an explicit access grant. The point is to express the authorization rule in a place that controls the read, not to copy a generic predicate without understanding the product.
Select each gate. Passing the identity gate does not answer the remaining policy questions.
Session. Verify the session and obtain the server-owned principal. Do not build the principal from an unsigned cookie or a userId request field.
const principal = await requireSession(req);
Action. Permission is specific to the operation. A user may read a document without being allowed to delete it or change its owner.
const action = "document:read";
Object. The requested ID selects an object. Apply the ownership and tenant policy to that object, not merely to a parent route or a UI menu.
where: { id, ownerId: principal.userId, tenantId: principal.tenantId }
Decision. A missing authorized row must stop the protected operation. Check the failure path as carefully as the successful path.
if (!document) throw notFound();
return document.body;
Review question: Can you point to the decision that authorizes this subject, action, and object together?
How a server establishes identity
An identity value in a request body, URL, hidden form field, or browser storage is user-controlled. The server may accept a target user ID as data for an operation, but it must not treat that ID as proof of the caller's identity. A trusted identity normally comes from a server-validated session, a verified token with the right issuer and audience, or another authenticated channel whose contract is understood.
Consider an account profile update:
export async function updateProfile(request: Request) {
const body = await request.json();
await db.user.update({
where: { id: body.userId },
data: { displayName: body.displayName },
});
return new Response(null, { status: 204 });
}
The client can choose body.userId. Even if the UI always sends the current user's ID, a direct caller can change it. The route needs a server-derived identity and a policy for which profile may be edited:
export async function updateProfile(request: Request) {
const session = await requireSession(request);
const body = await request.json();
const displayName = parseDisplayName(body.displayName);
await db.user.update({
where: { id: session.userId },
data: { displayName },
});
return new Response(null, { status: 204 });
}
This version uses the caller's trusted identity as the object ID. It still needs appropriate validation for displayName and any downstream HTML rendering. When a feature intentionally lets one user edit another person's profile, the route should accept a target ID and check a specific administrative or delegated permission. Removing the target ID from every API is not a universal design rule; making the authorization decision explicit is.
Middleware is a starting point, not the whole answer
Authentication middleware can reject requests without a valid session and attach an identity to a request context. Authorization middleware can enforce coarse rules such as "this route requires an admin role." But many decisions depend on the specific object loaded later: whether the current user owns this document, belongs to this team, is the assigned reviewer, or may perform this transition on a closed ticket. A generic route guard cannot decide that without the object.
When code says requireAdmin(), inspect its implementation. Does it use a current server-side role, a stale claim from a long-lived token, or a request header? Is it applied to every HTTP method and route variant? If a background job calls the same service without middleware, does the service assume all callers are trusted? The reviewer needs to know whether the control follows the operation, not only whether one route imports a promising helper.
OWASP's Authorization Cheat Sheet recommends deny by default and permission checks on every request. In code, that means an unmatched policy branch rejects the action; it does not silently permit it. It also means the service or policy layer should have a testable contract rather than depending on a particular UI.
Sessions: identity across requests
HTTP requests are independent. A session mechanism lets the server associate later requests with an authenticated user. In a common cookie-based design, the browser sends a session identifier; the server looks up or validates that identifier and recovers identity and session state. The identifier is a bearer credential. Anyone who can use a valid identifier may be treated as the user until it expires or is revoked.
A reviewer does not need to reimplement a session framework to inspect it responsibly. Ask:
- Is the session ID generated with sufficient unpredictability by a trusted library?
- Is the cookie sent only over HTTPS using Secure, inaccessible to ordinary JavaScript using HttpOnly where appropriate, and scoped with a deliberate SameSite choice?
- Does the server regenerate or rotate the session ID after login or another privilege change?
- Can the server revoke a session on logout, password reset, or account disablement?
- Are idle and absolute expiration applied, and are sensitive operations rechecked against current permissions?
- Is the identity in the session derived from validated server state, not a client-editable field?
OWASP's Session Management Cheat Sheet discusses these controls and why session IDs should not appear in URLs. The exact framework configuration varies, so a review should inspect actual cookie settings and token verification rather than copying a checklist into a finding.
What cookie flags do and do not prove
HttpOnly reduces the chance that injected JavaScript reads the cookie value directly. It does not prevent the browser from sending the cookie with requests initiated by an XSS payload. Secure restricts cookie transmission to HTTPS; it does not authorize a particular invoice. SameSite can reduce some cross-site request scenarios, but should be treated as defense in depth, not a substitute for a server-side authorization rule or all CSRF defenses. These are important controls with different jobs.
Session fixation occurs when an attacker can cause a victim to use a session identifier known to the attacker before authentication and the server keeps that identifier after login. Rotating the identifier at login breaks that continuity. Session hijacking involves stealing or otherwise using a valid session. Neither problem is solved by adding an ownerId check in one route; they belong to the identity boundary.
The document ID is a long, random UUID. What does that establish about authorization?
Authorization as subject, action, object, and context
A good policy statement names four parts:
Subject: the signed-in customer. Action: export. Object: invoice 1482. Context: the customer's current tenant, the invoice's state, and any delegated access grant.
This is more precise than "admins can access invoices." It helps reviewers discover edge cases. A user might read an invoice but not refund it. A finance administrator may export invoices for one tenant but not another. A support agent may temporarily view redacted metadata but not the full PDF. A closed invoice may forbid editing even by its owner.
Authorization may be expressed through role-based access control, attributes, relationships, or a combination. A role such as "team admin" can answer a broad question. An ownership predicate answers whether a particular user created or owns an object. A relationship such as "assigned to this ticket" can grant a narrow action. A policy engine may centralize these rules. The reviewer's job is not to prefer a fashionable model; it is to find the rule the product intends and confirm every relevant code path enforces it.
The policy belongs at the sensitive operation
Here is a common failure. The route loads a team and verifies membership. It then calls a service that accepts a team ID and creates an invitation:
export async function inviteMember(request: Request, teamId: string) {
const session = await requireSession(request);
const team = await db.team.findUnique({ where: { id: teamId } });
if (!team || !team.memberIds.includes(session.userId)) {
return new Response('Not found', { status: 404 });
}
const body = await request.json();
await invitationService.create(teamId, body.email);
return new Response(null, { status: 204 });
}
Membership is not necessarily permission to invite others. If the rule is "only owners and admins may invite," the route enforces the wrong predicate. The service may also be called from another route that does no check. A stronger service contract makes the actor and action explicit:
async function createInvitation(actorId: string, teamId: string, email: string) {
const membership = await db.membership.findUnique({
where: { teamId_userId: { teamId, userId: actorId } },
});
if (!membership || !['owner', 'admin'].includes(membership.role)) {
throw new ForbiddenError();
}
return db.invitation.create({
data: { teamId, email: parseEmail(email), createdBy: actorId },
});
}
The service checks the action against current membership before creating the invitation. A real implementation should consider race conditions, transactions, invitation limits, tenant scoping, and whether owners can invite another owner. Those are product rules, not details that a generic "is admin" check can guess.
Deny by default
Policy logic should reject requests when required information is missing, invalid, stale, or unmatched. Consider a switch:
function mayChangeTicket(role: string, action: string): boolean {
if (action === 'read') return role === 'agent' || role === 'manager';
if (action === 'close') return role === 'manager';
return true;
}
The final true makes every newly introduced action permitted by default. A future "delete" operation could accidentally inherit authorization. The safer default is false, with explicit permitted cases and tests for unknown actions. If a remote policy service is unavailable, decide which operations must fail closed and how to communicate the outage; do not turn an undefined decision into a permit simply to keep the request flowing.
Express the ownership policy in the lookup
The policy allows only an owner in the same tenant to read a document. Which predicates make that policy visible?
const principal = await requireSession(req);
const document = await db.document.findUnique({
where: { id: req.params.id },
});
return document.body;
Reveal the safer implementation
const principal = await requireSession(req);
const document = await db.document.findFirst({
where: {
id: req.params.id,
ownerId: principal.userId,
tenantId: principal.tenantId,
},
});
if (!document) throw notFound();
return document.body;
The verified user and tenant scope the selected row before its body is returned. This implements the stated owner-only policy. A product that supports sharing or administrator access needs an explicit policy for those cases rather than silently removing the scope.
Ownership and tenant boundaries
Object ownership checks are easy to omit because the requested ID often looks unguessable. An opaque identifier is useful for routing and can make accidental discovery harder, but it is not an authorization mechanism. IDs leak through logs, links, support tickets, analytics, browser history, and other API responses. A security rule should hold even if an attacker knows the exact ID.
For multi-tenant systems, a tenant predicate is often the first boundary:
const record = await db.document.findFirst({
where: {
id: documentId,
tenantId: session.tenantId,
},
});
But this alone may be too broad. A tenant member may be allowed to see one project but not another. A document may be shared with a partner tenant under a specific grant. The reviewer should identify the actual hierarchy: organization → team → project → document, then follow how each lookup preserves it.
Parent-child lookups
Suppose a route is /api/projects/:projectId/files/:fileId. It checks that the user can access projectId, then loads a file by fileId alone. An attacker can supply a permitted projectId and another project's fileId. The presence of a checked parent in the URL does not make the child belong to that parent. The file query or policy must verify file.projectId equals the authorized project, or directly query the file through the permitted project relationship.
const file = await db.file.findFirst({
where: {
id: fileId,
projectId,
project: { tenantId: session.tenantId },
},
});
if (!file) return notFound();
This pattern avoids a common insecure direct object reference. It still requires action-specific checks: reading a file and deleting it may have different permissions.
Lists and batch operations
Reviewers sometimes check a single-object endpoint and overlook list or batch operations. A list query without tenant scope can leak many objects at once. A batch update that verifies only the first ID can modify objects outside the actor's scope. Pagination and filtering can complicate the evidence: a post-query filter may disclose total counts, timing, or metadata and may be bypassed in another code path.
For a list, put the scope in the query or use a reviewed policy-aware data access layer:
const invoices = await db.invoice.findMany({
where: {
tenantId: session.tenantId,
status: requestedStatus,
},
take: 50,
});
Validate requestedStatus independently and consider whether the actor may view every invoice in the tenant. For a batch, verify every target before any side effect, ideally within a transaction or through a scoped update predicate. A policy that allows 9 of 10 requested objects should define whether the operation rejects all, processes the permitted subset, or returns per-item results. Do not accidentally act on the tenth.
Least privilege in application code
Least privilege means an actor or component receives only the permissions needed for its legitimate task, for only as long as needed. It applies to users, service accounts, API keys, database roles, storage credentials, and background jobs.
A "viewer" role should not have mutation permission simply because the UI hides editing controls. A PDF renderer should not need credentials that can delete invoices. A dependency scanner should not run with production write access if it only reads source and package manifests. Narrow permissions reduce both the chance of a boundary mistake and the damage if one occurs.
In a code review, look for authorization decisions that are too broad:
- A user with "admin" status in one organization can affect all organizations because the query omits organization ID.
- A service uses a root database credential when a read-only query would suffice.
- A token with a broad wildcard scope is passed to a helper that only needs to read one object.
- A worker accepts a job message containing an arbitrary user ID and treats it as delegated authority without verifying who enqueued the job.
- A role check permits every action while the product intended only one maintenance operation.
The fix often has two parts: enforce the application policy and reduce the component's capabilities. A narrow service credential does not excuse a missing user authorization check; it is a second boundary.
What a useful authorization finding looks like
A review finding should make the rule and missing decision testable:
The invoice export route authenticates the caller but loads the invoice by request-supplied ID alone. A user who knows another tenant's invoice ID can reach renderPdf without a tenant or ownership check. The server should look up the invoice under the caller's authorized tenant or evaluate a documented sharing policy before rendering. Add a test in which user A requests user B's invoice and receives no PDF.
This is stronger than "IDOR" alone because it names actor, input, object, sink, impact, and fix. It also avoids assuming that a 404 versus 403 status is the core security property. Either response can be acceptable under a product policy if the sensitive data and side effect are withheld consistently. A reviewer should not require a particular status without understanding information-disclosure tradeoffs.
Negative tests matter
A test that proves an owner can read their invoice does not prove a non-owner cannot. Design a small authorization matrix:
| Actor | Target | Action | Expected |
|---|---|---|---|
| Owner in tenant A | Own invoice | Read | Allowed |
| Other member in tenant A | Same invoice | Read | Depends on policy |
| User in tenant B | Tenant A invoice | Read | Denied |
| Tenant A viewer | Tenant A invoice | Refund | Denied |
| Tenant A finance admin | Tenant A invoice | Refund | Allowed only in valid state |
| Anonymous caller | Any invoice | Read | Denied |
Add a test for a missing target, a disabled account, a revoked membership, and a role change during an active session if those cases matter to the product. Tests should assert no sensitive response and no side effect, not only an HTTP status. For a denied invitation, assert no invitation row and no email job. For a denied refund, assert the balance and audit log remain unchanged.
Beware of mock-only proof
A unit test can mock requirePermission() to return true and still fail to prove the route calls it correctly. A route test can pass because the fixture uses only one tenant. A meaningful test constructs two users and two objects with separate scopes, then exercises the same API path a real caller uses. Static review and tests complement each other: the code identifies the intended decision point, and the test proves denial across a boundary.
An export endpoint accepts an array of document IDs. What must its access check cover?
Practice: review a delegated export flow
The following example is original to this lecture. Assume requireSession validates the cookie and returns a server-side user ID and current tenant ID. The product policy allows only a manager of the relevant tenant to create or download an export containing payroll data.
// routes.ts
export async function GET(request: Request, exportId: string) {
const session = await requireSession(request);
const exportRecord = await exportService.get(exportId);
if (!exportRecord) return notFound();
return streamFromStorage(exportRecord.storageKey);
}
// export-service.ts
export async function get(exportId: string) {
return db.export.findUnique({ where: { id: exportId } });
}
// create-export.ts
export async function createPayrollExport(actor: Session, targetTenantId: string) {
if (!actor.roles.includes('manager')) throw new ForbiddenError();
return enqueueExport({ tenantId: targetTenantId, requestedBy: actor.userId });
}
Before reading the answer notes, write:
- Which decision does createPayrollExport make, and what does it not prove about the GET route?
- Which values can a GET caller choose?
- What policy should be checked before streamFromStorage?
- How could a test distinguish a correct policy from an endpoint that merely requires a session?
- Does the create route enforce the target tenant boundary shown?
Compare your reasoning
The create function checks a manager role, but it does not authorize download. The GET caller chooses exportId, and the service fetches a record by ID alone. Before streaming, the server needs to verify that the export belongs to the caller's permitted tenant and that the caller's role or explicit grant allows downloading this type of export.
A cross-tenant manager should be denied, as should a same-tenant viewer if the policy reserves payroll access for managers. The test should assert no bytes stream and no storage read on denial.
The create function also deserves scrutiny: targetTenantId comes from a parameter and the shown code checks only that the actor is a manager somewhere. It does not prove the manager has authority for that target tenant. The review therefore identifies two independent missing object boundaries, one on creation and one on download. A service-level policy that binds actor, tenant, export type, and action can protect both callers without relying on UI conventions.
Apply the method to a real code case
Open the authorization code review challenge. Find the missing authorization check yourself. Do not guess from the challenge description. Trace the request, identify how the server obtains identity, name the privileged action or object, and locate the point where the authorization decision should happen. Write a proposed denial test and a fix that enforces the intended rule on the server.
Use this template:
A caller with [identity and current role] can choose [target or action]. The code checks [existing control] but does not verify [required permission] before [sensitive operation]. The impact is [specific unauthorized read or change]. Enforce [policy decision] at [server-side point] and add a test with [denied actor and target].
The challenge is the assessment. This lecture deliberately does not disclose its answer or vulnerable line.
Authorization over time: sessions, revocation, and queued work
An authorization decision is made at a moment in time. Product state can change before the next request or before a background worker runs. A reviewer should ask when the application reads role and membership data, how long that result remains valid, and whether the operation is still permitted when the sensitive effect occurs.
Imagine that a manager starts a 30-minute payroll export. Five minutes later, an administrator removes the manager from the organization. Does the queued job still generate the file? Does the old manager's browser still have a download URL? The answer is a product policy decision, but the implementation must enforce that decision. A snapshot of a role copied into a job message is not necessarily current authority.
A signed storage URL may remain usable after an application session is revoked until the URL expires. Review the queue producer, worker, storage permissions, URL lifetime, and revocation path together.
Consider this queue message:
await queue.publish('payroll-export', {
tenantId: request.body.tenantId,
requestedBy: session.userId,
roleAtRequest: session.roles[0],
});
The worker must not treat roleAtRequest as a proof of present permission merely because the field was written by a server. The value may have been selected from stale session claims, the tenantId came from a request body, and the actor's membership can change. A safer design records a server-selected tenant and a durable request record, then defines whether execution uses a policy snapshot or a fresh check.
If the product requires immediate revocation, the worker should resolve the actor's current membership and permission before accessing payroll data. If the product intentionally allows already-approved jobs to complete, record who approved them, when, and what data scope was approved. That exception should be explicit and auditable.
State transitions also matter within a single request. A user may be allowed to edit a draft invoice but not a paid invoice. A check performed before a database transaction can race with another action that changes the invoice state. The database update should include the allowed state and tenant in its predicate, or the application should use a transaction and locking appropriate to its database:
const result = await db.invoice.updateMany({
where: {
id: invoiceId,
tenantId: session.tenantId,
status: 'draft',
},
data: { memo: requestedMemo },
});
if (result.count !== 1) return forbiddenOrConflict();
This pattern binds authorization-relevant object state to the write itself. It still needs input validation and a policy decision about who may edit drafts, but it avoids a separate read-check-write gap for those predicates. It also avoids updating an object from another tenant if invoiceId is known. A reviewer should ask whether the ORM emits one atomic update for updateMany and whether other side effects, such as email or audit events, occur only after success.
Cached permissions create another time boundary. A cache keyed only by user ID may return a role from tenant A while the request targets tenant B. A cache with a long lifetime may retain a removed membership. If the product uses cached grants, verify the cache key includes the policy context, the invalidation path works, and the acceptable revocation delay is documented.
The same reasoning applies to JWT claims: signature verification proves the token was issued by the server, not that its embedded roles remain current forever.
Worked review: project deletion across routes and services
Assume a collaboration service has organizations, projects, and members. A project owner may delete a project only while it is archived. Organization administrators can archive projects but cannot delete them unless they are the owner. The following code is an invented review target:
// deletion-route.ts
export async function DELETE(request: Request, projectId: string) {
const session = await requireSession(request);
const project = await projects.getById(projectId);
if (!project) return notFound();
if (!session.roles.includes('owner')) return forbidden();
await projects.remove(project.id);
return noContent();
}
// project-service.ts
export async function getById(id: string) {
return db.project.findUnique({ where: { id } });
}
export async function remove(id: string) {
await db.project.delete({ where: { id } });
await queue.publish('erase-project-files', { projectId: id });
}
Pause before the review notes. Identify the subject, action, object, and context. The subject is the authenticated user returned by requireSession. The action is deletion. The object is a project selected by projectId. Context includes organization, project ownership, archived state, and possibly a deletion approval window. The route checks a role label without showing whether that label applies to the target project or organization. It also never checks archived state.
The service deletes by ID and sends a cleanup job, so its effect is broader than an HTTP response.
The role check might be even weaker than it appears. If session.roles is a list of roles across all organizations, "owner" somewhere does not mean owner of this project. Even if roles are organization-scoped, this product's policy requires ownership of the project, not merely an organization-level owner role. The precise finding should say which relationship is missing, not claim that every role check is useless.
The code also leaves a time-of-check gap if archived state is checked in an earlier route but not bound to the delete. A project could be restored between the check and deletion.
One possible service design accepts the actor, evaluates a policy with the actual project record, and performs the final mutation with the key conditions in the database. A route can still authenticate and parse input, but the service should not accept a bare project ID as authority:
export async function deleteProject(actor: Session, projectId: string) {
const project = await db.project.findFirst({
where: { id: projectId, organizationId: actor.organizationId },
});
if (!project) throw new NotFoundError();
if (project.ownerUserId !== actor.userId) throw new ForbiddenError();
if (project.status !== 'archived') throw new ConflictError();
const removed = await db.project.deleteMany({
where: {
id: project.id,
organizationId: actor.organizationId,
ownerUserId: actor.userId,
status: 'archived',
},
});
if (removed.count !== 1) throw new ConflictError();
await queue.publish('erase-project-files', { projectId: project.id });
}
This sketch is still incomplete as a production deletion workflow. The database deletion and queue publication need a durable coordination method, such as an outbox, if a successful deletion must always erase files. The worker must verify its message originates from the trusted queue and cannot be forged through a public API. The purpose of the sketch is to show where the authorization predicates belong and how to avoid treating a route-level role label as a complete decision.
Construct a negative test matrix for this policy. Test a project owner with an archived project, the same owner with an active project, an organization administrator who is not the project owner, a project owner in another organization, a disabled user whose old session cookie is still present, and a request where the target is archived during the test but restored before the delete.
For each denied case, assert no project row deletion and no erase-project-files job. If the implementation returns 404 for cross-organization targets and 403 for same-organization denials, check that this matches the product's object-disclosure policy.
This example shows why reviewing only one line is rarely enough. The route identifies the actor and target; the service performs the mutation; the worker finishes the effect. Authorization must survive all three boundaries. The reviewer should follow the effect to completion and identify the smallest enforceable rule that protects it.
Which test most directly detects a missing ownership check?
Self-check: six authorization decisions
For each statement below, decide whether it establishes authentication, authorization, both, or neither. Then state the missing evidence. These are not trick questions; some statements are useful controls that answer only part of the policy.
- A request has a valid session cookie signed by the server.
- A route checks that the session has a "billing" role.
- A query loads an invoice by its ID and the session's tenant ID.
- A UI button is hidden from users without a manager role.
- An API token contains the scope "reports:read" and is accepted by a worker.
- A batch update checks the first record's tenant and then updates all supplied IDs.
Review notes: The valid cookie can establish a server-recognized identity if the session is not expired or revoked; it says nothing about the chosen object. The billing role is an authorization input, but its scope and the target action still matter. The tenant-scoped query enforces an object boundary if session.tenantId was established by the server and the tenant policy grants that user invoice access; it does not automatically authorize every billing action.
A hidden button is neither server authentication nor server authorization. The token scope may authorize a class of reads if its issuer, audience, expiry, revocation model, and target resource constraints are verified; acceptance alone is not proof of those details. Checking only the first batch record leaves the remaining IDs unconstrained, so it does not authorize the batch.
Turn one of these into a review comment. For example, "The batch endpoint verifies tenant ownership for ids[0] but updateMany receives all request-supplied IDs. A member of tenant A can include a tenant B ID later in the array, potentially modifying that record.
Scope the update predicate to tenant A for every target and add a mixed-tenant batch test that asserts no forbidden row changes." The comment names the decision, the gap, the effect, and a test. It avoids relying on the generic phrase "missing auth" as its entire explanation.
One last distinction: cross-site request forgery and missing authorization can coexist, but they are different checks. CSRF asks whether a browser was tricked into sending a state-changing request under an existing session. Authorization asks whether the identified actor may perform that action on the chosen object. A valid anti-CSRF token does not grant permission to delete someone else's project. An object-level permission check does not prove the user's browser intended to send the request.
When reviewing a mutation, trace both questions if the endpoint uses cookie-based authentication. A test that posts with a correct CSRF token and another tenant's ID is valuable because it isolates the object authorization rule; a test with a missing token checks a different boundary.
Likewise, a route can have a perfect ownership check and still let a suspended account keep acting if session revocation is absent. Review the sequence from account status to session lookup to policy evaluation. If a product promises immediate suspension, a long-lived role claim in a token may violate that promise. If the policy permits a bounded delay, document the interval and test it. Authorization quality comes from matching the enforced rule to the product's actual permission model, including when permissions change.
Key takeaways
- Authentication proves identity; authorization connects an actor, action, object, and context.
- A session cookie, role label, UI control, or opaque ID is not proof of permission for a particular object.
- Enforce permission on every relevant server path, as close as practical to the sensitive read or effect.
- Query scope, parent-child relationships, lists, batches, and background jobs all need the intended boundary.
- Deny by default and give users and services only the capabilities they need.
- Test forbidden cross-user, cross-tenant, cross-role, and invalid-state cases, including absence of side effects.
Glossary
Authentication: Establishing an actor's identity through a trusted mechanism.
Authorization: Deciding whether that actor may perform a specific action on a specific resource under current conditions.
Session: Server-recognized state that associates requests with an authenticated actor, often through a browser cookie.
Object ownership: A policy relationship between an actor and a particular object; it may be direct ownership or a documented access grant.
Tenant: A boundary between customer organizations or accounts sharing one application infrastructure.
Least privilege: Granting only the capabilities required for a legitimate task.
Deny by default: Rejecting an operation unless an explicit policy permits it.
Insecure direct object reference: A class of object authorization failure in which a caller can name and access an object they should not control.
Frequently asked questions
If a route requires login, is it authorized?
No. Login identifies the caller. The route must still decide whether that caller may access the requested object and perform the requested action.
Are random or unguessable IDs a substitute for ownership checks?
No. IDs can be disclosed through links, logs, notifications, or other responses. A secure rule should hold even if the caller knows the ID. Unpredictable IDs can reduce accidental discovery but do not grant or deny permission.
Should the route or service enforce authorization?
The boundary must be enforced on every path to the sensitive operation. A route can handle coarse authentication and input parsing; a service or policy layer is often a better place for object-specific authorization when multiple routes or jobs call the same operation. The exact placement depends on architecture, but the rule must be explicit and testable.
Is returning 404 better than 403?
Both can be appropriate. A 404 can avoid confirming an object's existence; a 403 can communicate an understood denial. The security requirement is that unauthorized callers receive no protected data and cause no protected side effect. Keep response behavior consistent with the product's disclosure policy.
Does SameSite prevent CSRF and authorization bugs?
SameSite is a useful cookie control but not a complete CSRF strategy and not an object authorization decision. A valid browser request can still target another user's object if the server omits the policy check.