Area 08 · Backend · Concept 07 of 20

OAuth 2.0

‘Login with Google’, and letting your app act on a user’s account with their permission.

01–10 · The basePhase 0 + 5 · Weeks 1–2, 18–20≈ 1.5 hours

The idea

OAuth 2.0 lets a user grant your app limited access to their account on another service without giving you their password. In the authorization code flow, your app redirects the user to the provider, they approve specific scopes (read calendar, send email), and your app receives a code it exchanges for an access token (and often a refresh token).

OpenID Connect adds identity on top, which is how "Login with Google" works: you get an ID token saying who the user is.

For AI agents this is central: an agent that reads a user’s Gmail or Drive should use that user’s OAuth token with minimal scopes, not a company-wide service account. Use PKCE, validate state, store refresh tokens encrypted, and request only the scopes you need.

Why it matters

It is how agents get safe, user-scoped access to real tools and data, and how MCP remote servers authenticate.

Picture it

Words to know

  • ScopeA named permission the user grants.
  • PKCEProof Key for Code Exchange; protects the code flow.
  • Refresh tokenLong-lived token used to get new access tokens.

Try it without code

Review your grants

  1. Open your Google account’s third-party access page.
  2. Look at which apps have which scopes.
  3. Remove one you no longer use.

Use it in code

Google login with Authlib in FastAPI.

python
# pip install authlib itsdangerous httpx
from authlib.integrations.starlette_client import OAuth
from fastapi import FastAPI, Request
from starlette.middleware.sessions import SessionMiddleware

app = FastAPI()
app.add_middleware(SessionMiddleware, secret_key="load-from-env")
oauth = OAuth()
oauth.register("google", client_id="...", client_secret="...",
               server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",
               client_kwargs={"scope": "openid email profile https://www.googleapis.com/auth/calendar.readonly",
                              "code_challenge_method": "S256"})

@app.get("/login")
async def login(request: Request):
    return await oauth.google.authorize_redirect(request, request.url_for("callback"))

@app.get("/callback")
async def callback(request: Request):
    token = await oauth.google.authorize_access_token(request)
    return {"email": token["userinfo"]["email"], "scopes": token.get("scope")}
PRACTICE · TICK IT AFTER THIS

Add Google login to your app and give your agent a read-only calendar tool that uses the user’s own token.

Common mistakes

  • Requesting broad scopes "just in case".
  • Storing refresh tokens in plain text.

Go deeper