Registry / web-framework / flask-oidc

flask-oidc

JSON →
library2.4.0pypypi✓ verified 24d ago

Flask-OIDC is an extension to Flask that allows you to add OpenID Connect based authentication to your website. It is currently at version 2.4.0 and sees regular releases, with several updates in the past year, indicating active maintenance and development.

pip install flask-oidc
INSTALL
IMPORT
SIG · FLASK-OIDC
F
flask-oidc
web-frameworkpythonv2.4.0
Install
4.0s avg
Import
1103ms
Disk
45MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.4.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 1.132s · 46.7MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 4.0s · import 1.074s · 47MB
45MB installed
● package 45MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

OpenIDConnect
from flask_oidc import OpenIDConnect
The primary class for OIDC integration.
g
from flask import g
Flask's global object, used to access OIDC user information after login (e.g., `g.oidc_user`).
session
from flask import session
Flask's session object, stores 'oidc_auth_profile' for user information.

This quickstart demonstrates a basic Flask application integrated with Flask-OIDC. It configures the OIDC extension, protects a route using `oidc.require_login`, and provides simple login/logout functionality. Configuration details for your OIDC provider are expected in a `client_secrets.json` file. Ensure `FLASK_SECRET_KEY` and the `client_secrets.json` path are set, ideally via environment variables, and configure `OIDC_REDIRECT_URI` to match your registered callback URL.

import os from flask import Flask, redirect, url_for, render_template_string, g, session from flask_oidc import OpenIDConnect app = Flask(__name__) app.config.update({ 'SECRET_KEY': os.environ.get('FLASK_SECRET_KEY', 'a_very_secret_key_that_should_be_random'), 'OIDC_CLIENT_SECRETS': os.environ.get('OIDC_CLIENT_SECRETS_FILE', './client_secrets.json'), 'OIDC_REDIRECT_URI': os.environ.get('OIDC_REDIRECT_URI', 'http://localhost:5000/oidc_callback'), 'OIDC_SCOPES': ['openid', 'email', 'profile'], 'OIDC_COOKIE_SECURE': False, # Use True in production with HTTPS 'OIDC_CALLBACK_ROUTE': '/oidc_callback', # The default callback route. 'OIDC_REQUIRE_VERIFIED_EMAIL': False # Set to True for stricter validation }) oidc = OpenIDConnect(app) HTML_TEMPLATE = ''' <!doctype html> <html lang="en"> <head><meta charset="utf-8"></head> <body> {% if g.oidc_user.is_authenticated() %} Hello, {{ g.oidc_user.userinfo.get('preferred_username', 'User') }}! <a href="{{ url_for('private') }}">Access Protected Area</a> <a href="{{ url_for('oidc_logout') }}">Log Out</a> {% else %} Welcome, anonymous user! <a href="{{ url_for('private') }}">Log In</a> {% endif %} </body> </html> ''' @app.route('/') def index(): return render_template_string(HTML_TEMPLATE) @app.route('/private') @oidc.require_login # Protect this route. def private(): return f"Hello, {g.oidc_user.userinfo.get('email')}! This is a protected area." @app.route('/logout') def oidc_logout(): oidc.logout() return redirect(url_for('index')) # Example client_secrets.json content (create this file next to your app.py): # { # "web": { # "client_id": "YOUR_CLIENT_ID", # "client_secret": "YOUR_CLIENT_SECRET", # "auth_uri": "YOUR_PROVIDER_AUTH_URI", # "token_uri": "YOUR_PROVIDER_TOKEN_URI", # "userinfo_uri": "YOUR_PROVIDER_USERINFO_URI", # "issuer": "YOUR_PROVIDER_ISSUER", # "redirect_uris": ["http://localhost:5000/oidc_callback"], # "token_introspection_uri": "YOUR_PROVIDER_TOKEN_INTROSPECTION_URI" (optional) # } # } if __name__ == '__main__': # For local development, ensure OIDC_CLIENT_SECRETS_FILE points to a valid file. # Replace with your actual OIDC provider details in client_secrets.json # And set FLASK_SECRET_KEY in your environment. # export FLASK_SECRET_KEY="a_strong_random_secret_key" # If using HTTP (not recommended for production), set OIDC_COOKIE_SECURE to False. # Otherwise, ensure your application runs over HTTPS. app.run(debug=True, port=5000)
Debug
Known issues
breakingVersion 2.0.0 represents a major rebase of Flask-OIDC's API on the Authlib library. This introduced significant breaking changes in how the library is configured and used compared to 1.x versions.
fix
Review the official documentation and migration guides for Authlib and Flask-OIDC v2.x. Many configuration options and API calls have changed or been removed. For example, `oidc.credentials_store` and other constructor parameters were removed.
affects: >=2.0.0
deprecatedThe `OpenIDConnect.user_getinfo()` and `OpenIDConnect.user_getfield()` methods are deprecated. User information should now be accessed via `session["oidc_auth_profile"]` or `g.oidc_user.userinfo`.
fix
Replace calls to `oidc.user_getinfo()` or `oidc.user_getfield()` with direct access to `session["oidc_auth_profile"]` or the properties of `g.oidc_user` (available since 2.2.0).
affects: >=2.0.0
breakingThe `redirect_uri` sent to the ID provider in earlier 2.x versions (e.g., 2.0.3) was forced to HTTPS. In 2.1.0, this was changed to no longer force HTTPS based on OIDC spec recommendations. If you explicitly need to force HTTPS (or any specific URL), use `OIDC_OVERWRITE_REDIRECT_URI`.
fix
For applications needing specific `redirect_uri` behavior, especially forcing HTTPS, explicitly set the `OIDC_OVERWRITE_REDIRECT_URI` configuration option. Review the behavior in versions 2.0.3 and 2.1.0 in the changelog.
affects: 2.0.0 - 2.0.x
gotchaThe `oidc.redirect_to_auth_server()` method was initially removed in 2.x and then re-added in version 2.2.2 for compatibility with v1.x usage patterns.
fix
If migrating from 1.x and encountering issues with `redirect_to_auth_server()`, ensure you are on version 2.2.2 or later if you need to use this specific method. Otherwise, adapt your code to newer 2.x patterns for redirection.
affects: 2.0.0 - 2.2.1
gotchaA `SECRET_KEY` for the Flask application is absolutely critical for session management and overall security. Failing to set a strong, unique secret key will lead to security vulnerabilities.
fix
Always set `app.config['SECRET_KEY']` to a long, random string. It is highly recommended to manage this key via environment variables in production. For example, `os.environ.get('FLASK_SECRET_KEY', 'default_for_dev')`.
affects: All versions
gotchaThe `client_secrets.json` file is mandatory for OIDC configuration unless the `OIDC_ENABLED` setting is explicitly set to `False`. Before version 2.3.1, not having this file would cause issues even if `OIDC_ENABLED` was set to `False`.
fix
Ensure a valid `client_secrets.json` file is present or that `OIDC_ENABLED` is set to `False` (requires version 2.3.1 or higher for `client_secrets.json` to be entirely optional in this disabled state). The structure requires a top-level `web` key.
affects: <2.3.1
breakingVersion 2.4.0 includes a fix for an open redirect vulnerability in login and logout URLs. While this is a fix, applications relying on or inadvertently enabling such redirects could experience changes in behavior or breakages.
fix
Upgrade to version 2.4.0 or later to apply the security fix. Review any custom login/logout redirect logic to ensure it is not negatively impacted by the fix and adheres to secure redirect practices.
affects: <2.4.0
Errors
Common errors & fixes
The 'redirect_uri' parameter must be a Login redirect URI in the client app settings
This error occurs when the redirect URI that Flask-OIDC sends to the Identity Provider does not exactly match a URI registered in the client application settings of the Identity Provider. This is particularly common when deploying behind a reverse proxy (e.g., Nginx) or with HTTPS, where Flask-OIDC might generate an HTTP callback URL while the application is accessed via HTTPS.
fix
Ensure the exact callback URL (e.g., `https://yourdomain.com/oidc/callback`) is registered in your OIDC provider's client settings. In your Flask application, explicitly set `app.config['OVERWRITE_REDIRECT_URI'] = 'https://yourdomain.com/oidc/callback'` to force Flask-OIDC to use the correct absolute HTTPS URL.
ModuleNotFoundError: No module named 'flask_oidc'
The `flask-oidc` library is not installed in the Python environment where your Flask application is running, or the application is being run with a different Python interpreter/virtual environment than where the library was installed.
fix
Activate the correct Python virtual environment (if applicable) and install the library using pip: `pip install Flask-OIDC`.
Unauthorized mismatching_state: CSRF Warning! State not equal in request and response.
This error indicates a CSRF (Cross-Site Request Forgery) protection failure where the 'state' parameter generated by Flask-OIDC during the authorization request does not match the 'state' parameter returned in the OIDC callback. This often points to issues with Flask's session management, especially in multi-threaded environments (e.g., Gunicorn with multiple workers) where session data might not be properly shared or synchronized, or incorrect cookie settings preventing the state from being retrieved.
fix
Ensure your Flask application has a `SECRET_KEY` configured (`app.config['SECRET_KEY'] = 'your_strong_secret_key'`). If running with multiple workers/threads, ensure your Flask session configuration allows for proper state preservation across requests, potentially by using a shared session backend or verifying that cookie settings (like `SAMESITE`) are not inadvertently preventing the cookie from being sent.
ERROR:flask_oidc:ERROR: Unable to get token info
This error occurs when Flask-OIDC fails to exchange the authorization code received from the Identity Provider for an access token or to retrieve user information using the token. Common causes include incorrect `client_secrets.json` configuration (e.g., missing or incorrect `client_secret`), issues with the OIDC provider's client configuration (e.g., invalid scopes, incorrect token/introspection endpoint URLs), or using a public client setup with `flask-oidc` which often expects a `client_secret`.
fix
1. Verify your `client_secrets.json` file is correctly formatted and contains accurate `client_id`, `client_secret` (if it's a confidential client), `issuer`, `auth_uri`, `token_uri`, and `userinfo_uri`. 2. Ensure the `OIDC_SCOPES` configured in your Flask app match the scopes allowed and expected by your Identity Provider. 3. If using a public client with Keycloak or similar, `flask-oidc` may still expect a `client_secret` to be present (even if empty in `client_secrets.json`), but the provider might reject it if it's truly a public client that doesn't use client secrets for token exchange. Verify the OIDC provider's specific requirements for public vs. confidential clients and the client registration details.
Upgrade
Version history
2.4.0latest on PyPI · released Jun 16, 2025
Audit
Dependencies
FlaskrequiredCore web framework dependency.
AuthlibrequiredUnderlying OAuth 2.0 and OpenID Connect implementation, Flask-OIDC was rebased on Authlib in version 2.0.0.
requestsrequiredHTTP client library used internally.
blinkerrequiredFast, simple object-to-object and broadcast signaling.
Agent activity
23 hits · last 30 days
node
20
OpenAI (training)
1
Resources