Auth & Security/
Lesson

Imagine you arrive at an exclusive nightclub. At the door, a bouncer checks your ID, this is authenticationWhat is authentication?Verifying who a user is, typically through credentials like a password or token.. Inside, different areas require different wristbands, this is authorizationWhat is authorization?Checking what an authenticated user is allowed to do, like whether they can delete records or access admin pages.. Both are essential, but they solve different problems.

AuthenticationWhat is authentication?Verifying who a user is, typically through credentials like a password or token.: proving who you are

Authentication verifies identity. It answers the fundamental question: "Are you really who you claim to be?"

Think of it like airport security. You present your passport (proof of identity), the agent verifies it's genuine, compares your face to the photo, and stamps your boarding pass. Once authenticated, the system knows exactly who you are.

Common authentication methods

MethodWhat it provesExamples
PasswordSomething you know"CorrectHorseBatteryStaple"
TokenSomething you haveJWT, session cookie, API key
BiometricsSomething you areFingerprint, Face ID
MFA/2FAMultiple factorsPassword + SMS code

Passwords are the most common but also the weakest. People reuse them, write them down, or choose weak ones like "password123". They're vulnerable to phishing and brute force attacks.

Tokens work like temporary badges. After proving your identity once (with a password), you receive a tokenWhat is token?The smallest unit of text an LLM processes - roughly three-quarters of a word. API pricing is based on how many tokens you use.. Subsequent requests use this token instead of resending your password. Tokens expire, limiting the damage if stolen.

Multi-factor authentication combines methods. Even if someone steals your password, they still need your phone for the SMS code. This dramatically improves security.

Remember
Authentication is about identity. Once you know who someone is, you need to decide what they're allowed to do. That's authorization.
02

AuthorizationWhat is authorization?Checking what an authenticated user is allowed to do, like whether they can delete records or access admin pages.: controlling access

Authorization determines what an authenticated user can do. A bank teller and a bank manager might both authenticate successfully, but they see different data and can perform different actions.

Types of access control

RBACWhat is rbac?Role-Based Access Control - assigning permissions to roles (like admin or editor), then giving users roles instead of individual permissions. (Role-Based Access Control) assigns permissions to roles, then assigns roles to users:

Admin role → [create, read, update, delete]
User role → [read, update_own]

Alice gets Admin role
Bob gets User role

This is simple and scales well. When someone changes jobs, you change their role, not individual permissions.

ABACWhat is abac?Attribute-Based Access Control - an authorization model that makes decisions based on attributes of the user, resource, and environment rather than fixed roles. (Attribute-Based Access Control) makes decisions based on attributes:

Allow access if:
- User.department == Resource.department
- AND User.level >= 'senior'
- AND Time.hour between 9 and 17

More flexible but complex. Used in enterprise systems with fine-grained security requirements.

ACL (Access Control Lists) specify permissions per resource:

Document #123:
- Alice: read, write
- Bob: read
- Charlie: none

Simple for small systems, but doesn't scale well to thousands of resources.

03

The typical authenticationWhat is authentication?Verifying who a user is, typically through credentials like a password or token. flow

Here's how authentication works in a modern web application:

1. User submits credentials (email + password)2. Server verifies credentials against database
        ↓
3. Server generates token (JWT or session)4. Token sent to client (stored in cookie or localStorage)5. Client includes token in subsequent requests
        ↓
6. Server verifies token and processes request

The key insight: after step 3, the password is never sent again. The tokenWhat is token?The smallest unit of text an LLM processes - roughly three-quarters of a word. API pricing is based on how many tokens you use. proves identity for subsequent requests.

04

Security best practices

Never trust the client

// ❌ WRONG: Trusting client-provided user ID
app.post('/update-profile', (req, res) => {
  updateUser(req.body.userId, req.body.data);  // Dangerous!
});

// ✅ RIGHT: Verify identity server-side from token
app.post('/update-profile', requireAuth, (req, res) => {
  // req.userId comes from verified JWT, not client
  updateUser(req.userId, req.body.data);
});

Anyone can send any data in a request. The client could claim to be user ID 99999. Always verify who they are from a trusted source (your tokenWhat is token?The smallest unit of text an LLM processes - roughly three-quarters of a word. API pricing is based on how many tokens you use. or sessionWhat is session?A server-side record that tracks a logged-in user. The browser holds only a session ID in a cookie, and the server looks up the full data on each request.).

Validate at every layer

Security works like layers of an onion:

  1. Client: Quick validation for UX (disable submit button on invalid input)
  2. APIWhat is api?A set of rules that lets one program talk to another, usually over the internet, by sending requests and getting responses.: Strict validation with ZodWhat is zod?A TypeScript-first schema validation library that validates data at runtime while automatically inferring static TypeScript types from the schema. or Joi (never trust the client)
  3. Database: Constraints and types (final safety net)

Each layer catches what the previous one missed.

Defense in depth

Don't rely on a single security measure. If authenticationWhat is authentication?Verifying who a user is, typically through credentials like a password or token. fails, rate limitingWhat is rate limiting?Restricting how many requests a client can make within a time window. Prevents brute-force attacks and protects your API from being overwhelmed. should block brute force attacks. If that fails, input validation prevents SQL injectionWhat is sql injection?An attack where user input is inserted directly into a database query, letting the attacker read, modify, or delete data. Parameterized queries prevent it.. Multiple layers protect you.

Principle of least privilege

Give users only the permissions they absolutely need:

  • Don't make everyone an admin
  • Use tokens with limited scopeWhat is scope?The area of your code where a variable is accessible; variables declared inside a function or block are invisible outside it. (only read, not write)
  • Database connections should use restricted database users

Fail securely

When something goes wrong, default to denying access:

// ✅ Good: Deny by default
if (!user || !passwordMatches) {
  return res.status(401).json({ error: 'Invalid credentials' });
}
// Continue only if authenticated

05

Quick reference: Auth concepts

ConceptQuestion it answersExample
AuthenticationWho are you?Login with password, receive JWT
AuthorizationWhat can you do?Admin can delete, User can only read
RBACWhich role?User vs Admin vs Moderator
SessionAre you still logged in?Cookie with session ID
TokenCan you prove identity?JWT containing user ID

Master these distinctions, and you'll build authenticationWhat is authentication?Verifying who a user is, typically through credentials like a password or token. systems that are both secure and maintainable.