Authlib is a Python library that makes implementing OAuth 2.0 and OpenID Connect (OIDC) in Flask applications feel almost trivial.
Let’s see it in action. Imagine we want to add "Login with Google" to a Flask app.
First, the client-side setup in Flask.
from flask import Flask, redirect, url_for, session
from authlib.integrations.flask_client import OAuth
app = Flask(__name__)
app.secret_key = 'super_secret_key_change_me' # Important for session management
oauth = OAuth(app)
# Configure Google as an OAuth 2.0 provider
oauth.register(
name='google',
client_id='YOUR_GOOGLE_CLIENT_ID',
client_secret='YOUR_GOOGLE_CLIENT_SECRET',
access_token_url='https://oauth2.googleapis.com/token',
authorize_url='https://accounts.google.com/o/oauth2/auth',
client_kwargs={'scope': 'openid email profile'},
)
@app.route('/')
def index():
if 'google_token' in session:
# User is logged in
user_info = oauth.google.get('userinfo').json()
return f'Hello, {user_info["name"]}! <a href="/logout">Logout</a>'
else:
# User is not logged in
return '<a href="/login/google">Login with Google</a>'
@app.route('/login/google')
def login_google():
redirect_uri = url_for('authorize_google', _external=True)
return oauth.google.authorize_redirect(redirect_uri)
@app.route('/authorize/google')
def authorize_google():
token = oauth.google.authorize_access_token()
session['google_token'] = token # Store the token in the session
return redirect(url_for('index'))
@app.route('/logout')
def logout():
session.pop('google_token', None) # Remove token from session
return redirect(url_for('index'))
if __name__ == '__main__':
app.run(debug=True)
To make this work, you’ll need to:
- Create a Google Cloud Project: Go to the Google Cloud Console, create a new project, and enable the "Google People API".
- Create OAuth 2.0 Credentials: In your project, navigate to "APIs & Services" -> "Credentials". Create an "OAuth client ID" for a "Web application".
- You’ll get a
client_idandclient_secret. - Crucially, add your redirect URI: For local development, this will likely be
http://127.0.0.1:5000/authorize/google. Make sure this matches theredirect_uriin yourauthorize_googlefunction.
- You’ll get a
- Replace Placeholders: Substitute
YOUR_GOOGLE_CLIENT_IDandYOUR_GOOGLE_CLIENT_SECRETin the code with your actual credentials. - Install Authlib:
pip install authlib
When a user clicks "Login with Google":
/login/googleis hit.oauth.google.authorize_redirectconstructs a URL for Google’s authorization server, including your client ID and the redirect URI. It sends the user’s browser there.- Google prompts the user to grant your application access to their profile information (email, name, etc., as defined by the
scope). - If the user approves, Google redirects them back to your specified
redirect_uri(/authorize/google) with an authorization code. /authorize/googleis hit.oauth.google.authorize_access_tokentakes this code, exchanges it with Google’s token endpoint for an access token and a refresh token.- The
tokendictionary is stored in the Flasksession(which is whyapp.secret_keyis vital). - The user is redirected back to the index page, now logged in.
The most surprising thing is how little code Authlib requires to handle the entire OAuth 2.0 flow, including token refreshing and scope management, because it abstracts away the complexities of the OAuth 2.0 specification. You’re not manually crafting HTTP requests to Google’s API endpoints; Authlib does that for you, using the configuration you provide.
The client_kwargs={'scope': 'openid email profile'} is where you define what permissions your application is requesting. openid is essential for OpenID Connect, which allows you to verify the user’s identity and get basic profile information. email and profile are standard OAuth scopes that grant access to the user’s email address and basic profile information, respectively. When you make subsequent requests using oauth.google.get('userinfo'), Authlib automatically includes the access token in the Authorization: Bearer <access_token> header.
The next step is often implementing a refresh token flow to automatically re-authenticate users when their access tokens expire, without requiring them to log in again.