This sample demonstrates how to add authentication to a Python web app built with Flask using Authgear as an OpenID Connect provider.
Authgear is an Identity-as-a-Service (IDaaS) platform that acts as a gatekeeper to the resources you provide to customers through web apps, mobile apps, APIs, and more. It handles authorization via OAuth 2.0, and the OpenID Connect layer on top adds authentication to secure your users' digital identities.
- Logging a user in through Authgear's hosted login page
- Handling the OAuth 2.0 authorization-code callback
- Reading the authenticated user's profile from the
/userinfoendpoint - Logging a user out
Before you get started, you will need the following:
- A free Authgear account. Sign up if you don't have one already.
- An Authgear OIDC Client application to use as your OpenID Connect provider.
- Python 3.10 or above installed on your machine (this example is tested with Python 3.12).
- pip to install the project's dependencies.
git clone https://github.com/authgear/authgear-example-python-flask.git
cd authgear-example-python-flaskCopy .env.example to .env:
cp .env.example .envThen fill in the values from your Authgear OIDC client app:
| Variable | Description |
|---|---|
AUTHGEAR_CLIENT_ID |
The client ID of your Authgear application. |
AUTHGEAR_CLIENT_SECRET |
The client secret of your Authgear application. |
AUTHGEAR_DOMAIN |
Your Authgear app endpoint, e.g. https://your-project.authgear.cloud. |
APP_SECRET_KEY |
A random string used to sign the Flask session. Generate one with openssl rand -hex 32. |
In the Authgear Portal, add http://localhost:3000/callback to your client app's Authorized Redirect URIs.
We recommend using a virtual environment:
python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt
python server.pyThe app will be served at http://localhost:3000/.
Alternatively, you can run the example in a container. With your .env file in place:
# macOS / Linux
./exec.sh
# Windows (PowerShell)
./exec.ps1This builds the image and runs it, mapping the app to http://localhost:3000/.
The app defines a handful of routes in server.py:
| Route | Description |
|---|---|
/ |
Home page. Shows the raw session token when signed in. |
/login |
Redirects to Authgear's hosted login page. |
/callback |
Handles the OAuth 2.0 redirect and stores the token in the session. |
/user |
Fetches and displays the authenticated user's profile from the /userinfo endpoint. |
/logout |
Clears the session and ends the Authgear session. |
Authentication is handled by Authlib, which discovers Authgear's endpoints automatically from the OpenID Connect configuration at {AUTHGEAR_DOMAIN}/.well-known/openid-configuration.