Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 53 ยท Cryptography and Authentication

Authentication, Sessions and Access Control Flaws

Learn how broken authentication, session fixation, IDOR, privilege escalation and weak JWT checks happen, and how to design sessions and access checks that hold.

Authentication answers "who are you?" and access control answers "what may you do?". Most serious web breaches involve one of the two going wrong. The code usually isn't missing cryptography. It trusts something it should have checked: an ID in a URL, a role in a token, a session value the client chose.

This lesson explains the common mistakes at the concept level and shows each one in a small model you can run in your browser. Real login pages, session stores and JWT libraries cannot run here, so the framework code in this lesson is read-only. The runnable parts are stand-ins: tiny Node programs with made-up users that reproduce the logic of a flawed check and of the fix. If you haven't yet, read Password Attacks and Defenses first, because this lesson assumes passwords are already stored safely.

Five ways identity goes wrong

Weak login Guessable or reusable credentials.
Session flaws Tokens that can be fixed or stolen.
IDOR Changing an ID shows someone else's data.
Privilege escalation A normal user reaches admin features.

Authentication proves who you are. Authorization decides what you may do.

1 / 2

Broken authentication

Broken authentication is a family of weaknesses in how a site decides that you are who you claim to be. The most common ones are:

  • Unlimited guessing. The login accepts unlimited attempts, so a script can try common passwords or passwords leaked from other sites (credential stuffing).
  • Revealing error messages. "No such user" versus "wrong password" tells an attacker which usernames exist. Use one message for both.
  • Weak recovery flows. A password reset that asks "mother's maiden name", or sends a short guessable code with no expiry, is easier to attack than the password itself.
  • Missing MFA on important accounts. One stolen password is enough.
  • Default or shared credentials. Admin/admin on a management page is still found on real systems.

The defenses are familiar: slow password hashing, rate limiting and lockouts, multi-factor authentication, identical error messages, and reset tokens that are long, random, single-use and short-lived. You build a complete flow in Project: Build and Harden a Login Flow.

Sessions: how the server remembers you

HTTP is stateless, so after you log in the server gives your browser a session identifier in a cookie. From then on, that identifier is your identity. Anyone who holds it can act as you, so the identifier needs the properties of a secret: unpredictable, long, and protected in transit and in the browser.

Session fixation

In session fixation, the attacker gets a valid session ID first, somehow makes the victim use it (for example through a URL parameter or a cookie set from a sibling subdomain), and then waits for the victim to log in. If the server keeps the same ID after login and just marks it as authenticated, the attacker's copy of the ID is now logged in as the victim.

sequenceDiagram
    participant A as Attacker
    participant S as Server
    participant V as Victim
    A->>S: Request page
    S-->>A: Session ID abc123 (anonymous)
    A->>V: Make victim use abc123
    V->>S: Log in with abc123
    S-->>V: abc123 is now authenticated
    A->>S: Use abc123
    S-->>A: Logged in as the victim

Fixation: the vulnerable server keeps the same ID before and after login.

The fix is one line of design: issue a brand-new session ID at login (and at any privilege change) and discard the old one. Frameworks call this "regenerating" the session. Laravel, Django and Express session libraries all offer it.

Secure session design

A solid session cookie has these properties:

HTTP
Set-Cookie: session=9f2c...long-random...; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=3600
  • Random and long. Generated by a cryptographically secure generator, at least 128 bits. Never built from a username, counter or timestamp.
  • Secure. The cookie is only sent over HTTPS.
  • HttpOnly. JavaScript cannot read it, which limits what a cross-site scripting bug can steal (see Cross-Site Scripting and CSRF Defense).
  • SameSite. The browser does not attach it to most cross-site requests.
  • Expiry. Both an idle timeout and an absolute lifetime. Logout must destroy the session on the server, not only delete the cookie in the browser.

Access control flaws

Once the server knows who you are, it must check, on every request, whether you may do the thing you asked for. Authentication happens once per login. Authorization happens constantly.

IDOR: insecure direct object reference

An IDOR (also called broken object-level authorization) appears when the server looks up a record by an identifier supplied by the client and never checks that the record belongs to the caller. Suppose you view your invoice at /invoices/1041. If you change the URL to /invoices/1042 and see another customer's invoice, the site has an IDOR. Hiding IDs behind random-looking values makes guessing harder but does not fix it. The check has to exist.

The stand-in below models an invoice store with two users. Read the vulnerable handler first: it checks that you are logged in (authentication) but never that the invoice is yours (authorization).

Node.js IDOR: vulnerable and fixed handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The line to look at is alice asks 1042: the vulnerable handler answers 200 with Bob's data, and the fixed one answers 404. Everything else behaves the same. In real code the ownership check often lives in the query itself (WHERE id = ? AND owner_id = ?), or in a policy object that every controller must go through, so it can't be forgotten on one route.

Test with two accounts. The easiest way to find access control bugs in your own app is to log in as user A, copy a request that works, then replay it with user B's session. If it still succeeds, you have found one. Do this in your own lab only. See Building a Safe Home Lab.

Privilege escalation

Vertical escalation means a normal user reaches admin features: a hidden /admin page that has no server-side role check, or a request with role=admin in a form field the server accepts. Horizontal escalation means reaching another user's data at the same level, which is exactly what the IDOR above does. Two rules prevent most of it:

  1. Deny by default. A route with no explicit permission rule should be forbidden, not open.
  2. Never read the role from the client. The role comes from the server-side session or database, not from a hidden field, a cookie value or a URL parameter. Hiding a menu item in the interface is a convenience, not a control.

JWT mistakes

A JSON Web Token (JWT) is a signed bundle of claims, written as three Base64URL parts separated by dots: header, payload and signature. Servers use them so they don't need a session lookup. The payload is only encoded, not encrypted, so anyone can read it, and the signature is what stops anyone from changing it. Typical mistakes:

  • Trusting the header's alg field. A flawed verifier lets the token choose its own algorithm. If it accepts "alg": "none", an unsigned token passes. If a library lets a token switch from an asymmetric algorithm to HMAC, the public key can be misused as a secret. Fix: the server fixes the allowed algorithm and ignores the header's claim.
  • Not verifying the signature at all, only decoding the payload.
  • Weak shared secrets that can be guessed offline.
  • No expiry (exp) check, and no way to revoke a stolen token.
  • Sensitive data in the payload, because everyone can read it.

The stand-in models a simplified token (JSON header and payload, an HMAC signature from node:crypto). It is not a full JWT implementation, but the verification logic has the same shape. The naive verifier honors the token's own algorithm choice. The strict one does not.

Node.js Naive vs strict token verification

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The naive verifier lets the forged token through as admin and also accepts the expired one, while the strict verifier rejects everything except good. The edited token is rejected by both, because the signature really does cover the payload. That is the whole point of signing, and it is why the weakness in a real library is almost always in how the signature is checked, never in HMAC itself.

Real vs stand-in. In production, use a maintained JWT library, pin the accepted algorithms and key in configuration, and set short expiry times. The model above only shows why those settings matter. For many web apps, a server-side session with an opaque random ID is simpler and easier to revoke than a JWT.

Finding these flaws in an authorized test

A tester checks authentication and access control by exercising the application, never by guessing at systems outside the agreed scope:

  • Log in as two normal users and one admin, then replay each request under the other identities.
  • Try each privileged URL while logged out, and as a low-privilege user.
  • Check that the session ID changes at login and that logout invalidates it on the server.
  • Inspect cookie flags (Secure, HttpOnly, SameSite) in the browser's developer tools.
  • Read tokens' payloads, look for secrets and check that a changed payload is rejected.

Intercepting proxies make this repeatable, and Web Application Security Basics introduces the idea read-only. The findings go into your report as described in Writing a Penetration Test Report.

JWT structure, weak secrets and key confusion

The section above covered the common mistakes. This one looks at the token more closely and adds two attacks that deserve names.

Structure

A JWT is three Base64URL strings joined by dots: header.payload.signature.

  • The header names the token type and the signing algorithm (alg), for example HS256 (HMAC with SHA-256, a shared secret), RS256 (RSA signature with a private key, verified with the public key) or ES256 (ECDSA). It may also carry a key ID (kid) that says which key to verify with.
  • The payload holds claims: who the token is about (sub), who issued it (iss), who it is for (aud), when it expires (exp) and when it was issued (iat), plus application data such as a role.
  • The signature covers the first two parts, so any change to them invalidates it.

Anyone can decode the first two parts; only the signature needs a key. A verifier must therefore check the signature, the algorithm it expects, the issuer and audience, and the expiry. Many libraries make each of those an explicit option precisely because forgetting one is a classic vulnerability.

Weak secrets

With HS256 the same secret signs and verifies. If the secret is short or a dictionary word, an attacker who captures one valid token can test guesses offline: sign the header and payload with each candidate and compare the result to the signature. No request to the server is needed and nothing is logged. Once the secret is found, the attacker can mint tokens with any claims. The cure is a secret of at least 256 random bits from a cryptographically secure generator (or an asymmetric algorithm), stored outside the code and rotated on a schedule.

Key confusion (algorithm confusion)

A server that uses RS256 holds a public key, which is not secret and is often published. If its verification code lets the token pick the algorithm, an attacker can set alg to HS256 and sign the token using the public key as the HMAC secret. A flawed verifier then uses the public key as an HMAC secret and accepts the signature. The cure is the same pinning rule from earlier: the server decides which algorithm each key is for, and ignores the header's claim. The related kid header is also untrusted input: never use it to build a file path or SQL query without validation.

The stand-in demonstrates both ideas with invented values. It cracks a tiny weak secret from a captured token using a short word list, and shows that a verifier which pins the algorithm rejects the confused token. It uses HMAC only (so there is no RSA key), with a label standing in for the public key.

Node.js Weak secret check and algorithm pinning

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Best practices

  • Pin the algorithm and the key per issuer in server configuration; never let the token choose.
  • Validate exp, nbf, iss and aud on every request, with a small clock-skew allowance.
  • Keep access tokens short-lived and use refresh tokens that can be revoked; store them where scripts cannot read them (an HttpOnly cookie) rather than in localStorage when XSS is a concern (XSS and CSRF).
  • Do not put secrets or personal data in the payload; it is readable by anyone.
  • Use a well-maintained library, keep it updated, and rotate signing keys with a kid you map to a fixed list.
  • Remember that a JWT is not automatically better than a server-side session. If you need instant logout or revocation, sessions are simpler.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A site keeps the same session ID before and after login. Which attack does this allow?

    If an attacker can plant a known session ID in a victim's browser and the server keeps it after login, the attacker's copy becomes authenticated. Regenerate the ID at login.
  2. 2. Changing /invoices/1041 to /invoices/1042 shows another customer's invoice. What is the root cause?

    This is an IDOR: missing object-level authorization. Random IDs make guessing harder but the ownership check is still required.
  3. 3. Why must a JWT verifier ignore the algorithm claimed in the token header?

    The server decides which algorithm and key are acceptable. Letting the token choose lets an attacker pick the weakest or no verification.
  4. 4. Which is the best place to take a user's role from when authorizing a request?

    Anything the client sends can be changed. Roles must come from data the server controls.
  5. 5. Hiding the Admin menu from normal users is enough to protect admin features.

    Hidden links are not security. Anyone can request the URL directly, so the server must enforce the rule.

Summary

  • Authentication proves identity, authorization decides permissions, and both must be enforced by the server on every request.
  • Broken authentication includes unlimited guessing, revealing errors, weak recovery and missing MFA.
  • A session ID is a secret: random, long, Secure, HttpOnly, SameSite, expiring, and regenerated at login.
  • IDOR happens when the server trusts an ID from the client without an ownership check; random IDs don't fix it.
  • Prevent escalation with deny-by-default rules and roles that come from server-side data.
  • A JWT verifier must pin the algorithm, verify the signature, check expiry and keep secrets out of the payload.
  • Test with several accounts, in your own lab or a scope you are authorized for.

Next: Web Application Security Basics.