StackPractices
advanced By Mathias Paulenko

Complete Guide to Authentication Patterns

Implement production authentication: JWT, OAuth2, sessions, passkeys, MFA, SAML and OIDC SSO, RBAC vs ABAC, and secure token rotation with code.

Introduction

Authentication is the front door of every application, and it fails in boring ways: a refresh token that survives “log out everywhere”, a session store nobody can revoke, a JWT signed with the same secret on every service. The breaches that follow aren’t exotic — OWASP keeps broken authentication near the top of its lists year after year because the mistakes repeat.

This guide walks through the patterns you actually ship: JWT with refresh rotation, server-side sessions, OAuth2 Authorization Code, SAML and OIDC for SSO, passkeys (WebAuthn), MFA, and the authorization layer that sits behind all of them (RBAC vs ABAC). Every section has runnable Python — FastAPI + Redis because the patterns transfer to any stack — plus the trade-offs nobody mentions in the happy path. Where a sibling resource goes deeper (PKCE, SAML XML, password hashing), this guide links out instead of duplicating it.

Choosing an Authentication Pattern

Most authentication mistakes happen before any code: the team picks JWT because it’s trendy, then discovers revocation, or picks sessions and then needs cross-service calls. Decide by what you’re building, not by what’s fashionable:

What you are buildingRecommended patternWhy
Server-rendered web appSession cookiesInstant revocation, no token handling in the browser
SPA or mobile app + APIOAuth2 + PKCE, JWT access + rotating refreshStateless verification, theft detection on refresh
Microservices / API-to-APIJWT with RS256Services verify with the public key, no shared secret
Enterprise workforce SSOSAML or OIDC via the company IdPCentralized lifecycle, mandated by IT policy
Consumer passwordlessPasskeys (WebAuthn)Phishing-resistant, no shared secret to breach
Sensitive actions on top of any of theseMFA (TOTP, WebAuthn, backup codes)Limits damage when the primary factor leaks
Decision flow for choosing an authentication pattern: a server-rendered web app uses session cookies, an SPA or mobile app with an API uses OAuth2 with PKCE and JWT, microservices use JWT with RS256, enterprise SSO uses SAML or OIDC, and sensitive operations add MFA on top.

Two rules of thumb behind the diagram. First, JWT and sessions aren’t rivals — JWT wins on stateless verification across services, sessions win on revocation and simplicity inside one app. Second, whatever you pick for sign-in, authorization (RBAC/ABAC) and MFA are separate decisions layered on top.

JWT Authentication

A JSON Web Token (RFC 7519) is a signed claim set: the API verifies it locally without hitting a session store. That’s the whole point — and also the whole problem, because a valid signature on a stolen token keeps working until it expires. Keep access tokens short (5-15 minutes), pair them with rotating refresh tokens, and accept that real revocation needs a blocklist, which eats part of the stateless benefit.

Token Structure

JWT Structure: header.payload.signature

Header:  {"alg": "RS256", "typ": "JWT"}
Payload: {"sub": "user123", "email": "user@example.com", "role": "admin", "exp": 1735689600}
Signature: RSA-SHA256(header_b64 + "." + payload_b64, private_key)

Security rules:
  - Never put secrets in the payload: it is base64, not encryption
  - Always set exp; add iat and nbf for clock-skew safety
  - RS256 (asymmetric) over HS256 (symmetric) when more than one service verifies
  - Validate signature, exp, iss, and aud on every request
  - Browser clients: httpOnly cookies, never localStorage

The storage decision deserves emphasis. A token in localStorage is one XSS away from exfiltration; an httpOnly + Secure + SameSite cookie isn’t readable by JavaScript at all, and CSRF risk is what SameSite exists for.

JWT Implementation

import secrets
import jwt
from datetime import datetime, timedelta, timezone
from dataclasses import dataclass

class AuthError(Exception):
    pass

@dataclass
class JWTConfig:
    private_key: str
    public_key: str
    issuer: str = "https://auth.stackpractices.com"
    audience: str = "stackpractices-api"
    access_token_ttl: int = 900          # 15 minutes
    refresh_token_ttl: int = 86400 * 7   # 7 days

class JWTService:
    def __init__(self, config: JWTConfig):
        self.config = config

    def generate_access_token(self, user_id: str, claims: dict) -> str:
        now = datetime.now(timezone.utc)
        payload = {
            "sub": user_id,
            "iss": self.config.issuer,
            "aud": self.config.audience,
            "iat": now,
            "nbf": now,
            "exp": now + timedelta(seconds=self.config.access_token_ttl),
            "type": "access",
            **claims
        }
        return jwt.encode(payload, self.config.private_key, algorithm="RS256")

    def generate_refresh_token(self, user_id: str) -> str:
        now = datetime.now(timezone.utc)
        payload = {
            "sub": user_id,
            "iss": self.config.issuer,
            "aud": self.config.audience,
            "iat": now,
            "exp": now + timedelta(seconds=self.config.refresh_token_ttl),
            "type": "refresh",
            "jti": secrets.token_urlsafe(16)  # unique ID for rotation/revocation
        }
        return jwt.encode(payload, self.config.private_key, algorithm="RS256")

    def verify_token(self, token: str, expected_type: str = "access") -> dict:
        try:
            payload = jwt.decode(
                token,
                self.config.public_key,
                algorithms=["RS256"],
                issuer=self.config.issuer,
                audience=self.config.audience,
                options={"require": ["exp", "iss", "aud", "sub", "type"]}
            )
            if payload.get("type") != expected_type:
                raise AuthError(f"Expected {expected_type} token, got {payload.get('type')}")
            return payload
        except jwt.ExpiredSignatureError:
            raise AuthError("Token expired")
        except jwt.InvalidTokenError as e:
            raise AuthError(f"Invalid token: {e}")

# Usage
config = JWTConfig(
    private_key=open("private.pem").read(),
    public_key=open("public.pem").read()
)
jwt_service = JWTService(config)

access_token = jwt_service.generate_access_token("user123", {"role": "admin"})
refresh_token = jwt_service.generate_refresh_token("user123")
payload = jwt_service.verify_token(access_token)

Two details worth copying exactly: datetime.now(timezone.utc) instead of the deprecated utcnow(), and the type claim that stops a refresh token from being replayed as an access token. The require option forces the claims to exist, not just match when present.

Refresh Token Rotation

Long-lived refresh tokens are the credential attackers hunt for, so every refresh issues a new refresh token and revokes the old one. If a stolen token is used after rotation, the legitimate owner hits an “already used” error — that collision is your theft detector. This is the pattern RFC 6819 recommends for OAuth2 deployments.

class TokenRotationManager:
    def __init__(self, jwt_service: JWTService, redis_client):
        self.jwt = jwt_service
        self.redis = redis_client

    def refresh_tokens(self, refresh_token: str) -> dict:
        payload = self.jwt.verify_token(refresh_token, expected_type="refresh")
        jti = payload["jti"]
        user_id = payload["sub"]

        # Global revocation must be checked BEFORE the per-token check:
        # revoke_all_tokens() marks the user, not individual JTIs.
        if self.redis.get(f"revoked_user:{user_id}"):
            raise AuthError("All tokens for this user have been revoked")
        if self.redis.get(f"revoked:{jti}"):
            # Reused rotated token = probable theft. Fail closed.
            raise AuthError("Refresh token has been revoked")

        # Rotate: kill the old refresh token, issue a new pair
        self.redis.setex(f"revoked:{jti}", self.jwt.config.refresh_token_ttl, "1")
        return {
            "access_token": self.jwt.generate_access_token(user_id, {}),
            "refresh_token": self.jwt.generate_refresh_token(user_id),
            "expires_in": self.jwt.config.access_token_ttl
        }

    def revoke_all_tokens(self, user_id: str):
        """Logout everywhere: flag the user so every refresh token dies."""
        self.redis.setex(
            f"revoked_user:{user_id}",
            self.jwt.config.refresh_token_ttl,
            "1"
        )

    def logout(self, refresh_token: str):
        """Revoke a single refresh token."""
        payload = self.jwt.verify_token(refresh_token, expected_type="refresh")
        self.redis.setex(
            f"revoked:{payload['jti']}",
            self.jwt.config.refresh_token_ttl,
            "1"
        )

The revoked_user check is the part everyone forgets: flagging the user without reading the flag on refresh leaves “log out everywhere” as a button that does nothing. The deeper end-to-end implementation lives in Python JWT Refresh Token Rotation.

Session-Based Authentication

Sessions invert the JWT trade-off: the server keeps state in Redis, so revocation is a DEL away and nothing sensitive reaches the browser beyond an opaque ID. For a single server-rendered app this is still the simplest correct answer.

import secrets
from datetime import datetime, timezone
from fastapi import Request, Response

class SessionManager:
    def __init__(self, db, redis_client):
        self.db = db
        self.redis = redis_client
        self.session_ttl = 3600          # sliding window: 1 hour of inactivity
        self.absolute_ttl = 86400 * 14   # hard cap: 14 days regardless of activity
        self.cookie_name = "session_id"

    def create_session(self, response: Response, user_id: str) -> str:
        session_id = secrets.token_urlsafe(32)

        self.redis.hset(f"session:{session_id}", mapping={
            "user_id": user_id,
            "created_at": datetime.now(timezone.utc).isoformat(),
            "last_access": datetime.now(timezone.utc).isoformat()
        })
        self.redis.expire(f"session:{session_id}", self.absolute_ttl)
        # Index sessions per user — makes "destroy all" O(1) lookups, not a full SCAN
        self.redis.sadd(f"user_sessions:{user_id}", session_id)

        response.set_cookie(
            key=self.cookie_name,
            value=session_id,
            httponly=True,
            secure=True,
            samesite="strict",
            max_age=self.absolute_ttl,
            path="/"
        )
        return session_id

    def get_session(self, request: Request) -> dict | None:
        session_id = request.cookies.get(self.cookie_name)
        if not session_id:
            return None

        session_data = self.redis.hgetall(f"session:{session_id}")
        if not session_data:
            return None

        # Sliding renewal inside the absolute cap
        self.redis.hset(f"session:{session_id}", "last_access",
                        datetime.now(timezone.utc).isoformat())
        return session_data

    def destroy_session(self, request: Request, response: Response):
        session_id = request.cookies.get(self.cookie_name)
        if not session_id:
            return
        session_data = self.redis.hgetall(f"session:{session_id}")
        user_id = session_data.get("user_id")
        self.redis.delete(f"session:{session_id}")
        if user_id:
            self.redis.srem(f"user_sessions:{user_id}", session_id)
        response.delete_cookie(self.cookie_name, path="/")

    def destroy_all_sessions(self, user_id: str):
        """Kill every session for a user without scanning the whole keyspace."""
        for session_id in self.redis.smembers(f"user_sessions:{user_id}"):
            self.redis.delete(f"session:{session_id}")
        self.redis.delete(f"user_sessions:{user_id}")

Two production details the naive version misses. A sliding TTL alone means an active session never expires — the absolute_ttl cap bounds how long a hijacked session stays useful. And scan_iter("session:*") works for a demo but reads the whole keyspace under load; the user_sessions:{id} index turns “log out everywhere” into a set lookup.

OAuth2 Authorization Code Flow

OAuth2 (RFC 6749) is delegated authorization, not authentication by itself — the id_token/userinfo fetch is what turns it into a login. The Authorization Code flow keeps tokens off the browser URL; for public clients (SPAs, mobile) the client_secret can’t be kept secret, which is exactly why PKCE exists — see Implement OAuth 2.0 PKCE for Single-Page Applications for that variant.

import os
import secrets
import httpx
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import RedirectResponse
from starlette.middleware.sessions import SessionMiddleware

app = FastAPI()
# request.session only exists with SessionMiddleware installed
app.add_middleware(SessionMiddleware, secret_key=os.environ["SESSION_SECRET"])

class OAuth2Client:
    def __init__(self, config: dict):
        self.client_id = config["client_id"]
        self.client_secret = config["client_secret"]
        self.redirect_uri = config["redirect_uri"]
        self.auth_url = config["auth_url"]
        self.token_url = config["token_url"]
        self.userinfo_url = config["userinfo_url"]
        self.scopes = config["scopes"]

    def get_auth_url(self, state: str) -> str:
        params = {
            "client_id": self.client_id,
            "redirect_uri": self.redirect_uri,
            "response_type": "code",
            "scope": " ".join(self.scopes),
            "state": state
        }
        query = "&".join(f"{k}={v}" for k, v in params.items())
        return f"{self.auth_url}?{query}"

    async def exchange_code(self, code: str) -> dict:
        async with httpx.AsyncClient() as client:
            response = await client.post(self.token_url, data={
                "grant_type": "authorization_code",
                "client_id": self.client_id,
                "client_secret": self.client_secret,
                "redirect_uri": self.redirect_uri,
                "code": code
            })
            response.raise_for_status()
            return response.json()

    async def get_user_info(self, access_token: str) -> dict:
        async with httpx.AsyncClient() as client:
            response = await client.get(
                self.userinfo_url,
                headers={"Authorization": f"Bearer {access_token}"}
            )
            response.raise_for_status()
            return response.json()

# Google OAuth2 example — secrets come from env, never the codebase
google_oauth = OAuth2Client({
    "client_id": os.environ["GOOGLE_CLIENT_ID"],
    "client_secret": os.environ["GOOGLE_CLIENT_SECRET"],
    "redirect_uri": "https://stackpractices.com/auth/callback",
    "auth_url": "https://accounts.google.com/o/oauth2/v2/auth",
    "token_url": "https://oauth2.googleapis.com/token",
    "userinfo_url": "https://www.googleapis.com/oauth2/v2/userinfo",
    "scopes": ["openid", "email", "profile"]
})

@app.get("/auth/login")
async def login(request: Request):
    state = secrets.token_urlsafe(32)
    request.session["oauth_state"] = state
    return RedirectResponse(google_oauth.get_auth_url(state))

@app.get("/auth/callback")
async def callback(request: Request, response: Response, code: str, state: str):
    # The state check is the CSRF defense — never skip it
    if state != request.session.get("oauth_state"):
        raise HTTPException(400, "Invalid state")

    tokens = await google_oauth.exchange_code(code)
    user_info = await google_oauth.get_user_info(tokens["access_token"])

    # Hand off to your own session or JWT — db/redis are app-provided
    session = SessionManager(db, redis)
    session_id = session.create_session(response, user_info["id"])
    return RedirectResponse(f"/dashboard?session={session_id}")

SAML SSO

When the customer is an enterprise, “sign in with Google” stops being an option: their IT runs an Identity Provider (Okta, Entra ID, ADFS) and expects SAML 2.0. The model differs from OAuth2 in shape, not in spirit — instead of JSON tokens, your app (the Service Provider) receives a signed XML assertion after the user authenticates at the IdP.

Two flows exist. SP-initiated — the user hits your app, you redirect to the IdP with an AuthnRequest, the assertion comes back to your ACS endpoint. IdP-initiated — the user starts at the company portal and lands in your app already asserted; convenient but weaker against unsolicited-response attacks, so most SPs disable it or pin it down. The things that actually break SAML in production are boring: clock skew invalidating NotBefore/NotOnOrAfter, certificate rotation on the IdP side, and NameID formats that change between customers.

Implement it with a library (python3-saml, pysaml2, or ITfoxtec/Sustainsys in .NET) rather than parsing XML yourself — signature wrapping attacks are a real thing and hand-rolled SAML validation is how they get in. The full SP setup with metadata, ACS endpoint, and attribute mapping is covered in Implement SSO with SAML. Rule of thumb for new builds: OIDC if the IdP supports it, SAML when the enterprise customer already runs it.

Passkeys (WebAuthn)

Passkeys replace the shared secret with a key pair: the authenticator signs a challenge, your server verifies with the stored public key. There’s nothing to phish — the credential is bound to your origin — and nothing reusable to leak in a breach. The W3C WebAuthn spec defines the protocol; platform authenticators (Touch ID, Windows Hello, Android biometrics) cover the consumer case, and roaming keys (YubiKey) cover the paranoid one.

import json
from webauthn import (
    generate_registration_options, verify_registration_response,
    generate_authentication_options, verify_authentication_response
)

class PasskeyManager:
    def __init__(self, rp_id: str, rp_name: str, origin: str):
        self.rp_id = rp_id
        self.rp_name = rp_name
        self.origin = origin

    def generate_registration(self, user_id: str, username: str) -> dict:
        options = generate_registration_options(
            rp_id=self.rp_id,
            rp_name=self.rp_name,
            user_id=user_id.encode(),
            user_name=username,
            authenticator_selection={
                "authenticatorAttachment": "platform",
                "userVerification": "required"
            }
        )
        # Persist options.challenge server-side for the verify step
        return {"options": json.dumps(options.to_dict()),
                "challenge": options.challenge}

    def verify_registration(self, credential: dict, challenge: bytes) -> bool:
        try:
            verification = verify_registration_response(
                credential=credential,
                expected_challenge=challenge,
                expected_origin=self.origin,
                expected_rp_id=self.rp_id
            )
            # db.store_credential(user_id, verification.credential_id,
            #                     verification.credential_public_key)
            return True
        except Exception:
            return False

    def generate_authentication(self) -> dict:
        # No allow_credentials → discoverable credential (passkey)
        options = generate_authentication_options(
            rp_id=self.rp_id,
            user_verification="required"
        )
        return {"options": json.dumps(options.to_dict()),
                "challenge": options.challenge}

    def verify_authentication(self, credential: dict, challenge: bytes,
                              stored_public_key: bytes,
                              stored_sign_count: int) -> bool:
        try:
            verification = verify_authentication_response(
                credential=credential,
                expected_challenge=challenge,
                expected_origin=self.origin,
                expected_rp_id=self.rp_id,
                credential_public_key=stored_public_key,
                credential_current_sign_count=stored_sign_count
            )
            # verification.new_sign_count > stored → update; equal → possible clone
            return True
        except Exception:
            return False

The browser side is two calls: navigator.credentials.create() at registration and navigator.credentials.get() at sign-in. Deploy passkeys as the primary factor with a TOTP or recovery-code fallback during migration — forcing a flag-day switch is how adoption dies.

Multi-Factor Authentication (MFA)

A second factor caps the damage when the first leaks. The hierarchy, strongest first: WebAuthn/passkey → TOTP (RFC 6238, the pyotp below) → SMS codes. SMS is the weakest (SIM swap, SS7) but still better than a password alone — the OWASP MFA Cheat Sheet has the full trade-off matrix.

import hashlib
import secrets
import pyotp

class MFAService:
    def __init__(self, db, redis):
        self.db = db
        self.redis = redis

    def generate_totp_secret(self) -> str:
        return pyotp.random_base32()

    def get_totp_uri(self, secret: str, email: str,
                     issuer: str = "StackPractices") -> str:
        return pyotp.TOTP(secret).provisioning_uri(
            name=email, issuer_name=issuer
        )

    def verify_totp(self, secret: str, code: str) -> bool:
        # valid_window=1 tolerates one 30s step of clock drift
        return pyotp.TOTP(secret).verify(code, valid_window=1)

    def generate_backup_codes(self, user_id: str, count: int = 10) -> list:
        # Return codes once, store only hashes — they're passwords too
        codes = [secrets.token_hex(4).upper() for _ in range(count)]
        hashes = [hashlib.sha256(c.encode()).hexdigest() for c in codes]
        self.redis.sadd(f"backup_hashes:{user_id}", *hashes)
        return codes

    def verify_backup_code(self, user_id: str, code: str) -> bool:
        digest = hashlib.sha256(code.encode()).hexdigest()
        # SREM is atomic: returns 1 and consumes the code if present
        return self.redis.srem(f"backup_hashes:{user_id}", digest) == 1

    def send_sms_code(self, phone: str):
        code = f"{secrets.randbelow(1000000):06d}"
        self.redis.setex(f"sms_code:{phone}", 300, code)  # 5 min TTL
        # sms_service.send(phone, f"Your code: {code}") — never return it

    def verify_sms_code(self, phone: str, code: str) -> bool:
        stored = self.redis.get(f"sms_code:{phone}")
        if stored and stored.decode() == code:
            self.redis.delete(f"sms_code:{phone}")
            return True
        return False

# Login flow with a pending-MFA challenge between the two factors
class MFAAuthFlow:
    def __init__(self, mfa_service: MFAService, jwt_service: JWTService, redis):
        self.mfa = mfa_service
        self.jwt = jwt_service
        self.redis = redis

    def step1_verify_password(self, username: str, password: str) -> dict:
        user = verify_credentials(username, password)  # app-provided
        if not user:
            raise AuthError("Invalid credentials")

        if user.mfa_enabled:
            # Issue a short-lived challenge, NOT a token
            challenge = secrets.token_urlsafe(32)
            self.redis.setex(f"mfa_challenge:{challenge}", 300, user.id)
            return {"requires_mfa": True, "challenge": challenge,
                    "methods": ["totp", "sms", "backup_code"]}

        return self._generate_tokens(user.id)

    def step2_verify_mfa(self, challenge: str, method: str, code: str) -> dict:
        user_id = self.redis.get(f"mfa_challenge:{challenge}")
        if not user_id:
            raise AuthError("Invalid or expired challenge")

        user = get_user(user_id.decode())  # app-provided
        ok = {
            "totp": lambda: self.mfa.verify_totp(user.totp_secret, code),
            "sms": lambda: self.mfa.verify_sms_code(user.phone, code),
            "backup_code": lambda: self.mfa.verify_backup_code(user.id, code),
        }.get(method, lambda: False)()
        if not ok:
            raise AuthError(f"Invalid {method} code")

        self.redis.delete(f"mfa_challenge:{challenge}")
        return self._generate_tokens(user.id)

    def _generate_tokens(self, user_id: str) -> dict:
        return {
            "requires_mfa": False,
            "access_token": self.jwt.generate_access_token(user_id, {}),
            "refresh_token": self.jwt.generate_refresh_token(user_id),
            "expires_in": self.jwt.config.access_token_ttl
        }

The pattern that matters: between password and MFA there’s a pending state — the 5-minute mfa_challenge — so a correct password never produces a usable token on its own. Backup codes live hashed, for the same reason passwords do.

Password Storage

If passkeys are the destination, passwords are still the road — most systems keep them as primary or fallback. Store them with a memory-hard KDF: Argon2id is the current OWASP recommendation, bcrypt is the acceptable legacy. Never SHA-256, never MD5, never “salted fast hash” — those fold to GPU cracking in hours. Parameters, pepper handling, and migration code (re-hash on login) are in Hash Passwords with Argon2. This is also where the secrets management guide earns its place: peppers and keys don’t belong in the repository.

Rate Limiting and Brute-Force Protection

Every endpoint above — /login, /auth/callback, TOTP verify, backup-code verify — is a guessing oracle until you throttle it. The practical shape: limit attempts per account (5-10 failures → exponential backoff or temporary lock), limit per IP (to slow credential stuffing across many accounts), and return identical “invalid credentials” responses for unknown users and wrong passwords so the endpoint can’t be used to enumerate accounts. TOTP and backup-code verification need the same treatment — a 6-digit code brute-forces in under a minute without a counter. For the implementation patterns, see the rate limiting recipe and the API rate limiting guide.

RBAC and ABAC

Authentication says who you are; authorization says what you may touch. RBAC maps users to roles and roles to permissions — simple, auditable, and enough for most apps. ABAC evaluates attributes (subject, resource, action, environment) so you can write “editors edit their own articles”, which RBAC cannot express. Start with RBAC; reach for ABAC when the permission matrix stops fitting in a table.

from enum import Enum

class Permission(Enum):
    READ = "read"
    WRITE = "write"
    DELETE = "delete"
    ADMIN = "admin"

# RBAC: Role-Based Access Control
ROLE_PERMISSIONS = {
    "viewer": {Permission.READ},
    "editor": {Permission.READ, Permission.WRITE},
    "admin": {Permission.READ, Permission.WRITE, Permission.DELETE, Permission.ADMIN},
}

def check_rbac(user_role: str, required_permission: Permission) -> bool:
    return required_permission in ROLE_PERMISSIONS.get(user_role, set())

# ABAC: Attribute-Based Access Control
class ABACEvaluator:
    def __init__(self):
        self.policies = []

    def add_policy(self, policy: dict):
        self.policies.append(policy)

    def evaluate(self, subject: dict, resource: dict, action: str) -> bool:
        for policy in self.policies:
            if self._match(policy, subject, resource, action):
                return policy["effect"] == "allow"
        return False  # default deny

    def _resolve(self, expected, subject: dict):
        """Resolve placeholders like '$subject.id' against the real subject."""
        if isinstance(expected, str) and expected.startswith("$subject."):
            return subject.get(expected[len("$subject."):])
        return expected

    def _match(self, policy: dict, subject: dict,
               resource: dict, action: str) -> bool:
        if action not in policy.get("actions", []):
            return False
        for key, value in policy.get("subject", {}).items():
            if subject.get(key) != self._resolve(value, subject):
                return False
        for key, value in policy.get("resource", {}).items():
            if resource.get(key) != self._resolve(value, subject):
                return False
        return True

# Usage
abac = ABACEvaluator()
abac.add_policy({
    "effect": "allow",
    "actions": ["read", "write"],
    "subject": {"role": "editor"},
    "resource": {"type": "article", "owner": "$subject.id"}
})
abac.add_policy({
    "effect": "allow",
    "actions": ["read", "write", "delete"],
    "subject": {"role": "admin"},
    "resource": {"type": "article"}
})

user = {"id": "user123", "role": "editor"}
article = {"type": "article", "owner": "user123"}
can_edit = abac.evaluate(user, article, "write")  # True — editor owns the article

The _resolve hook is the difference between a toy and a policy engine: "$subject.id" binds the resource attribute to the caller’s attributes, which is the entire point of ABAC.

SSO with OpenID Connect

OIDC is OAuth2 plus an identity layer: the id_token is a JWT your app verifies locally, and nonce binds it to the request that started the flow (anti-replay). Verify it against the provider’s JWKS — PyJWT ships PyJWKClient for this; python-jose is unmaintained and shouldn’t be in new code.

import httpx
import jwt
from jwt import PyJWKClient

class OIDCProvider:
    def __init__(self, config: dict):
        self.config = config
        # PyJWKClient caches keys and refetches on kid rotation
        self.jwks_client = PyJWKClient(config["jwks_uri"])

    @staticmethod
    def discover_jwks_uri(issuer: str) -> str:
        # {issuer}/.well-known/openid-configuration → jwks_uri
        resp = httpx.get(f"{issuer}/.well-known/openid-configuration")
        resp.raise_for_status()
        return resp.json()["jwks_uri"]

    def get_authorization_url(self, state: str, nonce: str) -> str:
        params = {
            "client_id": self.config["client_id"],
            "redirect_uri": self.config["redirect_uri"],
            "response_type": "code",
            "scope": "openid profile email",
            "state": state,
            "nonce": nonce
        }
        query = "&".join(f"{k}={v}" for k, v in params.items())
        return f"{self.config['auth_url']}?{query}"

    async def exchange_code(self, code: str) -> dict:
        async with httpx.AsyncClient() as client:
            response = await client.post(self.config["token_url"], data={
                "grant_type": "authorization_code",
                "client_id": self.client_id,
                "client_secret": self.client_secret,
                "redirect_uri": self.config["redirect_uri"],
                "code": code
            })
            response.raise_for_status()
            return response.json()

    def verify_id_token(self, id_token: str, nonce: str) -> dict:
        signing_key = self.jwks_client.get_signing_key_from_jwt(id_token)
        decoded = jwt.decode(
            id_token,
            signing_key.key,
            algorithms=["RS256"],
            audience=self.config["client_id"],
            issuer=self.config["issuer"]
        )
        # Nonce ties the token to this specific auth request
        if decoded.get("nonce") != nonce:
            raise AuthError("Nonce mismatch")
        return decoded

For the deeper production walkthrough — token endpoint hardening, at_hash validation, federation — see OAuth2 and OIDC in Production.

Best Practices

  1. Short access tokens, rotating refresh tokens. Fifteen minutes of access-token exposure beats seven days; rotation turns refresh-token theft into a detection signal instead of a silent breach.
  2. httpOnly + Secure + SameSite cookies for browser tokens. localStorage is XSS-readable by design; cookies with the right flags aren’t.
  3. Default deny everywhere. Missing permission, missing policy, missing claim — all must fail closed. “Allow unless matched” is how IDORs are born.
  4. Verify before you trust. Signature, exp, iss, aud, nonce, type — every claim, every request. The one check you skip is the one attackers test first.
  5. Fail identically for unknown users and bad passwords. Different error messages turn your login into an account-enumeration API.
  6. Bound credential lifetimes. Sliding session TTLs need an absolute cap; MFA challenges need a 5-minute expiry; backup codes need hashing.

Common Mistakes

  • “Log out everywhere” that revokes nothing. Flagging the user without checking the flag on refresh leaves every token alive — the classic bug in the rotation code above.
  • JWT in localStorage. Any XSS in your dependency tree reads it and walks out. Cookie or nothing for browser apps.
  • Skipping the state/nonce check. It’s the only thing standing between your OAuth callback and a login-CSRF attack.
  • Symmetric secrets at scale. HS256 means every verifying service holds the signing key — one leak and they are all forging tokens. RS256 splits sign and verify.
  • Unthrottled verification endpoints. TOTP codes and backup codes are small keyspaces; without a counter they are brute-forceable in minutes.
  • Hand-rolled SAML. XML signature validation is famously subtle; use a maintained library and don’t “simplify” the checks.

See Also

Frequently Asked Questions

Should I use JWT or session-based authentication?

JWT for stateless APIs and microservices where a session store is the bottleneck; sessions for server-rendered apps where instant revocation matters. One caveat worth repeating: JWT revocation requires a blocklist, which quietly reintroduces the state you were avoiding. For SPAs hitting an API, the standard shape is short-lived access JWT + rotating refresh.

What is refresh token rotation and why is it important?

Each refresh issues a new refresh token and retires the old one. When a stolen token gets used after its legitimate owner already rotated it, you see the collision and can nuke the family. Keep the old JTI in a revocation list and add a short reuse window for genuine race conditions.

Are passkeys better than passwords?

For phishing resistance, yes — the credential is bound to the origin, there's no shared secret to breach, and the user has nothing to remember or reuse. The honest cost is ecosystem maturity: account recovery across lost devices is the hard part. Ship passkeys as primary with a TOTP or backup-code fallback.

How do I implement MFA without hurting UX?

Make it risk-based instead of universal: prompt on new devices, new IPs, or sensitive actions, not every login. A passkey prompt is faster than typing a TOTP code, and a 30-day "remember this device" cookie covers the rest. Always issue backup codes — locked-out users with a lost phone are a support problem you created.

What is the difference between RBAC and ABAC?

RBAC assigns permissions to roles and is the right default: easy to audit, easy to explain. ABAC evaluates attributes, so it can express "editors edit their own articles" — the thing RBAC structurally cannot say. Most systems end up hybrid: RBAC for coarse gates, ABAC for ownership rules.

How do I implement secure logout?

JWT: push the token's JTI into a revocation list with a TTL equal to its remaining life. Sessions: delete the server-side record and expire the cookie. For "log out everywhere", flag the user — and actually check that flag on refresh, which is the step most implementations miss. SameSite=Strict on the cookie closes the logout-CSRF gap.