Authentication & Authorization: Core Concepts

TL;DR

Auth has 6 building blocks: credentials (what you provide), hashing (how passwords are stored), sessions (server remembers you), tokens (you carry proof), access control (RBAC/ABAC rules), and MFA (layered factors). Master these and every auth system makes sense.

Concept Map

Concept map showing the 6 building blocks of authentication and authorization and how they connect
Explain Like I'm 12

Think of auth like getting into a theme park. Your ticket (credentials) proves you paid. The park stamps your hand (session/token) so you don't need to show your ticket every time. Different wristband colors (roles) let you ride different rides — VIP gets everything, basic gets most. And some rides require you to be tall enough AND have the right wristband (multi-factor). The lock on the ticket booth (hashing) makes sure nobody can peek at everyone's payment info.

Cheat Sheet

ConceptWhat It DoesKey Tools
CredentialsSomething you present to prove identityPasswords, API keys, SSH keys, certificates
Hashing & SaltingOne-way transform so passwords aren't stored in plaintextbcrypt, Argon2, scrypt, PBKDF2
SessionsServer stores login state, sends a session ID cookieexpress-session, Flask-Login, Redis
TokensClient carries a signed proof of identityJWT, OAuth access tokens, refresh tokens
Access ControlRules that map users to permissionsRBAC, ABAC, ACLs, OAuth scopes
Multi-Factor AuthRequires 2+ independent proof typesTOTP apps, SMS, hardware keys (FIDO2/WebAuthn)

The Building Blocks

1. Credentials

A credential is anything you present to prove you are who you claim. The most common is a username + password pair, but credentials come in many forms:

Credential TypeFactor CategoryStrength
Password / PINSomething you knowWeak alone (phishable, guessable)
SSH private keySomething you haveStrong (never leaves your machine)
FIDO2 hardware keySomething you haveVery strong (phishing-resistant)
Fingerprint / Face IDSomething you areStrong (hard to fake, can't be shared)
X.509 certificateSomething you haveStrong (PKI-backed, used in mTLS)
Tip: Passwords are the weakest credential type. Whenever possible, prefer SSH keys, hardware tokens, or certificate-based auth.

2. Hashing & Salting

You never store passwords in plaintext. A hash function converts a password into a fixed-length string that can't be reversed. A salt is random data added before hashing so identical passwords produce different hashes.

# Python: Hash a password with bcrypt
import bcrypt

password = b"my_secure_password"
salt = bcrypt.gensalt(rounds=12)
hashed = bcrypt.hashpw(password, salt)

# Verify later
if bcrypt.checkpw(b"my_secure_password", hashed):
    print("Password matches!")
Warning: Never use MD5 or SHA-256 alone for passwords — they're too fast, making brute-force attacks easy. Use bcrypt, Argon2, or scrypt which are intentionally slow.

3. Sessions

In session-based auth, after you log in, the server creates a session (a record of your login state) and sends back a session ID as a cookie. On every subsequent request, your browser sends that cookie, and the server looks up your session.

// Express.js session setup
const session = require('express-session');

app.use(session({
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: false,
  cookie: { secure: true, httpOnly: true, maxAge: 3600000 }
}));

// After login
app.post('/login', (req, res) => {
  // ... verify credentials ...
  req.session.userId = user.id;
  req.session.role = user.role;
  res.redirect('/dashboard');
});
Info: Sessions are stateful — the server must store session data (in memory, Redis, or a database). This can be a bottleneck at scale, which is why many APIs use stateless tokens instead.

4. Tokens

Token-based auth flips the model: instead of the server remembering you, it gives you a signed token (like a JWT) that you carry. Each request includes the token, and the server verifies the signature without looking anything up.

// JWT creation (Node.js)
const jwt = require('jsonwebtoken');

const token = jwt.sign(
  { userId: 123, role: 'admin' },  // payload (claims)
  process.env.JWT_SECRET,           // signing key
  { expiresIn: '1h' }              // options
);

// JWT verification
try {
  const decoded = jwt.verify(token, process.env.JWT_SECRET);
  console.log(decoded.userId); // 123
} catch (err) {
  console.log('Invalid or expired token');
}
SessionsTokens
Server stores stateClient carries state
Easy to revoke (delete session)Hard to revoke (until expiry)
Needs sticky sessions or shared storeAny server can verify
Great for web apps with cookiesGreat for APIs and microservices

5. Access Control

Once you know WHO someone is (authentication), you need rules for WHAT they can do (authorization). The most common models:

ModelHow It WorksBest For
RBAC (Role-Based)Users get roles (admin, editor, viewer); roles have permissionsMost web apps, enterprise systems
ABAC (Attribute-Based)Policies use attributes (time, location, department, resource owner)Complex enterprise rules, cloud IAM
ACL (Access Control List)Each resource lists who can access it and howFile systems, network firewalls
OAuth ScopesTokens carry specific permission strings (read:email, write:repo)APIs, third-party integrations
# Simple RBAC middleware example (Python/Flask)
from functools import wraps
from flask import session, abort

def require_role(role):
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            if session.get('role') != role:
                abort(403)  # Forbidden
            return f(*args, **kwargs)
        return wrapper
    return decorator

@app.route('/admin')
@require_role('admin')
def admin_panel():
    return 'Welcome, admin!'

6. Multi-Factor Authentication (MFA)

MFA requires two or more different factor types. A password + a TOTP code from your phone = MFA. Two passwords ≠ MFA (same factor type).

FactorExamplesPhishing Resistant?
Something you knowPassword, PIN, security questionNo
Something you haveTOTP app, SMS code, hardware keyHardware keys: Yes. SMS/TOTP: Partially
Something you areFingerprint, Face ID, iris scanYes
Tip: FIDO2/WebAuthn hardware keys (YubiKey, etc.) are the gold standard for MFA — they're phishing-resistant because the key cryptographically binds to the specific website origin.

Test Yourself

Why should you use bcrypt instead of SHA-256 for password hashing?

bcrypt is intentionally slow (configurable work factor) which makes brute-force attacks impractical. SHA-256 is designed to be fast, so an attacker can try billions of guesses per second. bcrypt also has built-in salting.

What's the key trade-off between session-based and token-based authentication?

Sessions are stateful (server stores state, easy to revoke, needs shared storage at scale). Tokens are stateless (client carries proof, any server can verify, but hard to revoke before expiry). Sessions suit traditional web apps; tokens suit APIs and microservices.

A user enters a password and a TOTP code from their authenticator app. Is this MFA? What about a password + a security question?

Password + TOTP = yes, MFA (something you know + something you have). Password + security question = no, not MFA — both are "something you know" (same factor category).

When would you choose ABAC over RBAC?

ABAC is better when access decisions depend on dynamic attributes like time of day, geographic location, resource ownership, or department — things that can't be captured in simple role assignments. Cloud platforms like AWS IAM use ABAC-style policies.

Why is the httpOnly flag important on session cookies?

httpOnly prevents JavaScript from reading the cookie, which blocks XSS attacks from stealing session IDs. Even if an attacker injects a script, they can't access document.cookie to exfiltrate the session.