Zero Labs
Industry News / AI

Every Developer Gets Auth Wrong — Until They Understand This

Source · Towards AI By TheProdSDE

From the publisher’s feed, collected in the ZeroLabs newsroom.

You’ve been building login screens. You haven’t been building security. There’s a difference — and it’s costing teams millions in breaches, compliance failures, and re-architecture nightmares. This article fixes that.Reading time: ~22 minutesLevel: Mid to Senior Engineers, Architects, Tech LeadsTags: Authentication Authorization Okta Keycloak OAuth2 OpenID Connect JWT Security Web DevelopmentThe Problem Nobody Talks AboutYou’ve written if (user.isLoggedIn()) a hundred times. You've integrated a "Sign in with Google" button in an afternoon. You've stored a JWT in localStorage and called it a day.And somewhere, a security engineer just cringed — and here’s the part most tutorials skip: that localStorage decision alone is enough to get every token your users own stolen via a single XSS vulnerability. JavaScript running on your page — whether yours or from a compromised npm package — can read localStorage freely. An HttpOnly cookie cannot be touched by JavaScript at all. That one architectural choice is the difference between a quiet Tuesday and a breach notification email.Modern authentication and authorization is not a feature. It’s an entire discipline. The difference between thinkingyou’ve secured your app and actually securing it is exactly where billion-dollar breaches are born. The October 2023 Okta breach — where attackers compromised the support case management system and accessed files belonging to all Okta customers — the countless “we stored passwords in plaintext” confessions on HackerNews, the Auth0 vulnerabilities: they all trace back to the same root cause. Developers treating auth as a solved, trivial problem.It isn’t.This is Part 1 of a two-part series:Part 1 (this article): AuthN vs AuthZ, protocols, token types, every OAuth 2.0 flow with real HTTP request/response, and a deep-dive comparison of Okta vs Keycloak.Part 2 (upcoming): Fine-grained authorization, OPA, policy engines, Casbin, Cedar, SpiceDB, and how to stop botnets at the authorization layer.Let’s build the mental model that actually sticks.Part 1 — AuthN vs AuthZ: The Confusion That Breaks SystemsThese two words are used interchangeably every day. They should never be.Authentication (AuthN) — Who Are You?Authentication is the process of verifying an identity. It answers one question: “Is this entity who they claim to be?”Think of it like a passport check at an airport. The officer doesn’t care where you’re going or what you’re allowed to do there. They only care whether your face matches the photo and the document is real.Examples:Entering a username and passwordScanning your fingerprintCompleting an MFA promptPresenting a client certificateAuthorization (AuthZ) — What Are You Allowed to Do?Authorization happens after authentication. It answers: “Given that I know who you are — what are you permitted to do?”Back at the airport: once you’ve passed passport control, your boarding pass is your authorization. It tells security which gate, which seat, which class. Your identity was verified at passport control. Your permissions are checked at the gate.The Golden Rule: You cannot authorize someone you haven’t authenticated. But you absolutely can authenticate someone and still deny them access.Why the Confusion Is DangerousWhen developers conflate the two, they build systems where:A valid JWT means “this user can do anything” — with no authZ checks whatsoeverRole checks happen only in the UI, not the API — client-side authorization is not authorization“Admin” is a boolean flag, not a permission model❌ Wrong Mental Model: Login → "Authenticated" → Full Access✅ Correct Mental Model: Login → "Authenticated (Identity Confirmed)" → Authorization Check → Scoped AccessThat gap between the two models is where most security incidents live.Part 2 — The Building Blocks: Protocols, Standards & Token TypesBefore we touch Okta or Keycloak, you need to own these concepts cold.OAuth 2.0 — The Authorization FrameworkOAuth 2.0 is not an authentication protocol. Say it again. OAuth 2.0 is not an authentication protocol.It is a delegation framework — a standard that lets users grant third-party applications limited access to their resources without giving those apps their password.When you click “Connect your Google Calendar to Notion,” that’s OAuth 2.0 in action. Notion never gets your Google password. Google issues Notion an access token with the specific scope calendar.readonly. That's delegation.Core OAuth 2.0 Roles:OpenID Connect (OIDC) — Identity on Top of OAuth 2.0If OAuth 2.0 is the car, OIDC is the driver’s license in the glove compartment.OIDC is an identity layer built on top of OAuth 2.0. It adds the concept of an ID Token — a JWT that contains claims about the authenticated user (who they are, not what they can access).OAuth 2.0 → "Here's a token to access the calendar"OIDC → "Here's a token to access the calendar, AND here's who the user is"Most modern auth flows (Okta, Keycloak, Auth0, Cognito) implement OIDC over OAuth 2.0.SAML 2.0 — The Enterprise VeteranSecurity Assertion Markup Language 2.0 is an XML-based standard for SSO. It predates OAuth and is still dominant in enterprise environments — especially for integrating with legacy systems, Microsoft Active Directory, and government applications.Verbose XML format (compared to JSON-based JWT)Designed specifically for web browser SSOWidely supported by enterprise identity providers (Okta supports SAML extensively)Keycloak supports SAML as both an SP and an IdPIf you’re integrating with enterprise customers’ corporate identity systems, you will encounter SAML.JWT — The Token Format You Actually UseJSON Web Token (JWT) is not a protocol. It’s a token format — a compact, self-contained way to transmit claims between parties as a JSON object, digitally signed.A JWT has three base64url-encoded parts separated by dots:eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJ1c2VyXzEyMyIsImVtYWlsIjoidXNlckBleGFtcGxlLmNvbSIsInJvbGUiOiJhZG1pbiIsImV4cCI6MTcxNTAwMDAwMH0.SIGNATUREDecoded:json// Header{ "alg": "RS256", "typ": "JWT"}// Payload (Claims){ "sub": "user_123", "email": "user@example.com", "role": "admin", "iss": "https://auth.yourapp.com", "aud": "api.yourapp.com", "iat": 1714000000, "exp": 1715000000}// Signature: RS256(base64url(header) + "." + base64url(payload), privateKey)Critical JWT Claims:The Three Token TypesThis is where most tutorials get sloppy. There are three distinct tokens in a standard OIDC flow, and they serve entirely different purposes:⚠️ Common mistake: Sending the ID Token to your API as a Bearer token. The ID Token is for your client to know who is logged in. The Access Token is what your API validates. Mixing these up is an extremely common junior mistake that creates real security gaps.Part 3 — OAuth 2.0 Flows: With Real HTTP Requests & ResponsesThis is the section developers bookmark. Every flow, every HTTP call, every header.Flow 1: Authorization Code FlowThe most secure, most recommended flow for server-side and modern web apps. Uses a short-lived authorization code that is exchanged for tokens server-side, keeping tokens out of the browser URL entirely.Step-by-step HTTP:① Authorization Request (Browser → Authorization Server)httpGET /authorize HTTP/1.1Host: auth.yourapp.com?response_type=code&client_id=client_abc123&redirect_uri=https%3A%2F%2Fapp.com%2Fcallback&scope=openid%20profile%20email%20read%3Areports&state=a8f3bc92e1d74f&nonce=k2j9ms02kdTwo parameters worth understanding because they’re easy to copy-paste blindly:state — A random value your client generates. The authorization server echoes it back in the redirect. Your app must verify it matches before proceeding. This is your CSRF protection for the auth flow.nonce — A random value embedded in the ID Token by the server. Your client validates it matches what was sent. This prevents replay attacks — where a stolen ID Token is reused in a different session.② Authorization Server Redirects Back with CodehttpHTTP/1.1 302 FoundLocation: https://app.com/callback ?code=SplxlOBeZQQYbYS6WxSbIA &state=a8f3bc92e1d74f③ Token Exchange (App Server → Authorization Server)httpPOST /token HTTP/1.1Host: auth.yourapp.comContent-Type: application/x-www-form-urlencodedAuthorization: Basic Y2xpZW50X2FiYzEyMzpzZWNyZXQ=grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA&redirect_uri=https%3A%2F%2Fapp.com%2Fcallback&client_id=client_abc123④ Token ResponsehttpHTTP/1.1 200 OKContent-Type: application/jsonCache-Control: no-store{ "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "tGzv3JOkF0XG5Qx2TlKWIA", "id_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...", "scope": "openid profile email read:reports"}⑤ API Call with Access TokenhttpGET /api/reports HTTP/1.1Host: api.yourapp.comAuthorization: Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...Flow 2: Authorization Code + PKCEProof Key for Code Exchange (PKCE) — pronounced “pixie” by most, “pick-see” by others, argued about endlessly at conferences — is the mandatory extension for public clients (SPAs, mobile apps) that cannot securely store a client secret.The idea: before starting the flow, the client generates a random code_verifier, hashes it to create a code_challenge, and sends the challenge upfront. When exchanging the code, it proves it knows the verifier. This prevents authorization code interception attacks — where an attacker intercepts the redirect and tries to exchange the code themselves.Authorization Request (with PKCE)httpGET /authorize HTTP/1.1Host: auth.yourapp.com?response_type=code&client_id=spa_client_456&redirect_uri=https%3A%2F%2Fspa.yourapp.com%2Fcallback&scope=openid%20profile&state=xyz987&code_challenge=E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM&code_challenge_method=S256Token Exchange (with PKCE — no client_secret)httpPOST /token HTTP/1.1Host: auth.yourapp.comContent-Type: application/x-www-form-urlencodedgrant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA&redirect_uri=https%3A%2F%2Fspa.yourapp.com%2Fcallback&client_id=spa_client_456&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXkNote: No client_secret here. The PKCE verifier is the proof of authenticity. An attacker who intercepts the code gains nothing — they don't have the verifier.Flow 3: Client Credentials Flow (Machine-to-Machine)No user involved. Used for service-to-service communication — a backend microservice calling another microservice, a cron job hitting an API, a CI/CD pipeline authenticating.RequesthttpPOST /token HTTP/1.1Host: auth.yourapp.comContent-Type: application/x-www-form-urlencodedgrant_type=client_credentials&client_id=service_account_pipeline&client_secret=s3rv!ceS3cr3t&scope=internal:read%20internal:writeResponsehttpHTTP/1.1 200 OKContent-Type: application/json{ "access_token": "eyJhbGciOiJSUzI1NiJ9...", "token_type": "Bearer", "expires_in": 3600, "scope": "internal:read internal:write"}Note: No refresh_token and no id_token — there's no user identity here. The service simply re-authenticates when the token expires.Flow 4: Refresh Token FlowAccess tokens are short-lived by design. The Refresh Token flow lets a client get a new access token without making the user log in again.Refresh Token RequesthttpPOST /token HTTP/1.1Host: auth.yourapp.comContent-Type: application/x-www-form-urlencodedAuthorization: Basic Y2xpZW50X2FiYzEyMzpzZWNyZXQ=grant_type=refresh_token&refresh_token=tGzv3JOkF0XG5Qx2TlKWIAResponsehttpHTTP/1.1 200 OK{ "access_token": "eyJhbGciOiJSUzI1NiJ9.NEW_TOKEN...", "token_type": "Bearer", "expires_in": 3600, "refresh_token": "NEW_tGzv3JOkF0XG5Qx2NEW"}Refresh token rotation: Best practice is for the server to issue a new refresh token on each use and invalidate the old one. This limits the blast radius if a refresh token is stolen — the attacker’s copy becomes invalid the moment the legitimate client uses theirs.Flow 5: Device Authorization GrantOften overlooked, increasingly important. This flow is for input-constrained devices — Apple TV, smart TVs, CLI tools, IoT devices — where opening a browser and typing a URL isn’t practical.How It WorksDevice requests a device_code and a short user_code from the auth serverDevice displays: “Go to example.com/activate and enter: WDJB-MJHT”User completes auth on their phone or laptop (full browser experience)Device polls the token endpoint until auth completeshttpPOST /device/code HTTP/1.1Host: auth.yourapp.comContent-Type: application/x-www-form-urlencodedclient_id=device_client_789&scope=openid profile---HTTP/1.1 200 OK{ "device_code": "GmRhmhcxhwAzkoEqiMEg_DnyEysNkuNhszIySk9eS", "user_code": "WDJB-MJHT", "verification_uri": "https://auth.yourapp.com/activate", "expires_in": 900, "interval": 5}If you build anything that needs to authenticate from a terminal, a TV, or an embedded device, this is your flow.Flow 6: The Implicit Flow — Know It to Avoid ItThe Implicit Flow was OAuth’s original answer for SPAs. Tokens were returned directly in the URL fragment after the redirect, skipping the token exchange step entirely.It is deprecated. Do not use it.OAuth 2.1 formally removes it. The combination of Authorization Code + PKCE achieves the same goal (token access for public clients) without exposing tokens in browser history, server logs, and referrer headers.You’ll still encounter it in legacy codebases — now you know why it smells.Flow 7: Token Introspection & UserInfoTwo supplementary calls you need in your toolkit.Token Introspection — lets a resource server verify an opaque token (or validate a JWT with the authorization server):httpPOST /introspect HTTP/1.1Host: auth.yourapp.comContent-Type: application/x-www-form-urlencodedAuthorization: Basic token=eyJhbGciOiJSUzI1NiJ9...&token_type_hint=access_token---HTTP/1.1 200 OK{ "active": true, "sub": "user_123", "scope": "read:reports", "client_id": "client_abc123", "exp": 1715000000, "iat": 1714996400}UserInfo Endpoint — retrieve user profile claims using an OIDC access token:httpGET /userinfo HTTP/1.1Host: auth.yourapp.comAuthorization: Bearer eyJhbGciOiJSUzI1NiJ9...---HTTP/1.1 200 OK{ "sub": "user_123", "name": "Jane Doe", "email": "jane@example.com", "email_verified": true, "picture": "https://cdn.example.com/avatar.jpg"}The Complete Auth Flow — End to EndHere’s how all the pieces connect in a full Authorization Code + PKCE flow for a typical SPA:Part 4 — SSO, Sessions & MFASingle Sign-On (SSO)SSO lets users authenticate once and access multiple applications without re-entering credentials. The identity provider (Okta, Keycloak, etc.) becomes the single source of truth for identity across all connected apps.The flow:User logs into the IdP (e.g., sso.company.com)IdP creates a session and issues a session cookieUser navigates to App A — App A redirects to IdP, IdP sees the session, redirects back with a token. No login prompt.User navigates to App B — same thing. One login, access everywhere.SSO also means one logout to rule them all. A proper SSO implementation propagates logout to all connected apps (this is called SLO — Single Logout), so terminating an employee’s account in the IdP immediately revokes access to Slack, GitHub, Salesforce, and every other integrated app simultaneously.MFA / 2FAMulti-Factor Authentication layers additional verification on top of password, requiring proof from at least two of these three categories:On SMS OTP: It works, but it’s the weakest “something you have” factor. SIM-swapping attacks — where an attacker convinces a carrier to transfer your number to their SIM — are a real, documented threat vector. For any application handling sensitive data, push TOTP apps (Google Authenticator, Authy) or hardware keys (FIDO2/WebAuthn) instead.Adaptive MFA (used by Okta and others) is smarter — it evaluates risk signals before deciding whether to challenge. New device? Unusual country? 3 AM login? Challenge. Recognized device, normal location, normal time? Let them through silently. Same security outcome, dramatically less friction for legitimate users.Part 5 — RBAC vs ABACRole-Based Access Control (RBAC)Permissions are assigned to roles, and roles are assigned to users.User → Role → Permissionsjane → admin → [create, read, update, delete]bob → viewer → [read]✅ Strengths: Simple to implement and reason about. Easy to audit. Widely understood.❌ Weaknesses:Role explosion — as organizations grow, you end up creating a new role for every edge case. Imagine 50 departments, each needing 10 permission variations: that’s 500 roles to manage, document, and audit. RBAC doesn’t scale gracefully to complex organizations.Lacks contextual flexibility — the role says what you can do, but not when, from where, or under what conditions.Attribute-Based Access Control (ABAC)Access decisions are made based on attributes of the user, resource, and environment, evaluated against policies.ALLOW if: user.department == "finance" AND resource.classification == "internal" AND environment.time BETWEEN "09:00" AND "18:00" AND user.clearanceLevel >= resource.requiredClearanceThis policy does in four lines what would require dozens of RBAC roles — and it handles cases RBAC can’t express at all, like time-of-day restrictions or dynamic clearance comparisons.✅ Strengths: Extremely flexible. Context-aware (time, location, device, resource sensitivity). Scales to complex enterprises.❌ Weaknesses: Complex to implement and debug. Policy sprawl if not governed well. Harder to onboard new engineers to quickly.Part 2 of this series goes deep on ABAC engines, OPA (Open Policy Agent), and policy-as-code — including how to enforce these policies at scale without making your authorization logic a maintenance nightmare.Part 6 — Okta: The Cloud-Native Identity PlatformWhat Is Okta?Okta is a cloud-based Identity-as-a-Service (IDaaS) platform. You don’t install or manage anything — Okta handles the infrastructure, the scaling, the uptime SLAs, and the security patching. You configure it via a dashboard and APIs.Core Okta Key FeaturesUniversal Directory — A centralized, cloud-hosted user store that syncs with Active Directory, LDAP, HR systems (Workday, BambooHR), and custom sources via SCIM. One place that knows who everyone is, everywhere.Adaptive MFA — Risk-based authentication. Okta evaluates signals (new device, unusual location, time of day, IP reputation) and challenges only when risk is elevated. Low-risk = frictionless login. High-risk = challenge. You configure the thresholds.Application Integration Network — 7,000+ pre-built integrations with SaaS apps (Salesforce, Slack, AWS, GitHub, Jira). Setting up SSO for Salesforce takes under 10 minutes. This is genuinely Okta’s superpower for enterprise IT teams.Okta Workflows — A no-code automation platform for identity operations. Examples:Auto-deprovision user accounts when HR marks an employee as terminatedAdd user to Slack channel when added to a specific Okta groupAlert security when an admin role is assignedCustom Authorization Servers — Issue scoped JWT access tokens for your own APIs. Define custom claims, scopes, and access policies. This is what you use when you want Okta to be the token issuer for your own microservices, not just for SSO into third-party apps.Okta’s Pricing ModelOkta charges per Monthly Active User (MAU):Workforce Identity: Starts ~$2/user/month (Enterprise SSO)Customer Identity (CIAM): Tiered by MAU — free tier available up to 100 MAUEnterprise MFA, Lifecycle Management, and Workflows are add-onsThe hidden cost: For a startup with 50,000 users doing social login, Okta CIAM can quickly reach $1,500–$5,000+/month depending on features needed. Do the math before you commit — and factor in that the free tier disappears the moment you go to production scale.Part 7 — Keycloak: The Open-Source Identity PowerhouseWhat Is Keycloak?Keycloak is a CNCF incubating project (accepted April 2023), open-source Identity and Access Management (IAM) solution maintained by Red Hat. You deploy it yourself — on Kubernetes, Docker, bare metal, or cloud VMs. You own every bit of the data and configuration.Core Keycloak ConceptsRealms — The top-level isolation boundary. Each realm is its own universe: its own users, clients, roles, and identity providers. A single Keycloak instance can host dozens of realms, making it ideal for multi-tenant SaaS platforms where each customer gets an isolated identity namespace.Clients — Applications registered within a realm. Each client has its own client ID, secret, allowed redirect URIs, and token settings. A realm might have clients for your web app, mobile app, backend API, and internal CLI tool.Identity Brokering — Keycloak can act as a broker to external identity providers. Your users can log in with Google, GitHub, LDAP, Active Directory, or another SAML provider — and Keycloak normalizes all of it into a single identity within the realm. Your application only talks to Keycloak.User Federation — Rather than migrating users into Keycloak’s local database, you can point Keycloak at an existing LDAP or Active Directory and it reads directly from there. Zero user migration required.Keycloak’s Pricing ModelFree. Fully open-source under the Apache 2.0 license. But “free” means you pay in:Infrastructure: You need to run it. On Kubernetes, a production-grade Keycloak setup with HA and a clustered database is real infrastructure to manage.Ops overhead: Upgrades, patching, performance tuning, and backup/restore are your responsibility.Engineering time: Initial setup, customization, and ongoing maintenance require familiarity with the platform.Red Hat also offers Red Hat Build of Keycloak — an enterprise-supported, hardened version of Keycloak — if you want open-source economics with commercial support SLAs.Part 8 — Okta vs Keycloak: The Real ComparisonThis is the decision most teams face. Here’s the unfiltered breakdown:When to Choose OktaYou’re a startup or mid-size company moving fast and don’t want to own identity infrastructureYou have a complex enterprise SaaS integration story — connecting to customers’ existing SSO setupsCompliance (SOC2, HIPAA, FedRAMP) is a near-term requirement and you want it handed to youYour team has no dedicated platform/infrastructure engineersYou can absorb the per-MAU cost at your current and projected scaleWhen to Choose KeycloakYou’re building a multi-tenant SaaS platform where each customer needs an isolated identity namespaceData residency is a hard requirement (GDPR, sovereign cloud, regulated industries)You have hundreds of thousands or millions of users and per-MAU costs become prohibitiveYou have infrastructure engineering capacity and want to own the full stackYou need deep customization — custom authentication flows, custom token transformers, bespoke login UIsYou’re already running Kubernetes and Keycloak fits naturally into your platform engineering modelThe Honest SummaryOkta buys time and reduces operational burden at a monetary cost that scales with your user base. Keycloak is free but costs engineering time and operational maturity. Neither is universally better — the right choice depends entirely on your team’s capacity, budget curve, and how much control you actually need.A useful heuristic: if you’d pay a SaaS vendor to run your database, you’d probably pay Okta to run your identity. If you’d run PostgreSQL yourself on Kubernetes, you’d probably run Keycloak.Summary: The Mental Model That SticksHere’s everything in one place:AuthN → Verify identity (passport check)AuthZ → Grant permissions (boarding pass)OAuth 2.0 → Delegation framework (not AuthN)OIDC → Identity layer on top of OAuth 2.0SAML → Enterprise SSO standard (XML-based)JWT → Token format, not a protocolFlows by use case:The localStorage rule: Never store JWTs in localStorage. Use HttpOnly cookies. One XSS vulnerability away from losing every token you own is not a security posture.The ID Token rule: ID Tokens are for your client. Access Tokens are for your API. Do not mix them up.What’s Coming in Part 2Part 1 gave you the identity foundation. Part 2 is where authorization gets serious:Open Policy Agent (OPA) — policy-as-code at scaleCedar, Casbin, SpiceDB — fine-grained authorization engines comparedZanzibar — Google’s global authorization system and what you can learn from itHow to stop credential stuffing and bot attacks at the authorization layerFollow along — Part 2 publishes soon.Found an error? Have a question? Drop it in the comments. Auth is one of those topics where the edge cases are infinite and the discussion is always worth having.Every Developer Gets Auth Wrong — Until They Understand This was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.