0% found this document useful (0 votes)
2 views8 pages

Web Auth Guide

This beginner's guide explains the concepts of cookies, sessions, tokens, and web authentication, detailing how they help websites remember users and secure data. It covers the creation and types of cookies, the flow of session-based and token-based authentication, and the use of JWTs and OAuth 2.0 for secure access. Additionally, it provides best practices for storing tokens and maintaining security in web applications.

Uploaded by

raj2505000
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views8 pages

Web Auth Guide

This beginner's guide explains the concepts of cookies, sessions, tokens, and web authentication, detailing how they help websites remember users and secure data. It covers the creation and types of cookies, the flow of session-based and token-based authentication, and the use of JWTs and OAuth 2.0 for secure access. Additionally, it provides best practices for storing tokens and maintaining security in web applications.

Uploaded by

raj2505000
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Cookies, Tokens & Web Auth — Beginner's Guide

WEB SECURITY · BEGINNER'S GUIDE

Cookies, Tokens & Web Auth


Explained Simply
Everything you need to understand how websites remember who you are, keep you logged
in, and protect your data.

01 — COOKIES

What Are Cookies?


When you visit a website, your browser and the server need a way to "remember" things about
you across multiple page loads. HTTP is stateless — by itself, every request is brand new, with
zero memory of the past. Cookies are the fix: tiny pieces of text your browser stores and
automatically sends back to the server on every request.

ANALOGY
Think of a cookie like the wristband you get at a theme park. It proves you already paid. Every
time you approach a ride, the staff checks the band — they don't need to ask your name again.

How a Cookie Is Born


DIAGRAM — Cookie Creation Flow

① Browser sends GET /login → Server (no cookie yet)

② Server responds: Set-Cookie: session=abc123

③ Browser stores cookie, sends it on every future request to this domain

GET /dashboard Cookie: session=abc123

The Set-Cookie Header


The server sends a cookie via the Set-Cookie HTTP response header:

Set-Cookie: sessionId=abc123xyz; Path=/; HttpOnly; Secure; SameSite=Strict; Max-


Age=3600

Page 1
Cookies, Tokens & Web Auth — Beginner's Guide

Attribute What It Does

HttpOnly JavaScript cannot read the cookie. Protects from XSS attacks.

Secure Cookie only sent over HTTPS, never plain HTTP.

SameSite=Strict Cookie not sent on cross-site requests. Protects from CSRF attacks.

Max-Age How long (in seconds) before the cookie expires. 3600 = 1 hour.

Path=/ Which URL paths on the domain can receive the cookie.

Types of Cookies
Session Cookie Persistent Cookie

No expiry date set Has Max-Age or Expires set


Deleted when the browser tab or window closes Survives browser close and restart
Used for: login during one visit Used for: "Remember me" feature
⏱ Lives in memory only 💾 Saved to disk

02 — SESSIONS

Sessions & Cookie-Based Authentication


A session is a temporary "conversation" between your browser and a server. When you log in,
the server creates a session record, stores it somewhere (memory, database, Redis), and
hands you a session ID cookie. Every subsequent request proves who you are by presenting
that ID.

KEY IDEA
The cookie only holds a random ID (like sess_k9x3mL2P). The actual user data — name, role,
permissions — lives on the server side. This is why it's called server-side session.

Full Login Flow — Step by Step


DIAGRAM — Cookie-Based Auth Full Flow

① Browser → Server: POST /login { username, password }

② Server verifies credentials, creates session record in session store

③ Session Store returns session ID to Server

Page 2
Cookies, Tokens & Web Auth — Beginner's Guide

④ Server → Browser: Set-Cookie: sessionId=abc123

⑤ Browser → Server: GET /dashboard Cookie: abc123

⑥ Server looks up session abc123 in session store

⑦ Session Store: Found → user = Alice, role = admin. Server responds with data.

Logout
When you click "Log out," the server deletes the session record from its store and instructs the
browser to clear the cookie. Even if someone stole the cookie ID, it's now useless — the server
has no matching session.

// Express session destroy


[Link](err => {
[Link]('sessionId');
[Link]('/login');
});

03 — TOKENS

Token-Based Authentication
Sessions work great, but they have a problem: the server must store every active session. For
huge apps with millions of users this is expensive. Token-based auth solves this by putting all
the user info inside the token itself — the server doesn't store anything.

Session-Based Token-Based

State lives on the SERVER State lives in the TOKEN


Browser holds: just an ID Browser holds: signed token with user data
Server holds: user data, expiry, role Server holds: nothing (just the secret key)
✓ Easy to revoke instantly ✓ Stateless — scales easily
✗ Needs shared session store (scaling) ✗ Harder to revoke before expiry

The Access Token


An access token is a credential — a string the browser attaches to API requests to prove
identity. It's usually sent in the Authorization HTTP header, not a cookie.

GET /api/profile HTTP/1.1


Host: [Link]
Authorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...

Page 3
Cookies, Tokens & Web Auth — Beginner's Guide

WHY 'BEARER'?
"Bearer" means whoever bears (carries) this token can access the resource. It's just a naming
convention from the OAuth standard. Keep tokens secret — anyone who has it can use it.

04 — JWT

JSON Web Tokens (JWT)


JWTs are the most popular format for access tokens. A JWT is a Base64-encoded string in
three dot-separated parts. The server's cryptographic signature on the last part proves the data
hasn't been tampered with.

Anatomy of a JWT
HEADER PAYLOAD SIGNATURE
eyJhbGciOiJIUzI1NiJ9 eyJ1c2VyIjoiYWxpY2UifQ SflKxwRJSMeKKF2QT4fw

{ "alg": "HS256", "typ": { "sub": "user_123", "name": HMAC-SHA256( header +


"JWT" } "Alice", "role": "admin", payload, secret_key )
"exp": 1716703600 }

⚠ The payload is Base64-encoded, NOT encrypted — anyone can decode and read it! Never put
passwords, credit cards, or secrets in a JWT payload.

JWT Fields (Claims)


Claim Name Meaning

sub Subject Who the token is about (usually user ID)

iat Issued At Unix timestamp of when it was created

exp Expiration Unix timestamp of when it stops being valid

iss Issuer Who made the token (e.g. [Link])

aud Audience Who should accept it (e.g. [Link])

role Custom Any custom data you want to add

Verifying a JWT ([Link])

const jwt = require('jsonwebtoken');

Page 4
Cookies, Tokens & Web Auth — Beginner's Guide

const SECRET = [Link].JWT_SECRET;

// 1. Create a token after login


const token = [Link](
{ sub: 'user_123', name: 'Alice', role: 'admin' },
SECRET,
{ expiresIn: '1h' }
);

// 2. Verify on each request


try {
const payload = [Link](token, SECRET);
[Link]([Link]); // 'Alice'
} catch (err) {
// Token expired or tampered — reject the request
}

05 — REFRESH TOKENS

Refresh Tokens & Token Rotation


Access tokens are short-lived (15 minutes to 1 hour) for security. But you don't want users to re-
login every hour. The solution: a refresh token — a long-lived token stored securely, used only
to get a new access token when the old one expires.

THE TWO-TOKEN SYSTEM


Access Token — Short-lived (15 min). Used for every API call. Stored in memory. Refresh Token
— Long-lived (days/weeks). Used only to refresh. Stored in an HttpOnly cookie.

Refresh Token Flow


DIAGRAM — Refresh Token Flow

① Browser → Auth Server: POST /login

② Auth Server returns: access_token (15m) + refresh_token (7d)

③ Browser → API: GET /api/data Authorization: Bearer access_token

④ API: 200 OK — data returned

⏱ 15 minutes pass — access token expires

⑤ Browser → API: GET /api/data (expired token) → 401 Unauthorized

⑥ Browser → Auth Server: POST /refresh Cookie: refresh_token

⑦ Auth Server issues new access_token — user stays logged in, seamlessly!

Page 5
Cookies, Tokens & Web Auth — Beginner's Guide

Token Rotation
A best practice: each time a refresh token is used, the server issues a brand-new refresh token
and invalidates the old one. This is called token rotation. If an attacker steals an old refresh
token, it's already dead.

Refresh Token #1 Refresh Token #2 If #1 is Stolen

Used → INVALIDATED Issued. Used → invalidated Attacker tries to use it → 403


Forbidden ✓

Where to Store Tokens


Storage Access Token Refresh Token

Memory (JS variable) ✅ Recommended — gone on tab ❌ Too short-lived


close

HttpOnly Cookie ⚠ Possible (CSRF risk) ✅ Best — JS can't read it

localStorage ⚠ Risky — XSS can steal it ❌ Dangerous

sessionStorage ⚠ Same XSS risk as localStorage ❌ Dangerous

06 — OAUTH 2.0 & OIDC

OAuth 2.0 — "Login with Google"


OAuth 2.0 is an authorization framework that lets you say "I allow this app to access my Google
data, but I'm NOT giving this app my Google password." It's the standard behind every "Login
with Google / GitHub / Facebook" button.

QUICK DISTINCTION
OAuth 2.0 = authorization (what can this app do?) OpenID Connect (OIDC) = authentication built
on OAuth (who is this user?) — adds an ID Token (a JWT) to the mix.

Authorization Code Flow — Step by Step


DIAGRAM — OAuth 2.0 Authorization Code Flow

① User clicks 'Login with Google' → Your App redirects user to Google's auth URL

Page 6
Cookies, Tokens & Web Auth — Beginner's Guide

② Google shows its own login page to the user

③ User logs in & clicks 'Allow' on Google's consent screen

④ Google redirects back to your app with a one-time auth code: ?code=4/xyz...

⑤ Your App server exchanges code + client_secret for tokens (server-to-server)

⑥ Google returns access_token + id_token (JWT with user info)

⑦ Your App calls Google APIs with access_token (only approved scopes)

Scopes — Limiting What the App Can Do


When your app redirects to Google, it requests specific scopes — permissions. The user sees
exactly what they're approving.

[Link]
?client_id=YOUR_CLIENT_ID
&redirect_uri=[Link]
&response_type=code
&scope=openid email profile ← only these 3 permissions
&state=random_csrf_string

07 — COMPARISON

Putting It All Together


Which Auth Method for What?
Cookies + Sessions JWT Access Tokens OAuth 2.0 + OIDC

Best for: Best for: Best for:


Traditional server-rendered web REST APIs, SPAs, Social login, third-party
apps, small-medium scale microservices, mobile apps integrations, delegated access
Example: e-commerce, blogs Example: React SPA + Example: "Login with Google"
backend API
🍪 Session ID in cookie 🔐 Auth code → token
🔑 Stateless signed token exchange

Golden Security Rules


Rule Why

Always use HttpOnly + Secure on auth cookies Prevents JS theft and plain-HTTP sniffing

Page 7
Cookies, Tokens & Web Auth — Beginner's Guide

Rule Why

Keep access tokens short-lived (< 1 hour) Limits damage if one is stolen

Rotate refresh tokens on each use Detect stolen tokens automatically

Never put sensitive data in a JWT payload The payload is only Base64, not encrypted

Validate exp, iss, aud on every JWT Prevents expired or forged tokens from
working

Use SameSite=Strict or Lax on cookies Defends against CSRF attacks

Store access tokens in memory, not localStorage localStorage is readable by any JS on the
page

Glossary
Term Definition

Cookie Small text stored by the browser, sent automatically with every request to the
origin domain.

Session Server-side record of a user's state, keyed by a session ID stored in a cookie.

JWT JSON Web Token — a self-contained, signed token carrying user claims in a
compact format.

Access Token Short-lived credential used to authenticate API requests.

Refresh Token Long-lived token used only to obtain a new access token without re-login.

OAuth 2.0 Authorization framework allowing a user to grant limited access to their account
on one service to another service.

OIDC OpenID Connect — identity layer on top of OAuth 2.0 that adds user
authentication via an ID Token.

XSS Cross-Site Scripting — attacker injects malicious JS to steal cookies/tokens.

CSRF Cross-Site Request Forgery — tricking a logged-in user's browser into making
an unwanted request.

Bearer Token A token where possession = access. Sent in Authorization: Bearer <token>
header.

Page 8

You might also like