How OAuth 2.0 Works

Intermediate
8 min read· Security

OAuth 2.0 is an authorization framework that lets users grant third-party applications limited access to their accounts without sharing their password. When you click "Login with Google", OAuth is what happens: Google verifies your identity and issues your app a short-lived access token proving you're allowed to read the user's profile. OpenID Connect (OIDC) is a thin identity layer on top of OAuth 2.0 that also tells the app who the user is. Together they power every "Login with X" button on the internet.

Think of it like a hotel key card

When you check into a hotel, you don't hand every staff member your passport (your password). The front desk issues you a key card (access token) that opens only your room and the gym — not every room in the hotel. The key card expires after your stay. If you lose it, the hotel deactivates it and issues a new one without you needing a new passport. OAuth works the same way: the authorization server issues limited, time-bound tokens instead of sharing credentials.

Step by Step

1 / 6

Key Concepts

Authorization Code Flow

The most secure OAuth flow for server-side apps. The authorization code is exchanged for tokens on the backend using the client secret, so tokens are never exposed in the browser URL or history. Always use this flow for web apps, mobile apps (with PKCE), and server-side apps. Never use the deprecated Implicit flow (tokens in URL fragments).

PKCE (Proof Key for Code Exchange)

An extension to the Authorization Code flow for public clients (SPAs, mobile apps) that can't securely store a client secret. The app generates a random code_verifier, hashes it to a code_challenge, sends the challenge in the auth request, and sends the verifier in the token exchange. Prevents authorization code interception attacks.

Access Token

A short-lived credential (typically 1 hour) that grants access to specific resources as defined by its scopes. Often a JWT signed by the authorization server. APIs validate access tokens on every request. Short expiry limits the damage window if a token is stolen.

Refresh Token

A long-lived credential used only to obtain new access tokens. Never sent to resource APIs — only to the authorization server's token endpoint. Must be stored securely server-side. Should be rotated (a new refresh token issued on each use) and revoked on logout.

Scope

The permissions an app is requesting. OAuth scopes are strings that define what the access token grants. Examples: read:profile, write:posts, openid, email. Users see scopes on the consent screen. APIs check that the token's scopes include the required permission for each operation.

OpenID Connect (OIDC)

An identity layer on top of OAuth 2.0 that adds authentication. While OAuth only handles authorization (what you can do), OIDC also handles authentication (who you are). OIDC adds an ID token (a JWT with user claims: sub, email, name) and a /userinfo endpoint. Use OAuth for authorization, OIDC for login.

Client ID and Client Secret

Credentials that identify your app to the authorization server. Client ID is public — it appears in the browser redirect URL. Client secret is confidential — used server-side to exchange codes for tokens. SPAs and mobile apps cannot have a client secret (they run on user devices) — use PKCE instead.

State Parameter

A random, unguessable string generated by your app and included in the authorization request. The authorization server returns it unchanged in the redirect. Your app verifies it matches — if not, reject the response. Prevents Cross-Site Request Forgery (CSRF) attacks where an attacker tricks the callback into accepting their authorization code.

Key Facts

  • OAuth 2.0 is used by Google, Facebook, GitHub, Okta, Auth0, Apple, and virtually every major platform offering third-party login. There are billions of OAuth flows per day on the internet.
  • The "2.0" in OAuth 2.0 is significant — OAuth 1.0 required cryptographic request signing on every API call. OAuth 2.0 simplified this to bearer tokens over HTTPS, making it much easier to implement.
  • OAuth 2.0 is an authorization framework, not an authentication protocol. Using OAuth to verify identity (without OIDC) is a common mistake that leads to security vulnerabilities.
  • The Authorization Code flow with PKCE is recommended for all client types (server-side apps, SPAs, mobile apps) as of OAuth 2.1. The Implicit flow and Resource Owner Password Credentials flow are deprecated.
  • JWT access tokens are stateless — APIs can verify them by checking the signature without a database call. Opaque access tokens require the API to call the authorization server's introspection endpoint to validate.
  • Token revocation is a hard problem with JWTs. Because they're stateless, a stolen JWT is valid until it expires. Mitigation: short access token lifetimes (15 minutes), maintain a token blocklist for compromised tokens.

Real-World Applications

"Login with Google" button

The most common OAuth use case. Your app never handles Google passwords. OAuth verifies identity via Google, returns an ID token with user claims (email, name, sub). You create or look up a user account by the sub (stable unique identifier), issue your own session cookie, and the user is logged in. Never use email as the primary identifier — users can change emails.

Third-party API access

A project management tool wants to read a user's GitHub repositories. Instead of asking for GitHub credentials, it uses OAuth to request the repo:read scope. The user approves on GitHub's consent screen. The tool gets a scoped access token and can list repos — nothing more. The user can revoke access from GitHub's settings at any time.

Machine-to-machine auth (Client Credentials)

A backend service calling another service with no user involved uses the Client Credentials flow — it sends its client_id and client_secret directly to the token endpoint and gets a service-level access token. No user consent screen. Used for microservice authentication, scheduled jobs, and API-to-API communication.

Single Sign-On (SSO)

An enterprise deploys an identity provider (Okta, Azure AD). All internal apps redirect to the IdP for login. The user authenticates once; the IdP issues tokens for each app. SAML uses XML tokens; modern SSO uses OIDC with JWT tokens. The user sees one login prompt for all apps — the IdP handles session sharing.

Frequently Asked Questions

What is the difference between OAuth 2.0 and JWT?

OAuth 2.0 is a protocol/framework for authorization — it defines the flow for obtaining tokens. JWT is a token format — a compact, signed, self-contained way to encode claims. OAuth tokens CAN be JWTs (and often are for access tokens), but JWTs are not OAuth. You can use JWTs for session tokens without OAuth at all. OAuth defines the flows; JWT is one format for the resulting tokens.

Where should I store OAuth tokens in a web app?

Access tokens: in memory (JavaScript variable) — best security, lost on page refresh. Refresh tokens: in an HttpOnly, Secure, SameSite=Strict cookie — cannot be accessed by JavaScript (XSS-safe). Never store tokens in localStorage or sessionStorage — XSS attacks can steal them. The BFF (Backend For Frontend) pattern handles token storage entirely server-side, with the browser only holding a session cookie.

What is the difference between authentication and authorization?

Authentication (AuthN) answers "who are you?" — it verifies identity. Authorization (AuthZ) answers "what are you allowed to do?" — it controls access. OAuth 2.0 was designed for authorization (delegating access to resources). OIDC adds authentication on top. Most real-world systems need both: first authenticate the user, then authorize their actions based on roles and permissions.

Should I build my own OAuth server?

Almost certainly not. Auth is extraordinarily difficult to get right — token security, PKCE, refresh token rotation, revocation, brute force protection, MFA. Use a managed identity provider (Auth0, Clerk, Supabase Auth, AWS Cognito, Firebase Auth, Okta). They handle the hard parts. Build auth yourself only if you have very specific requirements and a dedicated security team.

Related Topics