IDOR, Authentication, JWT, OAuth, and API Access Control
Break object-level and function-level authorisation in a lab, then audit sessions, JWT validation, OAuth flows, MFA, and API rate limits like an application security engineer.
By the end, you’ll be able to…
- Distinguish BOLA, BFLA, tenant isolation failures, forced browsing, and mass assignment with concrete tests.
- Audit session lifecycle, cookie flags, fixation, logout invalidation, and MFA and recovery flows.
- Explain JWT structure and the failure modes behind alg none, key confusion, weak secrets, and header injection.
- Test OAuth authorisation code flows, state, PKCE, and redirect URI handling, and design API authorisation and rate limits.
01Authorization Is a Server-Side Decision
Authentication answers who the caller is. Authorisation answers what that caller may do to a specific object. Broken object-level authorisation, often called IDOR, occurs when the server accepts an object identifier and returns or modifies the object without checking that the caller owns it. The identifier can be a number, a UUID, a slug, a filename, or an opaque token. Changing a UUID is harder to guess but is not a control: identifiers leak through APIs, exports, emails, and shared links. The check must be an explicit query scoped to the authenticated subject or tenant.
Broken function-level authorisation is the vertical equivalent: a normal user reaches an administrative function. The UI may hide the button, but the route still exists. Forced browsing, method changes, and versioned APIs are common ways to find it. Test every role against every endpoint, including DELETE and PATCH, and include endpoints discovered in JavaScript bundles, mobile traffic, and API documentation. A 200 with admin data, or a successful state change, is the finding; a hidden button is not a control.
Tenant isolation deserves its own test because it fails differently from user-to-user access. A request may carry a tenant ID in a header, a subdomain, a JWT claim, or a query parameter. If the server trusts a client-supplied tenant value without checking membership, a user in one organisation can read another organisation's records. Test by swapping the tenant value while keeping the user's own token, and by using a token from a user in a different tenant. Return 404 rather than 403 when confirming existence would leak information, and log the denied attempt.
OBJECTS AND ROLES TO TESTAccounts: A customer, tenant one B customer, tenant one C customer, tenant two D support agent E administratorRequests to repeat for every object: GET /api/invoices/1042 PATCH /api/invoices/1042 {"total": 1} DELETE /api/invoices/1042 GET /api/invoices/1042/export POST /api/invoices/1042/payExpected results: Owner (A): 200 for read, allowed state changes Peer (B): 403 or 404, no data, denial logged Other tenant (C): 403 or 404, no data Support (D): read only if the support role explicitly allows it Admin (E): allowed, with an audit entry Anonymous: 401Also test: - the object id in the body, not only the path - the tenant header or claim swapped to tenant two - a trailing slash, a different API version, and a different method - GraphQL node ids and nested objects02Sessions, Fixation, and Logout
A session cookie is a bearer credential: whoever holds it can usually act as the user. Set Secure so it travels only over HTTPS, HttpOnly so script cannot read it, and an appropriate SameSite value so cross-site requests do not carry it by default. Use the __Host- prefix where possible to bind the cookie to one host and path. Choose a strong random identifier, store server-side state, and set both an idle timeout and an absolute lifetime. A session that lives for a month on a shared laptop is an incident waiting to happen.
Session fixation occurs when an attacker can make a victim use a known session identifier and then reuse it after login. The defence is to issue a fresh identifier at authentication and at every privilege change, and to reject identifiers supplied in URLs. Logout must invalidate the session server-side, not just delete the cookie in the browser. Password changes, email changes, and MFA resets should revoke other sessions, and users should be able to see and terminate active sessions.
Remember-me tokens need the same care. Store a hash of the token server-side, scope it to one device, rotate it on use, and revoke it on logout. A long-lived token in a cookie without rotation is a permanent credential if stolen. Concurrent session limits and anomaly alerts, such as a login from a new country immediately after a password reset, turn session management into detection as well as prevention.
HTTP/1.1 200 OKSet-Cookie: __Host-session=8f3c...; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=1800# Properties that matter:# __Host- binds the cookie to this exact host, requires Secure and Path=/# Secure never send over plaintext HTTP# HttpOnly JavaScript cannot read it, reducing XSS impact# SameSite Lax or Strict limits cross-site attachment# Max-Age short idle lifetime; rotate on privilege change# On login, issue a new identifier:# session.regenerate() then store the authenticated subject.# On logout, delete the server-side record, not only the browser cookie.03MFA, Recovery, and the Human Bypass
Multi-factor authentication raises the cost of credential stuffing, but only if the second factor is enforced by the server and cannot be skipped. Common bypasses include changing a response field such as mfa_required from true to false, replaying a valid OTP, using a backup code that never expires, and brute-forcing a six-digit code because there is no attempt limit. Test the flow step by step: does the server issue a full session before the second factor, or a limited session that cannot access protected routes? Does the second step trust a user-controlled account identifier?
Account recovery is often weaker than login. Security questions have guessable answers, reset links may not expire, tokens may be reusable, and support agents may reset access after a convincing phone call. Host header poisoning can turn a reset link into a link to an attacker domain if the application builds the URL from the request Host header. Email enumeration through different reset responses helps an attacker choose targets. Keep reset responses uniform, use single-use tokens with short lifetimes, bind them to the account, and notify the user of security-relevant changes.
Rate limits and lockouts belong here because they decide whether guessing is practical. Limit by account, by source address, and by device or token, with progressive delays and alerting. Avoid hard lockouts that let an attacker deny service to a known user; prefer throttling and risk-based challenges. Protect OTP verification, password reset, login, and any endpoint that returns partial account information. Log failures with enough context to investigate without storing the secret itself.
04JWT: Structure and Failure Modes
A JSON Web Token has three base64url parts separated by dots: a header describing the algorithm and key, a payload of claims, and a signature over the first two parts. The payload is encoded, not encrypted, so anyone can read it. Standard claims include sub for the subject, aud for the intended audience, iss for the issuer, exp and nbf for validity, iat for issue time, and jti for a unique identifier. The server must verify the signature with the correct key and algorithm, then validate every claim it relies on.
The alg none attack works when a library or custom verifier accepts a token whose header says none and skips signature verification. Key confusion works when the server expects RS256 but accepts HS256, then uses the public key as the HMAC secret; the attacker can sign a forged token with a value that is public. Weak HMAC secrets can be cracked offline from a single captured token. Header parameters such as kid, jku, x5u, and an embedded jwk are additional attack surfaces if the server trusts them without validation: kid can point at a path or inject into a key lookup, and jku or x5u can direct the server to an attacker-controlled key set.
Defend by allowlisting the expected algorithm rather than reading it from the token, verifying with a maintained library, checking aud, iss, exp, and nbf, and rejecting tokens that fail any check. Keep access tokens short-lived, rotate signing keys with a published key set, and maintain server-side revocation for logout and compromise. Never put secrets or sensitive personal data in the payload. Treat every claim that grants authority, such as role or tenant, as something the server must validate against current state, not something the token can assert forever.
05OAuth 2.0 and OpenID Connect
OAuth 2.0 delegates access. The client sends the user to an authorisation server, the user authenticates and consents, and the server returns an authorisation code to the client's registered redirect URI. The client exchanges the code for tokens. OpenID Connect adds an identity layer with an ID token. For web and mobile clients, use the authorisation code flow with PKCE: the client creates a random verifier, sends its SHA-256 hash with the request, and proves possession of the verifier when exchanging the code. This prevents an intercepted code from being redeemed by another party.
The state parameter protects the callback against CSRF: generate a random value, store it in the user's session, and require an exact match on return. Without state, an attacker can trick a victim into completing a login flow with the attacker's code, linking the victim's session to the attacker's account. Validate redirect_uri by exact match against a registered value, not by prefix or wildcard. A permissive redirect URI combined with an open redirect on the client can leak authorisation codes or tokens.
Scope should be minimal and explained to the user. The implicit flow returns tokens in the URL fragment, where they can leak through browser history and referrers, so avoid it. Validate the issuer to prevent mix-up attacks where a client is tricked into sending a code to the wrong token endpoint. Consent phishing, where a malicious application requests broad scopes and the user approves it, is an identity attack that technical controls alone cannot solve: maintain an application allowlist, require administrative consent for sensitive scopes, and monitor granted permissions.
GET /authorize?response_type=code &client_id=shop-web &redirect_uri=https%3A%2F%2Fshop.lab.test%2Fcallback &scope=openid%20profile%20orders%3Aread &state=7f3c9a2e5b &code_challenge=Q2hhbGxlbmdl... &code_challenge_method=S256 HTTP/1.1Host: idp.lab.test# Server checks:# 1. client_id is registered and redirect_uri matches exactly.# 2. response_type is code, not token.# 3. scope is allowed for this client and shown to the user.# 4. state is returned unchanged and compared to the session value.# 5. code_challenge_method is S256 and the verifier is checked at exchange.# 6. The code is single-use, short-lived, and bound to the client.06API Authorisation, Mass Assignment, and Rate Limits
APIs fail authorisation in predictable places. Object-level checks are missing on nested routes such as /users/42/orders/99. Function-level checks are missing on admin or internal endpoints that the gateway routes but the service does not protect. Property-level checks are missing when a response returns every database column or a request can set fields the user should not control. Mass assignment happens when a framework binds a JSON body directly to a model, so adding role, tenant_id, or is_admin to a profile update changes authority. Use explicit request and response schemas, allowlist writable fields, and strip sensitive fields before serialisation.
Rate limits protect availability, credentials, and money. Key them by the right identity: source address alone is weak behind NAT and easy to rotate; API key alone misses per-user abuse; a combination of account, token, route, and address is stronger. Apply tighter limits to login, OTP, password reset, search, export, and payment endpoints. Return 429 with a Retry-After header, log the decision, and alert on sustained abuse. Test bypasses: X-Forwarded-For spoofing, header case changes, trailing slashes, API version prefixes, alternate content types, and multiple keys belonging to the same tenant.
Pagination and filtering are part of the same surface. A limit parameter that accepts 100000 can turn a list endpoint into a bulk export. Negative offsets, cursor tampering, and filters that expose other tenants are common. Enforce a maximum page size server-side, use opaque cursors, and apply the same authorisation predicate to the count query as to the rows. For GraphQL, disable or restrict introspection in production, cap query depth and complexity, limit aliases and batching, and enforce field-level authorisation in resolvers rather than trusting the client to ask only for permitted fields.
### Object-level: another user's invoiceGET /api/v1/invoices/1042 HTTP/1.1Host: api.lab.testAuthorization: Bearer <user-B-token>### Function-level: admin route with a customer tokenGET /api/v1/admin/users HTTP/1.1Host: api.lab.testAuthorization: Bearer <user-A-token>### Property-level: try to grant a rolePATCH /api/v1/users/me HTTP/1.1Host: api.lab.testAuthorization: Bearer <user-A-token>Content-Type: application/json{"displayName":"Student","role":"admin","tenant_id":"tenant-two"}### Resource consumption: ask for everythingGET /api/v1/orders?limit=100000&offset=-1 HTTP/1.1Host: api.lab.testAuthorization: Bearer <user-A-token>### Expected: 403 or 404 for other objects, admin route denied,### role and tenant ignored or rejected, page size capped, 429 on abuse.07A Repeatable Authorisation Test Method
Start with an inventory. List every route from the UI, JavaScript bundles, OpenAPI or GraphQL schemas, mobile traffic, and error messages. For each route, record the method, the object it touches, the roles that should reach it, and the fields it accepts. Then build the role matrix and run it with real sessions for each role. Automate the repetitive part with a script that replays requests under each token and compares status codes and response shapes, but inspect the interesting differences by hand.
Test negative cases first: the requests that should fail. A peer reading another peer's object, a customer calling an admin route, a tenant-two user sending a tenant-one header, an anonymous request to a protected route, and a state change with a read-only role. Then test positive controls with the owner's token to prove the endpoint works. Record request, expected status, observed status, response body shape, and whether a denial was logged. A finding needs an impact statement: what data or action did the bypass expose?
Finally, verify the fix from the outside. Re-run the exact request and confirm the response no longer contains the data. Add an automated regression test with seeded users in two tenants. Check that the fix is applied in every service that owns the object, not only at the gateway, because internal callers may bypass the edge. Review logs to confirm denials are visible and alerting fires on repeated attempts.
The ideas worth keeping.
- Authorisation must be enforced per object, per function, and per field on the server; hidden UI and UUIDs are not controls.
- Sessions are bearer credentials: rotate on login, set Secure, HttpOnly, and SameSite, and invalidate server-side on logout.
- JWT verification needs a fixed algorithm, validated claims, trusted keys, short lifetimes, and revocation.
- OAuth code flow with PKCE, exact redirect URIs, and state checks prevents the most common token and callback attacks.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Exercise 1: Prove a tenant isolation failure
A SaaS app sends X-Tenant-ID on every request and authorises users by checking that the header matches a tenant they belong to. User A belongs only to tenant one. Design a test that determines whether the server actually enforces membership, and describe the expected secure behaviour.
Explore a worked solution
Log in as A and capture a working request to /api/projects with X-Tenant-ID: tenant-one. Repeat the same request with X-Tenant-ID: tenant-two and A's unchanged token. Expected secure result: 403 or 404, no project data, and a logged denial. Then try a token from a user who belongs to tenant two and confirm that tenant-two data is returned only for that user. Also test whether the tenant is taken from the token instead of the header, whether a missing header falls back to a default tenant, and whether nested routes such as /api/projects/99 ignore the header. A 200 containing tenant-two projects proves the server trusts the client-supplied tenant.Tenant membership must be derived from the authenticated identity and checked against the object, not trusted from a header the client can edit.
Exercise 2: Audit a JWT implementation
An API accepts JWTs, reads alg from the header, uses a single HMAC secret, and trusts a role claim for admin access. The token payload is readable by anyone. List the concrete tests you would run in a lab and the changes you would require.
Explore a worked solution
Tests: submit a token with alg none and an empty signature; try HS256 with a guessed weak secret offline; change the role claim and re-sign if the secret is recovered; check whether aud, iss, and exp are validated by using a token from another service and an expired token; try a kid value that points to a known file or injects into a key lookup; check whether the server fetches jku or x5u URLs. Required changes: allowlist the algorithm server-side, use a strong random secret or asymmetric keys, verify aud, iss, exp, and nbf, load keys from a trusted store and validate kid against it, ignore jku and x5u unless explicitly supported with an allowlist, keep tokens short-lived with revocation, and look up the role from the database rather than trusting a long-lived claim.A readable payload is normal for JWT. The vulnerability is trusting header or claim values that the server has not verified and authorised.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Keep exploring.
The official references behind this lesson, when you want a second angle or the full details.
One lesson closer.
Reading is a start. Trying it yourself makes the connection.