OAuth

suggest change

OAuth 2.0 (RFC 6749) is the standard way to let an application act on behalf of a user without ever seeing the user's password. "Sign in with Google", a CI job reading your GitHub repos, and a backend service calling another backend's API all use OAuth.

There are four roles:

The client gets an access token, a short-lived credential it sends with API requests as Authorization: Bearer <token>. It often also gets a refresh token, a long-lived credential used to get new access tokens without bothering the user. The scope says what the token is allowed to do, for example read:reports or repo.

How the client gets tokens is called a grant (or flow). Modern guidance (OAuth 2.0 Security Best Current Practice, RFC 9700, and the OAuth 2.1 draft) boils down to a short list:

Situation Grant
a user logs in to a web app, SPA, mobile or desktop app authorization code + PKCE
a service calls an API on its own behalf, no user client credentials
a device without a browser (TV, CLI on a server) device authorization (RFC 8628)
keeping a session alive refresh token
implicit, resource owner password deprecated, don't use

OAuth is about authorization, not authentication. An access token says "the bearer may read reports", not "this is Alice". To log users in, use OpenID Connect (OIDC), a layer on top of OAuth that adds a signed ID token with the user's identity.

This article covers:

The examples were run with Python 3.13, Authlib 1.9, requests 2.34 and Flask 3.1:

pip install authlib requests flask

A toy authorization server

Real providers need an account, a registered app and a browser, which makes examples hard to run. So the examples below talk to a small authorization server written with http.server. It implements the authorization code grant with mandatory PKCE, refresh tokens with rotation, client credentials, token introspection and a protected /api/me endpoint. It skips the login page and approves user alice immediately.

Save it as oauth_server.py next to the examples. It's about 150 lines, and reading it is a good way to see what an authorization server actually checks. It is not secure enough for real use: tokens live in memory, there's no login and no consent screen.

"""A toy OAuth 2.0 authorization server + API for local experiments. Not for production."""
import base64
import hashlib
import json
import secrets
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlencode, urlparse

CLIENTS = {
    "demo-app": {"secret": "demo-secret", "redirect_uris": ["http://127.0.0.1/callback"]},
    "report-job": {"secret": "job-secret", "redirect_uris": []},
    "reports-api": {"secret": "api-secret", "redirect_uris": []},  # a resource server
    "cli-tool": {"secret": None, "redirect_uris": ["http://127.0.0.1/callback"]},
}
ACCESS_TTL = 3600   # seconds, change it to see expiry in action
codes, access_tokens, refresh_tokens = {}, {}, {}


def issue_tokens(client_id, user, scope, with_refresh=True):
    token = secrets.token_urlsafe(24)
    access_tokens[token] = {"client_id": client_id, "sub": user, "scope": scope,
                            "exp": time.time() + ACCESS_TTL}
    resp = {"access_token": token, "token_type": "Bearer",
            "expires_in": ACCESS_TTL, "scope": scope}
    if with_refresh:
        rt = secrets.token_urlsafe(24)
        refresh_tokens[rt] = {"client_id": client_id, "sub": user, "scope": scope}
        resp["refresh_token"] = rt
    return resp


class Handler(BaseHTTPRequestHandler):
    def log_message(self, *args):  # keep the output quiet
        pass

    def send_json(self, status, obj, headers=()):
        body = json.dumps(obj).encode()
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Cache-Control", "no-store")
        for k, v in headers:
            self.send_header(k, v)
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def client_from_request(self, form):
        auth = self.headers.get("Authorization", "")
        if auth.startswith("Basic "):
            cid, _, sec = base64.b64decode(auth[6:]).decode().partition(":")
        else:  # client_secret_post
            cid, sec = form.get("client_id", ""), form.get("client_secret", "")
        c = CLIENTS.get(cid)
        if c and c["secret"] is None:  # public client: no secret, PKCE protects the code
            return cid
        if c and secrets.compare_digest(c["secret"], sec):
            return cid
        return None

    def bearer(self):
        auth = self.headers.get("Authorization", "")
        info = access_tokens.get(auth.removeprefix("Bearer "))
        if not auth.startswith("Bearer ") or not info or info["exp"] < time.time():
            return None
        return info

    def do_GET(self):
        url = urlparse(self.path)
        q = {k: v[0] for k, v in parse_qs(url.query).items()}
        if url.path == "/.well-known/oauth-authorization-server":
            base = f"http://{self.headers['Host']}"
            return self.send_json(200, {
                "issuer": base,
                "authorization_endpoint": base + "/authorize",
                "token_endpoint": base + "/token",
                "introspection_endpoint": base + "/introspect",
                "code_challenge_methods_supported": ["S256"],
            })
        if url.path == "/authorize":
            client = CLIENTS.get(q.get("client_id"))
            ru = urlparse(q.get("redirect_uri", ""))
            # RFC 8252: for loopback redirect URIs any port is allowed
            ru = ru._replace(netloc="127.0.0.1") if ru.hostname == "127.0.0.1" else ru
            if not client or ru.geturl() not in client["redirect_uris"]:
                return self.send_json(400, {"error": "invalid_request"})
            if q.get("code_challenge_method") != "S256" or not q.get("code_challenge"):
                return self.send_json(400, {"error": "invalid_request",
                                            "error_description": "PKCE S256 required"})
            # a real server shows a login + consent page here; we approve "alice"
            code = secrets.token_urlsafe(16)
            codes[code] = {"client_id": q["client_id"], "redirect_uri": q["redirect_uri"],
                           "challenge": q["code_challenge"], "sub": "alice",
                           "scope": q.get("scope", ""), "exp": time.time() + 60}
            params = {"code": code}
            if "state" in q:
                params["state"] = q["state"]
            self.send_response(302)
            self.send_header("Location", q["redirect_uri"] + "?" + urlencode(params))
            self.end_headers()
            return
        if url.path == "/api/me":
            info = self.bearer()
            if not info:
                return self.send_json(401, {"error": "invalid_token"},
                                      [("WWW-Authenticate", 'Bearer error="invalid_token"')])
            return self.send_json(200, {"sub": info["sub"], "scope": info["scope"]})
        self.send_json(404, {"error": "not_found"})

    def do_POST(self):
        length = int(self.headers.get("Content-Length", 0))
        form = {k: v[0] for k, v in parse_qs(self.rfile.read(length).decode()).items()}
        client_id = self.client_from_request(form)
        if client_id is None:
            return self.send_json(401, {"error": "invalid_client"})
        if self.path == "/introspect":
            info = access_tokens.get(form.get("token", ""))
            if not info or info["exp"] < time.time():
                return self.send_json(200, {"active": False})
            return self.send_json(200, {"active": True, "client_id": info["client_id"],
                                        "sub": info["sub"], "scope": info["scope"],
                                        "exp": int(info["exp"])})
        grant = form.get("grant_type")
        if grant == "authorization_code":
            c = codes.pop(form.get("code", ""), None)  # one-time use
            ok = (c and c["exp"] > time.time() and c["client_id"] == client_id
                  and c["redirect_uri"] == form.get("redirect_uri"))
            if ok:
                digest = hashlib.sha256(form.get("code_verifier", "").encode()).digest()
                ok = base64.urlsafe_b64encode(digest).rstrip(b"=").decode() == c["challenge"]
            if not ok:
                return self.send_json(400, {"error": "invalid_grant"})
            return self.send_json(200, issue_tokens(client_id, c["sub"], c["scope"]))
        if grant == "refresh_token":
            rt = refresh_tokens.pop(form.get("refresh_token", ""), None)  # rotation
            if not rt or rt["client_id"] != client_id:
                return self.send_json(400, {"error": "invalid_grant"})
            return self.send_json(200, issue_tokens(client_id, rt["sub"], rt["scope"]))
        if grant == "client_credentials":
            return self.send_json(200, issue_tokens(client_id, client_id,
                                                    form.get("scope", ""), with_refresh=False))
        self.send_json(400, {"error": "unsupported_grant_type"})


def start():
    """Start the server on a free port in a background thread, return its base URL."""
    server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    return f"http://127.0.0.1:{server.server_port}"

start() binds to port 0, so the OS picks a free port, and returns the server's base URL.

PKCE and the authorization URL

The authorization code flow starts by sending the user's browser to the authorization server's /authorize endpoint. Two random values go along:

PKCE is required for public clients (mobile, desktop, SPA, CLI) and recommended for every client, including server-side web apps with a client secret. Both values are easy to create with the standard library:

import base64
import hashlib
import secrets
from urllib.parse import urlencode

def make_pkce_pair():
    verifier = secrets.token_urlsafe(64)          # 86 chars, allowed: 43..128
    digest = hashlib.sha256(verifier.encode("ascii")).digest()
    challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
    return verifier, challenge

verifier, challenge = make_pkce_pair()
state = secrets.token_urlsafe(16)

params = {
    "response_type": "code",
    "client_id": "demo-app",
    "redirect_uri": "http://127.0.0.1/callback",
    "scope": "profile read:reports",
    "state": state,
    "code_challenge": challenge,
    "code_challenge_method": "S256",
}
url = "https://auth.example.com/authorize?" + urlencode(params)

print(len(verifier), len(challenge))
print(url.replace("&", "\n  &"))
86 43
https://auth.example.com/authorize?response_type=code
  &client_id=demo-app
  &redirect_uri=http%3A%2F%2F127.0.0.1%2Fcallback
  &scope=profile+read%3Areports
  &state=jfuZwtkU85mR-_1F919EFw
  &code_challenge=9E1NHqfEqTzptxzmGs_d9Y2ovQfDRstBNlMQQI7Z4q8
  &code_challenge_method=S256

The verifier must be 43 to 128 characters from [A-Za-z0-9-._~]; secrets.token_urlsafe(64) gives 86 such characters. The challenge is base64url without = padding. Always use S256; the plain method sends the verifier itself and defeats the point.

The authorization code flow step by step

Here is the whole flow with nothing but requests. Normally step 2 happens in the user's browser; here requests.get(..., allow_redirects=False) plays the browser and we read the redirect from the Location header.

import base64
import hashlib
import secrets
from urllib.parse import parse_qs, urlencode, urlparse

import requests
import oauth_server

AUTH = oauth_server.start()
CLIENT_ID, CLIENT_SECRET = "demo-app", "demo-secret"
REDIRECT_URI = "http://127.0.0.1/callback"

# 1. the client prepares state + PKCE and sends the user to /authorize
verifier = secrets.token_urlsafe(64)
challenge = base64.urlsafe_b64encode(
    hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
state = secrets.token_urlsafe(16)
auth_url = AUTH + "/authorize?" + urlencode({
    "response_type": "code", "client_id": CLIENT_ID, "redirect_uri": REDIRECT_URI,
    "scope": "profile", "state": state,
    "code_challenge": challenge, "code_challenge_method": "S256",
})

# 2. the user logs in and approves; the browser is redirected back to us
r = requests.get(auth_url, allow_redirects=False, timeout=10)
callback_url = r.headers["Location"]
print("redirected to:", callback_url.split("?")[0])

# 3. the callback handler checks state and takes the code
query = parse_qs(urlparse(callback_url).query)
if not secrets.compare_digest(query["state"][0], state):
    raise RuntimeError("state mismatch: possible CSRF")
code = query["code"][0]

# 4. exchange the code for tokens (back channel, with client authentication)
r = requests.post(AUTH + "/token", data={
    "grant_type": "authorization_code", "code": code,
    "redirect_uri": REDIRECT_URI, "code_verifier": verifier,
}, auth=(CLIENT_ID, CLIENT_SECRET), timeout=10)
r.raise_for_status()
token = r.json()
print("token fields:", sorted(token))

# 5. call the API with the access token
r = requests.get(AUTH + "/api/me", timeout=10,
                 headers={"Authorization": f"Bearer {token['access_token']}"})
print(r.status_code, r.json())

# a code can be used only once
r = requests.post(AUTH + "/token", data={
    "grant_type": "authorization_code", "code": code,
    "redirect_uri": REDIRECT_URI, "code_verifier": verifier,
}, auth=(CLIENT_ID, CLIENT_SECRET), timeout=10)
print("reusing the code:", r.status_code, r.json())
redirected to: http://127.0.0.1/callback
token fields: ['access_token', 'expires_in', 'refresh_token', 'scope', 'token_type']
200 {'sub': 'alice', 'scope': 'profile'}
reusing the code: 400 {'error': 'invalid_grant'}

The steps:

  1. The client redirects the browser to /authorize with response_type=code, its client_id, the redirect_uri, the requested scope, state and the PKCE challenge.
  2. The user logs in and approves. The authorization server redirects the browser back to redirect_uri?code=...&state=....
  3. The client checks that state matches what it stored, using secrets.compare_digest().
  4. The client posts the code, the same redirect_uri and the code verifier to the token endpoint. This is a direct server-to-server request (the "back channel"), authenticated with the client's credentials, here using HTTP Basic auth. The response contains the tokens.
  5. The client calls the API with Authorization: Bearer <access token>.

The authorization code is short-lived (usually under a minute) and single-use. A second exchange fails with invalid_grant, and a good server also revokes the tokens issued for that code, because a reused code suggests it was stolen.

The token response is JSON:

{
  "access_token": "...",
  "token_type": "Bearer",
  "expires_in": 3600,
  "refresh_token": "...",
  "scope": "profile"
}

expires_in is relative, so convert it to an absolute time (time.time() + expires_in) as soon as you receive it. The returned scope may be narrower than what you asked for if the user didn't grant everything.

The same flow with Authlib

Writing OAuth by hand is useful for understanding it, but in real code use a library. Authlib is the most complete OAuth and OpenID Connect library for Python, with clients for requests and httpx and integrations for Flask, Django, Starlette and FastAPI. (requests-oauthlib is an older alternative.)

OAuth2Session from authlib.integrations.requests_client is a requests.Session that knows how to build the authorization URL, exchange the code and attach the token:

import secrets

import requests
from authlib.integrations.requests_client import OAuth2Session
import oauth_server

AUTH = oauth_server.start()

client = OAuth2Session(
    client_id="demo-app",
    client_secret="demo-secret",
    redirect_uri="http://127.0.0.1/callback",
    scope="profile read:reports",
    code_challenge_method="S256",
)

# generates state; PKCE is added when you pass a code_verifier
code_verifier = secrets.token_urlsafe(64)
url, state = client.create_authorization_url(AUTH + "/authorize",
                                             code_verifier=code_verifier)
print("state:", len(state), "chars, has PKCE:", "code_challenge=" in url)

# store state and code_verifier in the user's session, then redirect to url...
callback = requests.get(url, allow_redirects=False, timeout=10).headers["Location"]

# ...in the callback: Authlib parses the URL, checks state and posts to the token endpoint
token = client.fetch_token(AUTH + "/token", authorization_response=callback,
                           state=state, code_verifier=code_verifier)
print(type(token).__name__, token["token_type"], token["expires_in"], "expires_at" in token)

# the session now adds "Authorization: Bearer ..." to every request
print(client.get(AUTH + "/api/me").json())

# a wrong state is rejected before any network call
try:
    client.fetch_token(AUTH + "/token", authorization_response=callback,
                       state="something-else", code_verifier=code_verifier)
except Exception as e:
    print(type(e).__name__, e)
state: 30 chars, has PKCE: True
OAuth2Token Bearer 3600 True
{'sub': 'alice', 'scope': 'profile read:reports'}
MismatchingStateException mismatching_state: CSRF Warning! State not equal in request and response.

create_authorization_url() generates a random state and, when you pass a code_verifier and set code_challenge_method="S256", adds the PKCE challenge. Save state and code_verifier in the user's server-side session (or a signed cookie) between the redirect and the callback.

fetch_token() takes the full callback URL, checks state, sends the code and the verifier to the token endpoint and returns an OAuth2Token, a dict subclass that adds expires_at (an absolute Unix timestamp) and an is_expired() method. The session then sends Authorization: Bearer ... with every request.

Most providers publish their endpoints in a metadata document: /.well-known/openid-configuration for OpenID Connect, or /.well-known/oauth-authorization-server (RFC 8414). Read the URLs from there instead of hard-coding them; the Flask integration below does that for you.

Storing and refreshing tokens

Access tokens are short-lived on purpose: if one leaks, it's useful for minutes, not months. A refresh token lets the client get a new access token without sending the user through the login page again.

Give OAuth2Session the saved token, the token_endpoint and an update_token callback. Before each request it checks expires_at, and if the token has expired, it refreshes it first and calls your callback so you can save the new tokens:

import json
import time
from pathlib import Path

import requests
from authlib.integrations.requests_client import OAuth2Session
import oauth_server

oauth_server.ACCESS_TTL = 2          # very short-lived access tokens
AUTH = oauth_server.start()
TOKEN_FILE = Path("token.json")

# shortcut: pretend we did the authorization code flow earlier and saved the result
token = oauth_server.issue_tokens("demo-app", "alice", "profile")
token["expires_at"] = int(time.time()) + token["expires_in"]
TOKEN_FILE.write_text(json.dumps(token))

def save_token(token, refresh_token=None, access_token=None):
    # Authlib calls this after every refresh: persist the new tokens
    TOKEN_FILE.write_text(json.dumps(token))
    print("  saved new token, refresh token rotated:", token["refresh_token"] != old_refresh)

# later, e.g. in another process: load the saved token
token = json.loads(TOKEN_FILE.read_text())
old_refresh = token["refresh_token"]
client = OAuth2Session(
    "demo-app", "demo-secret",
    token=token,
    token_endpoint=AUTH + "/token",   # enables automatic refresh
    update_token=save_token,
    leeway=0,                         # default: refresh 60 s before expiry
)

print("1:", client.get(AUTH + "/api/me").status_code)
time.sleep(2.5)
print("access token expired:", client.token.is_expired(leeway=0))
print("2:", client.get(AUTH + "/api/me").status_code)   # refreshes first
print("expired now:", client.token.is_expired(leeway=0))

# the old refresh token was invalidated by rotation
r = requests.post(AUTH + "/token", auth=("demo-app", "demo-secret"), timeout=10,
                  data={"grant_type": "refresh_token", "refresh_token": old_refresh})
print("old refresh token:", r.status_code, r.json())
TOKEN_FILE.unlink()
1: 200
access token expired: True
  saved new token, refresh token rotated: True
2: 200
expired now: False
old refresh token: 400 {'error': 'invalid_grant'}

Things to notice:

Store tokens like passwords. Refresh tokens in particular are long-lived credentials: keep them in a database column encrypted at rest, in the OS keychain for desktop and CLI apps (the keyring package), or in a secrets manager. Never log them, and don't put them in URLs. The token.json file here only keeps the example short.

Client credentials: service to service

When there's no user, for example a nightly job that reads reports through an API, the client authenticates as itself and asks for a token directly. There's no browser, no redirect and no refresh token:

import time

from authlib.integrations.requests_client import OAuth2Session
import oauth_server

oauth_server.ACCESS_TTL = 2
AUTH = oauth_server.start()

client = OAuth2Session(
    client_id="report-job",
    client_secret="job-secret",
    scope="read:reports",
    token_endpoint=AUTH + "/token",
    grant_type="client_credentials",
    leeway=0,
)
token = client.fetch_token()        # grant_type=client_credentials, no user involved
print(sorted(token))
print(client.get(AUTH + "/api/me").json())

first = token["access_token"]
time.sleep(2.5)
r = client.get(AUTH + "/api/me")   # expired: Authlib fetches a new token by itself
print(r.status_code, client.token["access_token"] != first)
client.close()
['access_token', 'expires_at', 'expires_in', 'scope', 'token_type']
{'sub': 'report-job', 'scope': 'read:reports'}
200 True

With grant_type="client_credentials" and a token_endpoint, Authlib also fetches a fresh token automatically when the current one has expired. Create one session at startup and reuse it; requesting a new token for every API call is slow and many providers rate-limit the token endpoint.

The same code works with httpx through authlib.integrations.httpx_client.OAuth2Client (and AsyncOAuth2Client for asyncio).

Log in with ... in a Flask app

For web apps, Authlib's framework integrations keep state, the PKCE verifier and (for OpenID Connect) the nonce in the session for you. You register a provider once, then write two views: one that redirects to the provider, and the callback.

The example uses Flask's test client as the browser and requests as the user approving the login at the authorization server:

import os
from urllib.parse import urlparse

import requests
from authlib.integrations.flask_client import OAuth, OAuthError
from flask import Flask, redirect, session, url_for
import oauth_server

AUTH = oauth_server.start()

app = Flask(__name__)
app.secret_key = os.urandom(32)   # signs the session cookie that holds state + PKCE verifier

oauth = OAuth(app)
oauth.register(
    name="toy",
    client_id="demo-app",                      # in real code: os.environ[...]
    client_secret="demo-secret",
    server_metadata_url=AUTH + "/.well-known/oauth-authorization-server",
    api_base_url=AUTH + "/api/",
    client_kwargs={"scope": "profile", "code_challenge_method": "S256"},
)

@app.route("/login")
def login():
    return oauth.toy.authorize_redirect("http://127.0.0.1/callback")

@app.route("/callback")
def callback():
    try:
        token = oauth.toy.authorize_access_token()   # checks state, sends code + verifier
    except OAuthError as e:
        return f"login failed: {e.error}", 400
    user = oauth.toy.get("me", token=token).json()
    session.clear()                                   # new session after login
    session["user"] = user["sub"]
    return redirect(url_for("home"))

@app.route("/")
def home():
    user = session.get("user")
    return f"hello {user}" if user else "not logged in"

# --- simulate a browser -----------------------------------------------------
browser = app.test_client()
r = browser.get("/login")
print("1.", r.status_code, urlparse(r.location).path)

# the authorization server logs the user in and redirects back
loc = requests.get(r.location, allow_redirects=False, timeout=10).headers["Location"]
cb = urlparse(loc)
print("2.", cb.path, sorted(k.split("=")[0] for k in cb.query.split("&")))

r = browser.get(f"{cb.path}?{cb.query}")
print("3.", r.status_code, r.location)
print("4.", browser.get("/").text)

# a forged callback from another browser (no matching state in its session)
r = app.test_client().get(f"{cb.path}?{cb.query}")
print("5.", r.status_code, r.text)
1. 302 /authorize
2. /callback ['code', 'state']
3. 302 /
4. hello alice
5. 400 login failed: mismatching_state

server_metadata_url points at the provider's metadata, from which Authlib reads authorization_endpoint and token_endpoint. code_challenge_method="S256" turns on PKCE. authorize_redirect() saves state and the verifier in Flask's session, and authorize_access_token() checks them and exchanges the code. A callback that arrives in a browser session that didn't start the login fails with mismatching_state, which is exactly the CSRF protection state exists for.

In real code, pass url_for("callback", _external=True) as the redirect URI (the toy server only accepts its one registered URI), read the client ID and secret from the environment, and call session.clear() after login to prevent session fixation, as above.

OpenID Connect

To log users in with Google, Microsoft, Okta, Keycloak and others, use OpenID Connect. Add openid to the scope and point server_metadata_url at the provider's /.well-known/openid-configuration:

oauth.register(
    name="google",
    client_id=os.environ["GOOGLE_CLIENT_ID"],
    client_secret=os.environ["GOOGLE_CLIENT_SECRET"],
    server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",
    client_kwargs={"scope": "openid email profile", "code_challenge_method": "S256"},
)

@app.route("/login/google")
def login_google():
    return oauth.google.authorize_redirect(url_for("auth_google", _external=True))

@app.route("/auth/google")
def auth_google():
    token = oauth.google.authorize_access_token()
    claims = token["userinfo"]        # validated ID token claims
    session.clear()
    session["user"] = {"sub": claims["sub"], "email": claims.get("email")}
    return redirect("/")

The token response now also contains an id_token, a JWT signed by the provider. Authlib sends a nonce with the authorization request, then verifies the ID token's signature against the provider's published keys and checks iss, aud, exp and nonce before returning the claims as token["userinfo"]. See JWT for what that verification involves.

Identify users by the sub claim (or the pair iss + sub if you support several providers), never by email address: emails change and get reassigned, and some providers don't verify them. Check email_verified before trusting an email for anything.

GitHub supports plain OAuth 2.0 rather than OpenID Connect: there's no ID token, so after getting the access token you call its https://api.github.com/user API to find out who logged in.

Logging in from a command-line tool

A CLI or desktop app is a public client: anything shipped to users can be read, so it can't keep a client secret. It uses the authorization code flow with PKCE and no secret, and receives the redirect on a loopback address: the app starts a tiny HTTP server on 127.0.0.1 on a free port, opens the system browser, and waits for one request (RFC 8252). Authorization servers allow any port for loopback redirect URIs.

import secrets
import threading
import webbrowser
from http.server import BaseHTTPRequestHandler, HTTPServer

import requests
from authlib.integrations.requests_client import OAuth2Session
import oauth_server

AUTH = oauth_server.start()

def login_from_cli(open_browser=webbrowser.open):
    result = {}

    class CallbackHandler(BaseHTTPRequestHandler):
        def do_GET(self):
            result["url"] = "http://127.0.0.1" + self.path
            self.send_response(200)
            self.send_header("Content-Type", "text/html")
            self.end_headers()
            self.wfile.write(b"<p>Logged in. You can close this tab.</p>")

        def log_message(self, *args):
            pass

    server = HTTPServer(("127.0.0.1", 0), CallbackHandler)   # port 0: any free port
    redirect_uri = f"http://127.0.0.1:{server.server_port}/callback"

    client = OAuth2Session("cli-tool", redirect_uri=redirect_uri, scope="profile",
                           code_challenge_method="S256",
                           token_endpoint_auth_method="none")   # public client
    verifier = secrets.token_urlsafe(64)
    url, state = client.create_authorization_url(AUTH + "/authorize", code_verifier=verifier)

    open_browser(url)
    server.timeout = 120
    server.handle_request()            # wait for exactly one request: the redirect
    server.server_close()
    if "url" not in result:
        raise TimeoutError("no response from the browser")

    return client.fetch_token(AUTH + "/token", authorization_response=result["url"],
                              state=state, code_verifier=verifier)

# in a test there is no browser: follow the redirects with requests in a thread
def fake_browser(url):
    threading.Thread(target=requests.get, args=(url,), kwargs={"timeout": 10}).start()

token = login_from_cli(open_browser=fake_browser)
print(sorted(token))
r = requests.get(AUTH + "/api/me", timeout=10,
                 headers={"Authorization": f"Bearer {token['access_token']}"})
print(r.json())
['access_token', 'expires_at', 'expires_in', 'refresh_token', 'scope', 'token_type']
{'sub': 'alice', 'scope': 'profile'}

token_endpoint_auth_method="none" tells Authlib to send only client_id to the token endpoint, with no secret. PKCE is what protects the code: another program on the machine that sees the redirect still can't redeem the code without the verifier. Bind to 127.0.0.1 rather than localhost (which may resolve to something else) and never to 0.0.0.0.

On a machine without a browser, for example over SSH, use the device authorization grant instead: the tool shows a short code and a URL, the user opens the URL on their phone, and the tool polls the token endpoint until the user approves. GitHub CLI and Azure CLI log in this way.

Protecting your own API

On the resource server side, every request must carry a valid access token with the right scope. There are two ways to validate a token:

The toy server issues opaque tokens, so this API uses introspection, with a decorator that checks the scope:

import functools
import time

import requests
from flask import Flask, g, jsonify, request
import oauth_server

AUTH = oauth_server.start()
INTROSPECT_URL = AUTH + "/introspect"
API_CREDENTIALS = ("reports-api", "api-secret")
_cache = {}   # token -> (checked_at, introspection result)

def introspect(token):
    hit = _cache.get(token)
    if hit and time.time() - hit[0] < 30:     # cache briefly: fewer calls, slower revocation
        return hit[1]
    r = requests.post(INTROSPECT_URL, data={"token": token, "token_type_hint": "access_token"},
                      auth=API_CREDENTIALS, timeout=5)
    r.raise_for_status()
    info = r.json()
    _cache[token] = (time.time(), info)
    return info

def require_scope(scope):
    def decorator(view):
        @functools.wraps(view)
        def wrapper(*args, **kwargs):
            auth = request.headers.get("Authorization", "")
            if not auth.startswith("Bearer "):
                return error(401)
            info = introspect(auth.removeprefix("Bearer "))
            if not info.get("active"):
                return error(401, "invalid_token")
            if scope not in info.get("scope", "").split():
                return error(403, "insufficient_scope", scope)
            g.token = info
            return view(*args, **kwargs)
        return wrapper
    return decorator

def error(status, code=None, scope=None):
    # RFC 6750: no error code when the request had no credentials at all
    params = [f'error="{code}"'] if code else []
    if scope:
        params.append(f'scope="{scope}"')
    value = " ".join(["Bearer", ", ".join(params)]).strip()
    return jsonify(error=code or "unauthorized"), status, {"WWW-Authenticate": value}

app = Flask(__name__)

@app.get("/reports")
@require_scope("read:reports")
def reports():
    return {"owner": g.token["sub"], "reports": ["q1.pdf", "q2.pdf"]}

client = app.test_client()
good = oauth_server.issue_tokens("demo-app", "alice", "profile read:reports")["access_token"]
weak = oauth_server.issue_tokens("demo-app", "bob", "profile")["access_token"]

for name, headers in [("no token", {}),
                      ("bad token", {"Authorization": "Bearer nope"}),
                      ("weak token", {"Authorization": f"Bearer {weak}"}),
                      ("good token", {"Authorization": f"Bearer {good}"})]:
    r = client.get("/reports", headers=headers)
    print(f"{name:10} {r.status_code} {r.get_json()} {r.headers.get('WWW-Authenticate', '')}")
no token   401 {'error': 'unauthorized'} Bearer
bad token  401 {'error': 'invalid_token'} Bearer error="invalid_token"
weak token 403 {'error': 'insufficient_scope'} Bearer error="insufficient_scope", scope="read:reports"
good token 200 {'owner': 'alice', 'reports': ['q1.pdf', 'q2.pdf']}

The status codes follow RFC 6750: 401 when the token is missing, invalid or expired (the client should get a new token), 403 when the token is fine but lacks the scope (a new token won't help unless the user grants more). The WWW-Authenticate header tells the client which case it hit.

The resource server authenticates to the introspection endpoint with its own credentials, so random clients can't use it to probe tokens. Caching results for a short time cuts the load on the authorization server, but a revoked token keeps working until its cache entry expires, so keep the cache time short.

Also check the audience: a token issued for another API (with JWTs, the aud claim) must be rejected even if it's otherwise valid. Otherwise any service that receives a token from a user can replay it against your API.

Handling errors

The token endpoint reports errors as JSON with an error code (and optionally error_description). Authlib raises OAuthError with the code in e.error:

from authlib.integrations.base_client import OAuthError
from authlib.integrations.requests_client import OAuth2Session
import oauth_server

AUTH = oauth_server.start()

def refresh(client_secret, refresh_token):
    client = OAuth2Session("demo-app", client_secret)
    try:
        return client.refresh_token(AUTH + "/token", refresh_token=refresh_token)
    except OAuthError as e:
        print("error:", e.error)
        if e.error == "invalid_grant":
            print("  -> refresh token expired or revoked: send the user to log in again")
        elif e.error == "invalid_client":
            print("  -> our client credentials are wrong: a configuration bug")

rt = oauth_server.issue_tokens("demo-app", "alice", "profile")["refresh_token"]
refresh("wrong-secret", rt)
refresh("demo-secret", "not-a-real-token")
token = refresh("demo-secret", rt)
print(sorted(token))
error: invalid_client
  -> our client credentials are wrong: a configuration bug
error: invalid_grant
  -> refresh token expired or revoked: send the user to log in again
['access_token', 'expires_at', 'expires_in', 'refresh_token', 'scope', 'token_type']

The codes you'll meet most often:

error Meaning What to do
invalid_grant code or refresh token is expired, used or revoked; redirect_uri or PKCE verifier don't match for refresh: drop the tokens and log the user in again
invalid_client wrong client ID or secret, or wrong auth method fix configuration; don't retry
invalid_scope asked for a scope the client isn't allowed fix the request
unauthorized_client this client isn't allowed this grant type fix the client's registration
access_denied (in the callback ?error=) the user clicked "Deny" show a message, don't treat it as a crash

Errors from /authorize come back to your callback as ?error=access_denied&state=... instead of ?code=.... Check state on error responses too, and don't display error_description as HTML without escaping it.

Security checklist

Summary

Task Code
PKCE pair secrets.token_urlsafe(64), base64url(SHA-256) without =
authorization URL client.create_authorization_url(url, code_verifier=v)
exchange code client.fetch_token(token_url, authorization_response=cb, state=s, code_verifier=v)
call an API client.get(url) or headers={"Authorization": f"Bearer {token}"}
automatic refresh OAuth2Session(..., token=t, token_endpoint=url, update_token=save)
service-to-service OAuth2Session(..., grant_type="client_credentials").fetch_token(url)
Flask login oauth.register(..., server_metadata_url=...), authorize_redirect(), authorize_access_token()
CLI login loopback server on port 0, token_endpoint_auth_method="none", PKCE
protect an API verify JWT or introspect; 401 for bad token, 403 for missing scope
errors except OAuthError as e: e.error

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents