Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 147/ 160
08. Backend

OAuth 2.0

Delegated authorization flows for connecting third-party tools to agents.

IntermediateAuth Code · Scopes3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

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

Loading interactive 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.

PKCE values

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.

Key takeaway: Use authorization code with PKCE and exact redirect URIs for user-delegated access, and client credentials for services.

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.

Blast radius by scope

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.

Key takeaway: Minimise scopes, protect and rotate stored tokens, keep them away from the model and give users a visible way to revoke.

How it works, step by step

Step 1 of 4
Platform engineer

1. Register the client and pick scopes

Register exact redirect URIs and request only the narrowest scopes each feature needs.

drive.readonly, not drive
Key numbers at this step
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

Authorization code + PKCE
Best for: User-delegated access from web, mobile and agent apps

Strengths: Strongest standard flow; protects intercepted codes.

Watch out: Needs redirect handling and token storage.

Client credentials
Best for: Service-to-service calls with no user

Strengths: Simple; no browser.

Watch out: The service holds a powerful secret.

Device code
Best for: CLIs and input-limited devices

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?
Interview tip: Say that scopes are a security control for agents, not just a consent screen detail.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply OAuth 2.0 with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Authentication with JWT
Next topic
SQL vs NoSQL