Okay, let's break down how flask_oidc.OpenIDConnect works.
The Goal:
flask_oidc is a Flask extension designed to simplify the process of adding OpenID Connect (OIDC) authentication to your Flask web application. OIDC is an identity layer built on top of the OAuth 2.0 protocol. It allows clients (like your Flask app) to verify the identity of an end-user based on authentication performed by an Authorization Server (also called an OpenID Provider or OP - e.g., Google, Okta, Keycloak, Auth0), as well as obtain basic profile information about the user.
Core Concept: The Authorization Code Flow (Simplified)
flask_oidc primarily implements the OIDC Authorization Code Flow, which is the standard and most secure flow for web applications. Here's a step-by-step breakdown of how it works with flask_oidc:
-
Initialization:
- You initialize the
OpenIDConnect extension, typically passing your Flask app object to it.
oidc = OpenIDConnect(app)
- You configure
flask_oidc using Flask's configuration system (app.config). Key settings include:
OIDC_CLIENT_SECRETS: Path to a JSON file containing your client ID, client secret, and provider URLs (authorization endpoint, token endpoint, userinfo endpoint, issuer URL). Often, this file also contains the discovery URL (.well-known/openid-configuration) which flask_oidc can use to automatically find the necessary endpoints.
OIDC_SCOPES: The OIDC scopes you are requesting (e.g., ['openid', 'email', 'profile']). openid is mandatory for OIDC.
OIDC_CALLBACK_ROUTE: The route in your Flask application where the OpenID Provider will redirect the user back after authentication.
SECRET_KEY: Flask's secret key, crucial for session security where tokens are often stored.
-
Protecting a Route:
- You use the
@oidc.require_login decorator on Flask view functions (routes) that require authentication.
@app.route('/profile')
@oidc.require_login
def profile():
# ... access user info ...
return render_template('profile.html')
-
Authentication Trigger: