OAuth 2.0
Delegated authorization flows for connecting third-party tools to agents.
In plain words
OAuth lets you say, "this app may read my files, but nothing else, and only until I say stop", without ever giving the app your password.
Think of it like…
A hotel key card issued at the front desk. You (the user) tell the desk which rooms the card may open and for how long; the desk gives the cleaner (the agent) a card, not your master key, and can deactivate it at any time without changing your own lock.
Where you’ve seen it
An assistant lets users connect Google Drive so it can answer questions about their documents. The app uses the authorization code flow with PKCE: it generates a random state (128 bits, checked on return to stop CSRF) and a code_verifier of 32 random bytes, which encode to 43 base64url characters (256 bits), computes code_challenge = BASE64URL(SHA256(code_verifier)) and redirects the browser to the authorization server with response_type=code, client_id, an exact-match registered redirect_uri, scope=drive.readonly and the challenge. The user signs in and consents; the server redirects back with a single-use code; the backend checks state and POSTs the code and the code_verifier to the token endpoint, receiving an access token (3,600 seconds) and a refresh token. The app requests only drive.readonly, not full Drive access: if a prompt-injected agent or a leaked token is abused, the attacker can read but not delete or modify, versus full control of every file the user owns. Tokens are stored encrypted at rest with envelope encryption, keyed by user and integration; the refresh job renews an access token 300 seconds before expiry (at 3,300 seconds), so with 5,000 users and 3 connected services (15,000 grants) the platform makes about 15,000 refreshes an hour, roughly 4 per second. Refresh tokens rotate where the provider supports it, invalid_grant errors mark the connection as needing re-consent, and a disconnect button revokes the token at the provider and deletes the stored copy. Tool calls look up the token for the acting user server-side; the model never sees it. The agent's tool list is built from the scopes actually granted, and sensitive actions (sending an email) still need human approval.
Words you’ll hear
- Scope
- A named permission the user grants, such as drive.readonly.
- Authorization code + PKCE
- A flow that swaps a one-time code and a secret verifier for tokens.
- Refresh token
- A long-lived credential used to obtain new access tokens.
- Redirect URI
- The pre-registered address where the authorization server sends the code.
Visual diagram
Theory & deep dive
Roles, flows and PKCE
OAuth has four roles: the resource owner (user), the client (your app or agent platform), the authorization server (issues tokens) and the resource server (the API holding the data). Authorization code with PKCE is the standard for web, mobile and agent platforms: the client sends the user to the authorization endpoint with client_id, redirect_uri, scope, state and a code_challenge; the user authenticates and consents; the server returns a short-lived, single-use code; the client's backend posts the code plus the original code_verifier to the token endpoint. PKCE protects the exchange: only the party holding the verifier (32 random bytes, 43 base64url characters) can redeem the code, so an intercepted code is useless. The state value ties the response to the request and prevents cross-site request forgery.
Other flows: client credentials (no user, a service authenticates as itself with its own credentials, for server-to-server calls), device code (a CLI or TV displays a code the user enters on another device) and, on older systems, flows to avoid (implicit and password grants are deprecated). Redirect URIs must be registered and matched exactly; wildcards and open redirects leak codes. OpenID Connect layers authentication on OAuth by adding an ID token (a JWT) and a userinfo endpoint; use it when you need to know who the user is, not only to call an API for them.
code_verifier = 32 random bytes → 43 base64url characters, e.g. dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk. code_challenge = BASE64URL(SHA256(verifier)) sent with the first request; the verifier itself is sent only at the token exchange.
Scopes, token handling and agent risks
Scopes are the user's consent boundary: request the narrowest that works (drive.readonly rather than full Drive), request additional scopes incrementally when a feature needs them and show users in plain language what the integration can do. Scope design is a security control for agents: a tool-using model that is manipulated by a prompt injection can only do what the token allows, so a read-only token turns a destructive attack into a limited disclosure risk. Actions with side effects (send, delete, pay) should also require human approval regardless of scope.
Token handling: access tokens are short-lived (often an hour); refresh them proactively (for example 300 seconds before expiry, at 3,300 of 3,600 seconds) and handle invalid_grant by prompting re-consent. Store refresh tokens encrypted at rest (envelope encryption with a managed key), scoped per user and integration, never in logs, prompts or client-side storage, and rotate them where the provider supports rotation. With 5,000 users × 3 integrations = 15,000 grants and one-hour tokens, expect about 15,000 refreshes per hour, 4 per second. Provide disconnect and revoke (call the provider's revocation endpoint, delete the stored token), keep an audit log of token use and tool calls, and never pass raw tokens to the model: tools receive a user ID, and your backend attaches the credential. Monitor consent-screen verification requirements, provider rate limits and scope changes, which can force users to re-authorise.
User has 12,000 Drive files. Token with full drive scope leaked: attacker can read, edit and delete all 12,000. Token with drive.readonly: read-only access to those files, no modification or deletion. Narrower still, drive.file limits the app to files the user explicitly opened with it.
How it works, step by step
Step 1 of 41. Register the client and pick scopes
Register exact redirect URIs and request only the narrowest scopes each feature needs.
- Request
- incrementally
When to use it & trade-offs
What it is
OAuth 2.0 is a framework for delegated authorization: a user lets one application (the client) act on their data in another service (the resource server) without sharing their password. The user approves a limited set of scopes at the authorization server, which issues an access token (short-lived) and often a refresh token (long-lived) to the client. The most common flow for apps with a user is the authorization code flow with PKCE, where the client redirects the user to log in and consent, receives a one-time code on its redirect URI and exchanges it, together with a secret code_verifier, for tokens. For machine-to-machine access the client credentials flow applies, and devices without browsers use the device code flow. OAuth handles authorization; OpenID Connect adds an ID token for authentication.
Why it matters: AI agents become useful when they act on a user's behalf in other systems: read a Google Drive folder, open a GitHub issue, post to Slack. Asking for passwords is unsafe and unscalable. OAuth gives users a consent screen and a way to revoke, gives you scoped, expiring credentials, and gives the third party an audit trail. It also concentrates risk: stored tokens are high-value secrets, over-broad scopes turn a prompt-injection bug into data loss and a flawed redirect flow can leak codes.
When to reach for it
- Connecting user accounts (Drive, GitHub, Slack) to an agent
- Letting partners call your API on behalf of their users
- Server-to-server access with client credentials
When to avoid or be careful
- Asking users for their passwords to other services
- Requesting broad scopes for convenience
- Placing access tokens in prompts or client-side code
OAuth flows
Strengths: Strongest standard flow; protects intercepted codes.
Watch out: Needs redirect handling and token storage.
Strengths: Simple; no browser.
Watch out: The service holds a powerful secret.
Strengths: No browser on the device.
Watch out: More user steps; polling.
Interview signals & numbers to know
When this topic comes up
- “How would an agent read a user's Google Drive?”
- Why PKCE
- OAuth versus OpenID Connect
- Scope design for least privilege
- Storing and refreshing tokens
Benchmarks & rules of thumb
- 32 bytes → 43 chars
- a PKCE code_verifier in base64url
- 3,300 s of 3,600 s
- refreshing 300 seconds before expiry
- 15,000 grants ≈ 4 refreshes/s
- 5,000 users with 3 integrations and one-hour tokens
Common mistakes & follow-ups
Common interview mistakes
- Skipping the state check on the redirect.
- Registering wildcard redirect URIs.
- Treating an OAuth access token as proof of who the user is.
Likely interviewer follow-ups
- How would you limit what a prompt-injected agent can do with a token?
- What happens when a refresh token is revoked?
- When do you add OpenID Connect?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply OAuth 2.0 with generative AI interview Q&A and hands-on practice.