Cryptography & Security

Authentication & Authorization

From passwords and sessions to JWTs, OAuth 2.0, SAML, and passwordless WebAuthn -- how systems verify identity and enforce permissions.

01 / Foundations

Authn vs Authz & Session-Based Auth

Authentication (authn) answers "who are you?" -- it verifies a claimed identity. Authorization (authz) answers "what are you allowed to do?" -- it enforces permissions after identity is established. Every secure system needs both, and they are separate concerns even when frameworks bundle them together.

AspectAuthenticationAuthorization
QuestionWho is this user?What can they access?
WhenBefore authorizationAfter authentication
MechanismPasswords, tokens, biometricsRoles, policies, ACLs
HTTP status on failure401 Unauthorized403 Forbidden

Session-Based Authentication

The classic server-side pattern: after verifying credentials, the server creates a session object, stores it (in memory, Redis, or a database), and sends a Set-Cookie header with a random session ID. Every subsequent request includes this cookie, and the server looks up the session to identify the user.

Session-Based Auth Flow
POST /login (creds)
->
Server validates
->
Create session in store
Set-Cookie: sid=abc123
->
Browser sends cookie
->
Server looks up session
Advantages of Sessions
Server can instantly revoke access by deleting the session. Session data never leaves the server, so sensitive claims stay private. Built-in CSRF protection with SameSite cookies.
Drawbacks
Requires server-side state, which complicates horizontal scaling (sticky sessions or shared session store). Not ideal for cross-domain or mobile-native apps where cookies are awkward.
02 / Tokens

JSON Web Tokens (JWT)

A JWT is a compact, URL-safe token consisting of three Base64url-encoded parts separated by dots: header.payload.signature. The server does not need to store state -- it verifies the signature and reads claims directly from the token.

// Header
{ "alg": "RS256", "typ": "JWT" }

// Payload (claims)
{
  "sub": "user_42",
  "iss": "auth.example.com",
  "exp": 1717200000,
  "roles": ["admin"]
}

// Signature
RSASHA256(base64url(header) + "." + base64url(payload), privateKey)

Signing Algorithms

AlgorithmTypeKeyUse Case
HS256Symmetric (HMAC)Shared secretSingle service, simple setups
RS256Asymmetric (RSA)Private signs, public verifiesDistributed systems, JWKS
ES256Asymmetric (ECDSA)Smaller keys, same securityMobile, IoT, performance-sensitive

Access + Refresh Tokens

A common pattern pairs a short-lived access token (5-15 min) with a longer-lived refresh token (days/weeks). When the access token expires, the client presents the refresh token to get a new pair. The refresh token is stored securely (httpOnly cookie or secure storage) and can be revoked server-side.

Token Refresh Flow
Access token expires
->
POST /token (refresh_token)
->
New access + refresh
JWT Pitfalls
No revocation by default -- once issued, a JWT is valid until it expires. You need a blocklist or short expiry to mitigate this. Payload is not encrypted -- Base64 is encoding, not encryption. Never put secrets in claims. Algorithm confusion attacks -- always validate alg against a server-side allowlist; never trust the token header alone. Token bloat -- every claim increases every request's size. Keep payloads lean.
03 / Delegation

OAuth 2.0

OAuth 2.0 is a delegation framework -- it lets a user grant a third-party app limited access to their resources on another service, without sharing their password. It defines several grant types for different scenarios.

Authorization Code + PKCE

The most common and secure flow for web and mobile apps. PKCE (Proof Key for Code Exchange) prevents authorization code interception attacks, which is why it is now required even for server-side apps in best-practice guidance.

Auth Code + PKCE Flow
1. App generates code_verifier + code_challenge
2. Redirect to /authorize?code_challenge=...
->
3. User logs in & consents
4. Redirect back with auth code
->
5. POST /token (code + code_verifier)
6. Server verifies challenge, returns access_token

Other Grant Types

Client Credentials

Machine-to-machine auth. No user involved. The client authenticates with its own credentials and gets an access token directly. Used for backend services, cron jobs, microservice communication.

Device Code

For input-constrained devices (smart TVs, CLI tools). The device shows a code, the user enters it on a browser. The device polls until the user completes authorization.

Scopes

Scopes limit what an access token can do. They are strings like read:user, write:repos, openid profile email. The authorization server includes granted scopes in the token response. Clients should always request the minimum scopes needed.

Key Insight
OAuth 2.0 is about authorization, not authentication. It tells you what a token can access, but it does not tell you who the user is. That is what OpenID Connect adds on top.
04 / Identity Layer

OpenID Connect & SAML 2.0

OpenID Connect (OIDC)

OIDC is a thin identity layer built on top of OAuth 2.0. It adds a standardized way to get user identity information. When you request the openid scope, the authorization server returns an ID Token (a JWT) alongside the access token.

ComponentPurpose
ID TokenJWT containing user identity claims (sub, email, name). Consumed by the client, never sent to APIs.
UserInfo EndpointGET /userinfo with access token. Returns additional claims about the authenticated user.
Discovery DocumentGET /.well-known/openid-configuration returns all endpoints, supported scopes, algorithms, and keys (JWKS URI).
ID Token vs Access Token
The ID token is for the client to learn who the user is. The access token is for API servers to authorize requests. Never send the ID token to an API as a bearer token.

SAML 2.0

Security Assertion Markup Language (SAML) is an older XML-based standard widely used in enterprise SSO. It involves two parties:

RoleDescriptionExample
Identity Provider (IdP)Authenticates the user and issues assertionsOkta, Azure AD, OneLogin
Service Provider (SP)Relies on IdP assertions to grant accessSalesforce, Jira, internal apps

A SAML Assertion is an XML document containing authentication statements (when/how the user authenticated), attribute statements (user metadata), and authorization decision statements. Assertions are digitally signed and often encrypted.

SAML SSO Flow (SP-Initiated)
User visits SP
->
SP redirects to IdP
->
User authenticates
IdP sends signed assertion
->
SP validates & creates session
05 / Passwordless

WebAuthn & FIDO2

WebAuthn (Web Authentication API) enables passwordless authentication using public-key cryptography. Together with CTAP (Client to Authenticator Protocol), it forms the FIDO2 standard. The private key never leaves the authenticator device -- the server only stores the public key.

WebAuthn Registration
Server sends challenge
->
Authenticator creates key pair
->
Public key + signed challenge sent to server

Authenticator Types

Platform Authenticator

Built into the device: Touch ID, Face ID, Windows Hello. Convenient for the user but tied to a specific device.

Roaming Authenticator

External hardware keys: YubiKey, Titan Key. Portable across devices, connected via USB, NFC, or Bluetooth.

Why Passwordless Wins
Immune to phishing (origin-bound credentials), credential stuffing, and server-side password breaches (server only stores public keys). Passkeys (discoverable credentials synced via cloud) make cross-device use seamless.
06 / Hardening

API Security, Access Control & Password Hashing

API Authentication Methods

MethodHow It WorksBest For
API KeysStatic secret passed in header or query paramIdentifying callers, rate limiting. Not true authn -- easily leaked.
mTLSBoth client and server present TLS certificatesService-to-service in zero-trust networks. Strong identity but complex PKI.
HMAC SigningRequest body + timestamp signed with shared secretWebhook verification, tamper-proof requests (e.g., AWS Signature V4).

Rate Limiting

Essential for API security. Common algorithms include token bucket (smooth bursts), sliding window (precise counts), and leaky bucket (constant drain). Typically enforced per API key, per IP, or per user. Return 429 Too Many Requests with a Retry-After header.

RBAC vs ABAC

ModelHow Decisions Are MadeTrade-offs
RBAC (Role-Based)User is assigned roles (admin, editor, viewer). Permissions are attached to roles.Simple to reason about. Can lead to role explosion in complex systems.
ABAC (Attribute-Based)Policies evaluate attributes of user, resource, action, and environment.Fine-grained and flexible. More complex to implement and audit.

Password Hashing

Never store passwords in plaintext or with fast hashes (MD5, SHA-256). Use purpose-built password hashing functions that are deliberately slow and memory-hard.

bcrypt

Adaptive cost factor, built-in salt, widely supported. Default cost 10-12. Battle-tested since 1999.

Argon2

Winner of the 2015 Password Hashing Competition. Configurable time, memory, and parallelism. Argon2id variant recommended (resists both side-channel and GPU attacks).

scrypt

Memory-hard function. Good alternative when Argon2 is unavailable. Used in some cryptocurrency proof-of-work schemes.

Common Mistakes
Using SHA-256 or MD5 for passwords (too fast, GPU-crackable). Forgetting to salt (enables rainbow tables). Setting bcrypt cost too low. Not enforcing rate limits on login endpoints.

Test Yourself

Score: 0 / 10
Question 01
What HTTP status code should be returned when a user is authenticated but lacks permission to access a resource?
403 Forbidden means the server knows who you are (authenticated) but you do not have permission (authorization failure). 401 means identity is unknown or unverified.
Question 02
A JWT consists of three parts. What are they?
A JWT is structured as header.payload.signature. The header declares the algorithm, the payload contains claims, and the signature ensures integrity.
Question 03
Why is HS256 less suitable than RS256 for distributed microservices?
HS256 uses a symmetric shared secret. Every service that needs to verify tokens must possess the same secret, increasing the attack surface. RS256 lets services verify with a public key while only the auth server holds the private key.
Question 04
What does PKCE protect against in the OAuth 2.0 Authorization Code flow?
PKCE (Proof Key for Code Exchange) binds the authorization code to the original client using a code_verifier/code_challenge pair, preventing attackers who intercept the code from exchanging it for tokens.
Question 05
Which OAuth 2.0 grant type is designed for machine-to-machine communication with no user interaction?
Client Credentials grant is for server-to-server communication where no user is involved. The client authenticates with its own ID and secret to get an access token directly.
Question 06
In OpenID Connect, what is the purpose of the ID Token?
The ID Token is a JWT consumed by the client application to learn who the user is. It contains identity claims like sub, email, and name. It should never be sent to APIs as a bearer token -- that is the access token's role.
Question 07
What makes WebAuthn resistant to phishing attacks?
WebAuthn credentials are origin-bound -- the authenticator includes the origin in the signed assertion. A phishing site on a different domain cannot obtain or replay the credential because the origin will not match.
Question 08
Why is SHA-256 unsuitable for password hashing?
SHA-256 is a general-purpose hash designed for speed. Attackers can compute billions of SHA-256 hashes per second on GPUs. Password hashing functions like bcrypt and Argon2 are deliberately slow and memory-hard to make brute-force attacks impractical.
Question 09
In SAML 2.0, what is the role of the Identity Provider (IdP)?
The Identity Provider (IdP) is responsible for authenticating the user and producing digitally signed SAML assertions that the Service Provider (SP) can trust to grant access.
Question 10
How does ABAC differ from RBAC?
ABAC (Attribute-Based Access Control) makes authorization decisions by evaluating policies against attributes of the user, the resource, the action, and the environment. RBAC assigns permissions to roles, which are then assigned to users. ABAC is more flexible but more complex.