Identity and Access Management
Identity and access management answers two questions that sound similar and are not: who are you (authentication) and what may you do (authorization). Collapsing them is the origin of a remarkable number of breaches â an application that authenticates correctly but never re-checks authorization on each object, a token that proves identity but grants far more than the task required. This lesson covers the factors and protocols behind authentication, the models behind authorization, and the governance that keeps both honest as an organization grows.
Authentication and authorization are separate decisions
Authentication establishes identity through something you know, have, are, or where you are. Authorization consults policy to decide whether that identity may perform this action on this resource right now. A valid session token proves the first; it says nothing about the second unless the application checks.
| Concept | Question | Example failure |
|---|---|---|
| Authentication (AuthN) | Who is making this request? | Password reuse after a credential dump |
| Authorization (AuthZ) | Is this request permitted? | Changing an order ID and reading another customer's order |
| Non-repudiation | Can the actor deny their action? | Missing audit trail tying actions to accounts |
| Federation | Which external IdP vouches for this user? | Trusting an unverified partner assertion |
Multi-factor authentication raises the cost of stolen credentials more than any other single control: a phished password is worthless without the second factor. The factors are commonly described as something you know (password, PIN), something you have (hardware token, phone), something you are (fingerprint, face), somewhere you are (network or geolocation context), and something you do (typing rhythm, interaction patterns). The first three are strong; location and behavior are useful signals but poor primary factors because they can be spoofed or legitimately vary.
Phishing-resistant factors deserve priority: FIDO2 security keys and platform authenticators bind the credential to the origin, so a convincing replica site receives nothing usable. Time-based one-time codes (TOTP) are a meaningful improvement over SMS but can still be relayed by a real-time proxy, which is why high-value accounts should graduate to hardware.
Time-based one-time codes in practice
TOTP works by both sides computing the same short code from a shared secret and the current time window, so it needs no server-side storage of codes and works offline.
import pyotp, qrcode, io, base64
# Enrolment: generate a secret, display it once as a QR code, never log it
secret = pyotp.random_base32()
totp = pyotp.TOTP(secret, interval=30, digest="sha256")
provisioning = pyotp.totp.provisioning_uri(
secret,
issuer_name="ChatWhole",
account_name="ana@company.example",
)
qr = qrcode.make(provisioning)
buf = io.BytesIO()
qr.save(buf, format="PNG")
print("qr bytes:", len(buf.getvalue()))
# Verification window: allow one step of drift for clock skew, never more
code = totp.now()
print("valid now:", totp.verify(code, valid_window=1))
print("valid later:", totp.verify(code, valid_window=0))
# Rate-limit failures server-side; codes are guesses by nature
attempts = {"count": 0}
def verify_login(submitted):
if attempts["count"] >= 5:
raise PermissionError("locked: too many attempts")
if totp.verify(submitted, valid_window=1):
attempts["count"] = 0
return True
attempts["count"] += 1
return False
Two implementation details decide whether this is a control or theater: a verification window of one step absorbs clock drift but ten steps would accept yesterday's codes, and no rate limit means a six-digit code is a small search space. Bind the factor to the session as well â an attacker who replays a valid code with their own session should still fail.
Passwords: hashing, storage and policy that works
Passwords remain the fallback factor everywhere, so their storage must assume the database will eventually leak. A general-purpose hash is too fast to be safe; a memory-hard function with a unique salt and a deliberately high cost makes each guess expensive for the attacker while remaining acceptable for the legitimate user.
import bcrypt, hmac, secrets
def hash_password(plaintext: str) -> bytes:
# bcrypt embeds its own salt; cost 12 is a sane starting point on modern hardware
return bcrypt.hashpw(plaintext.encode(), bcrypt.gensalt(rounds=12))
def check_password(plaintext: str, stored: bytes) -> bool:
# Constant-time comparison happens inside bcrypt; do not leak timing via manual checks
return bcrypt.checkpw(plaintext.encode(), stored)
stored = hash_password("correct-horse-battery-staple")
print("match:", check_password("correct-horse-battery-staple", stored))
print("wrong:", check_password("wrong-password", stored))
# Session identifiers must be unpredictable and revocable
session_id = secrets.token_urlsafe(32)
print("session id length:", len(session_id))
# Signing key for tokens: rotate it and keep the old one only for verification
signing_key = secrets.token_hex(32)
print("rotatable key:", hmac.new(signing_key.encode(), b"v1", "sha256").hexdigest()[:16])
Policy advice has shifted with evidence. Length beats composition rules; passphrases and a password manager beat forced rotation every 90 days, which reliably produces Winter2024! patterns. What matters is unique-per-account, long, stored correctly, checked against breach corpora, and protected by MFA â in that order of leverage.
RBAC, ABAC and the question of least privilege
Authorization models differ in what the decision reads. Role-based access control (RBAC) grants permissions through roles, which keeps administration simple and audit-friendly: a user is an editor, an editor may edit posts, done. Its weakness is explosion â the moment you need "editors in region EMEA except financial reports", roles multiply and overlap.
Attribute-based access control (ABAC) evaluates attributes of the subject, resource, action and environment instead: a policy might allow read access when the user's department equals the document's department and the device is managed and the time is within working hours. ABAC expresses fine-grained rules without a role per combination, at the cost of being harder to review â a policy engine with dozens of rules can grant access nobody intended.
# Role definitions stay small; every permission is explicit
roles:
viewer:
permissions: [report:read, dashboard:view]
analyst:
inherits: [viewer]
permissions: [dataset:read, model:run]
admin:
permissions: [user:create, user:disable, policy:write, audit:read]
requires: { mfa: true, approval: security }
# Attribute policy: the checks a role alone cannot express
policies:
- name: department-scoped-read
effect: allow
action: report:read
when:
- user.department == resource.department
- device.managed == true
- environment.time between 06:00 and 20:00
unless:
- resource.classification == "board-confidential"
# Separation of duties: no single identity may both create and approve a payment
constraints:
- deny_if: same_actor(user, resource.created_by) and action == payment:approve
Whichever model you choose, enforce checks server-side on every request, deny by default, and review the mapping between people and permissions on a schedule. Most organizations need both: roles for coarse administration, attributes for the exceptions that would otherwise breed shadow roles.
Single sign-on, SAML and OAuth
Federation moves authentication to an identity provider so one credential governs many applications. In a SAML web single sign-on flow, the service provider redirects the browser to the identity provider, the user authenticates there, and the identity provider returns a signed assertion to the service provider, which then establishes a local session. In OAuth 2.0, the focus is delegated authorization: a client receives a limited-scope access token rather than the user's password, and OpenID Connect layers identity on top of the same flow.
| Need | Protocol | What is exchanged | Watch out for |
|---|---|---|---|
| Web SSO to enterprise apps | SAML 2.0 | Signed XML assertion | Assertion replay, lax signature validation |
| Delegated API access | OAuth 2.0 / PKCE | Bearer or JWT access token | Scope creep, long-lived tokens |
| Identity for the app | OpenID Connect | ID token with claims | Missing nonce, weak audience checks |
| Service-to-service | mTLS or client credentials | Certificate or client assertion | Static secrets in config |
Security details are where these break: validate the assertion's signature, audience and audience expiry; use PKCE for public clients; keep access tokens short-lived with refresh rotation; check aud, iss and expiry on every JWT; and prefer authorization-code flow over implicit flow. SSO also concentrates risk â if the identity provider is down or compromised, every downstream application is too, so recovery paths and phishing-resistant factors at the IdP matter disproportionately.
Governance: access reviews that mean something
Access accumulates. People change teams, contractors finish projects, service accounts outlive their services, and permissions granted for a one-off migration are still there two years later. Governance is the machinery that removes what should no longer exist: joiner-mover-leaver automation, periodic certification campaigns, and reporting that shows who holds privileged access.
Certification campaigns fail when they are formatted as pages of green checkmarks for a manager to approve. Make them reviewable: group access by role and risk, highlight anything added since the last review, require an explicit decision for privileged grants, and revoke automatically for anyone who does not respond. Track the numbers â dormant privileged accounts, time-to-revoke after termination, percentage of access granted through roles rather than direct grants â because what gets measured gets cleaned.
Common Mistakes
Treating a successful login as authorization for everything after it
Fix: Re-check authorization on every request and every object, deriving the allowed set from the session rather than the UI.
Building a new role for every exception
Fix: Push fine-grained conditions into attribute policies and keep the role catalogue small and reviewable.
Collecting TOTP codes without rate limiting or session binding
Fix: Lock after repeated failures, limit the verification window, and bind the factor to the established session.
Storing passwords with a fast general-purpose hash
Fix: Use Argon2id, scrypt or bcrypt with per-user salts and a cost factor you benchmark.
Running access certifications that managers rubber-stamp
Fix: Show risk-grouped, delta-only reviews with automatic revocation for non-responses.
Best Practices
- Enforce SSO with phishing-resistant MFA at the identity provider â it is the highest-leverage control in the estate.
- Grant permissions through roles with short-lived elevation for privileged actions.
- Keep tokens short-lived, audience-checked and rotated; never accept an unsigned or unverified assertion.
- Automate joiner, mover and leaver flows so revocation does not depend on a ticket.
- Measure dormant accounts, direct grants and time-to-revoke quarterly.
Key Takeaways
- Authentication proves identity; authorization decides permission â most access breaches are failures of the second.
- MFA, especially hardware-backed and phishing-resistant, raises credential-stolen attack cost more than any other control.
- TOTP needs bounded verification windows and rate limiting, or a six-digit code is a small search space.
- RBAC is simple but multiplies roles; ABAC expresses context without new roles but is harder to audit â most estates need both.
- SAML, OAuth and OIDC solve different problems; signature, audience and expiry validation is where they break.
- Governance is what makes least privilege durable: automated joiner-mover-leaver and meaningful certification campaigns.