Skip to Content

Python / Flask backend

Add sign-in to a Python Flask app using the Authlib library and the Authorization Code flow with PKCE.

This guide adds OIDC sign-in to a Flask app using Authlib, which handles discovery, PKCE, and token validation for you. It assumes a confidential client (a backend that can keep a secret).

If you have not yet registered an application, see Before you start. For the protocol behind this, see OpenID Connect (Authorization Code + PKCE).

1. Install dependencies

pip install flask authlib requests

2. Configure the client

import os

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

app = Flask(__name__)
app.secret_key = os.environ["SESSION_SECRET"]

oauth = OAuth(app)
oauth.register(
    "idp",
    client_id=os.environ["OIDC_CLIENT_ID"],
    client_secret=os.environ["OIDC_CLIENT_SECRET"],
    # Your instance's login domain (issuer). Authlib reads the discovery
    # document and configures all endpoints from it.
    server_metadata_url="https://<your-domain>/.well-known/openid-configuration",
    client_kwargs={
        "scope": "openid profile email offline_access",
        "code_challenge_method": "S256",  # send a PKCE challenge as well
    },
)

Keep OIDC_CLIENT_ID and OIDC_CLIENT_SECRET in the environment, never in source control.

3. Start sign-in

Authlib builds the authorization URL with a PKCE challenge and a state, remembers both in the session, and redirects the browser:

@app.route("/login")
def login():
    redirect_uri = url_for("callback", _external=True)  # e.g. https://app.example.com/callback
    return oauth.idp.authorize_redirect(redirect_uri)

The redirect_uri must match a value registered on the application exactly.

4. Handle the callback

Exchange the code for tokens. Authlib validates the response, the state, the PKCE verifier, and the ID token for you.

@app.route("/callback")
def callback():
    tokens = oauth.idp.authorize_access_token()

    claims = tokens["userinfo"]  # validated ID-token claims
    session["user"] = {"sub": claims["sub"], "name": claims.get("name"), "email": claims.get("email")}
    session["id_token"] = tokens["id_token"]

    # Optional: fetch additional claims from UserInfo
    # userinfo = oauth.idp.userinfo(token=tokens)

    return redirect("/")

5. Log out

Send the user to the end-session endpoint, then clear your own session.

from urllib.parse import urlencode

@app.route("/logout")
def logout():
    metadata = oauth.idp.load_server_metadata()
    params = urlencode({
        "id_token_hint": session.get("id_token", ""),
        "post_logout_redirect_uri": "https://app.example.com/",
    })
    session.clear()
    return redirect(f"{metadata['end_session_endpoint']}?{params}")

Register https://app.example.com/ as a post-logout redirect URI on the application, the same way you register a redirect URI.

Troubleshooting

  • The discovery call fails. Confirm https://<your-domain>/.well-known/openid-configuration is reachable from your server and that the domain is your instance's login host.
  • mismatching_state on the callback. The session that started the login must be the one that handles the callback. Make sure session cookies survive the redirect (correct SameSite and, in production, secure cookies over HTTPS), and that secret_key is identical across all workers; a random per-worker key silently breaks the session on every redirect.
  • A refresh token is never returned. Include offline_access in the scope and confirm the application is configured to receive refresh tokens.

Next

On this page