<< back to Guides

πŸ” Deep Dive into Authentication

🧭 What Is Authentication?

Authentication is the process of verifying who a user is before granting access to a system.
It answers: β€œIs this user who they claim to be?”
(Authorization comes after authentication.)


🧁 Cookie-Based Authentication

How It Works:

  1. User logs in β†’ credentials are verified.
  2. Server creates a session and stores it in memory/store.
  3. A session ID is returned to the client as a cookie.
  4. Browser sends cookie with each request.
  5. Server retrieves session and authenticates the user.

βœ… Pros:

⚠️ Cons:

# Laravel session-based login (simplified)
Auth::attempt([
  'email' => $request->email,
  'password' => $request->password,
]);

πŸ’  Token-Based Authentication (Stateless)

JSON Web Tokens (JWT)

JWTs are self-contained tokens that carry user info and are signed.

How It Works:

  1. User logs in β†’ server returns a JWT.
  2. Client stores it (e.g. localStorage or HTTP-only cookie).
  3. Token is sent in every request (usually Authorization header).
  4. Server verifies the signature and grants access.

JWT Structure:

A JWT consists of three parts separated by dots:

<HEADER>.<PAYLOAD>.<SIGNATURE>

Each part is Base64URL-encoded:

// Example decoded payload
{
  "sub": "1234567890",
  "name": "John Doe",
  "iat": 1516239022
}

βœ… Pros:

⚠️ Cons:


JWT Examples:

// Java JWT verification (using jjwt)
Claims claims = Jwts.parser()
  .setSigningKey(secretKey)
  .parseClaimsJws(token)
  .getBody();
// Laravel - creating a JWT (with tymondesigns/jwt-auth)
$token = Auth::attempt(['email' => $email, 'password' => $password]);
// Send token back to client

πŸ” PASETO (Platform-Agnostic SEcurity TOkens)

A modern alternative to JWT with safer cryptographic defaults.

Features:

PASETO Example:

// Node.js with paseto package
const { V2 } = require('paseto');
const token = await V2.encrypt({ userId: 1 }, secretKey);

βœ… Pros:

⚠️ Cons:


🧾 Other Auth Methods

πŸ” OAuth2 + OpenID Connect

πŸ“„ SAML

πŸ”‘ API Keys


πŸ—‚οΈ Session vs JWT Comparison

Feature Sessions JWT
Storage Server-side Client-side
Stateless ❌ βœ…
Revocable βœ… ❌ (unless tracked)
CSRF Protection βœ… Optional
Susceptible to XSS βœ… if cookie not secure βœ… if stored in localStorage

🧠 Choosing the Right Auth Method

Use Case Recommended Auth
Web App (monolith) Cookies + Session
SPA / Public API JWT or OAuth2
Microservices JWT or PASETO (internal tokens)
Enterprise / SSO SAML or OpenID Connect
Backend-for-Frontend (BFF) JWT or Session in secure cookie

πŸ” Best Practices

<< back to Guides