Blog
Explainer· 3 min read

Sign in with ChatGPT in FastAPI (Python): a complete example

Add "Continue with ChatGPT" to a FastAPI app. Working Python code for the OAuth 2.0 + PKCE redirect, the token exchange with client_secret_basic, and ID token verification with PyJWT.

This post shows the whole Sign in with ChatGPT flow in a FastAPI app: two routes, about 80 lines of Python. It follows OpenAI's website integration docs. For the concepts (scopes, tokens, errors), see our developer guide.

Who can use this: the website flow is a limited trial for selected partners. You need an OpenAI client ID (oaiapp_…) and a registered callback URL for each environment. If you don't have one yet, join through OpenAI's interest form. Open-source and local apps don't need approval: see Sign in with ChatGPT in a Python CLI.

What you need

OPENAI_CLIENT_ID=oaiapp_...
OPENAI_CLIENT_SECRET=...
OPENAI_REDIRECT_URI=https://example.com/auth/chatgpt/callback
COOKIE_SECRET=any-long-random-string

The code

# main.py
import base64
import hashlib
import os
import secrets
from urllib.parse import urlencode

import httpx
import jwt
from fastapi import FastAPI, Request
from fastapi.responses import PlainTextResponse, RedirectResponse
from itsdangerous import BadSignature, URLSafeTimedSerializer

ISSUER = "https://auth.openai.com"
AUTHORIZE = f"{ISSUER}/api/accounts/authorize"
TOKEN = f"{ISSUER}/api/accounts/oauth/token"
JWKS = jwt.PyJWKClient(f"{ISSUER}/.well-known/jwks.json")

CLIENT_ID = os.environ["OPENAI_CLIENT_ID"]
CLIENT_SECRET = os.environ["OPENAI_CLIENT_SECRET"]
REDIRECT_URI = os.environ["OPENAI_REDIRECT_URI"]  # must match the registered URL exactly
signer = URLSafeTimedSerializer(os.environ["COOKIE_SECRET"], salt="siwc-tx")

app = FastAPI()


def b64url(data: bytes) -> str:
    return base64.urlsafe_b64encode(data).rstrip(b"=").decode()


# 1. Start sign-in: fresh state, nonce and PKCE verifier for every attempt.
@app.get("/auth/chatgpt")
def sign_in():
    state, nonce, verifier = (secrets.token_urlsafe(32) for _ in range(3))
    query = urlencode({
        "response_type": "code",
        "client_id": CLIENT_ID,
        "redirect_uri": REDIRECT_URI,
        "scope": "openid profile email",
        "state": state,
        "nonce": nonce,
        "code_challenge": b64url(hashlib.sha256(verifier.encode()).digest()),
        "code_challenge_method": "S256",
    })
    res = RedirectResponse(f"{AUTHORIZE}?{query}", status_code=302)
    res.set_cookie(
        "siwc_tx",
        signer.dumps({"state": state, "nonce": nonce, "verifier": verifier}),
        max_age=600, httponly=True, secure=True, samesite="lax", path="/auth/chatgpt",
    )
    return res


def fail(message: str, status: int = 400):
    res = PlainTextResponse(message, status_code=status)
    res.delete_cookie("siwc_tx", path="/auth/chatgpt")  # clear the transaction on failure too
    return res


# 2. Callback: check state, exchange the code, verify the ID token.
@app.get("/auth/chatgpt/callback")
async def callback(request: Request, code: str | None = None, state: str | None = None, error: str | None = None):
    try:
        tx = signer.loads(request.cookies.get("siwc_tx", ""), max_age=600)
    except BadSignature:  # also covers an expired transaction
        return fail("Sign-in failed")
    if error or not code:
        return fail("Sign-in failed")
    if not secrets.compare_digest(state or "", tx["state"]):
        return fail("Invalid state")

    # Confidential clients use client_secret_basic: httpx puts id and secret in the Authorization header.
    async with httpx.AsyncClient() as client:
        token_res = await client.post(TOKEN, auth=(CLIENT_ID, CLIENT_SECRET), data={
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": REDIRECT_URI,
            "client_id": CLIENT_ID,
            "code_verifier": tx["verifier"],
        })
    if token_res.status_code != 200:
        print("token exchange failed", token_res.status_code, token_res.headers.get("x-request-id"))
        return fail("Sign-in failed", 502)
    id_token = token_res.json()["id_token"]

    try:
        key = JWKS.get_signing_key_from_jwt(id_token).key
        claims = jwt.decode(id_token, key, algorithms=["RS256"], audience=CLIENT_ID, issuer=ISSUER)
    except jwt.PyJWTError:
        return fail("Invalid ID token")
    if not secrets.compare_digest(claims.get("nonce", ""), tx["nonce"]):
        return fail("Invalid nonce")

    # claims["sub"] is the stable ChatGPT account ID. Look users up by sub first;
    # link to an existing account by email only when claims.get("email_verified") is True.
    user = await find_or_create_user(
        sub=claims["sub"],
        email=claims.get("email"),
        email_verified=claims.get("email_verified") is True,
        name=claims.get("name"),
    )
    res = RedirectResponse("/", status_code=302)
    res.delete_cookie("siwc_tx", path="/auth/chatgpt")
    start_session(res, user)  # your own HttpOnly, Secure, SameSite=Lax session cookie
    return res

find_or_create_user and start_session are your app's own functions. Run it with uvicorn main:app. OpenAI signs ID tokens with RS256 (see its discovery document), so the code accepts only that algorithm.

The button

Link your button to /auth/chatgpt, label it Continue with ChatGPT, and add the data-oai-siwc-button attribute so OpenAI can verify your integration:

<a href="/auth/chatgpt" data-oai-siwc-button>Continue with ChatGPT</a>

Common mistakes

When something fails, log the x-request-id (or openai-request-id) response header. OpenAI asks for it when you report a problem.

Next steps