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.
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
- Open your Google account’s third-party access page.
- Look at which apps have which scopes.
- Remove one you no longer use.
Use it in code
Google login with Authlib in FastAPI.
# 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")}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.