How to Implement OAuth in Flask: Simple Guide with Example
To implement
OAuth in Flask, use the Flask-Dance library which simplifies OAuth integration with providers like Google or GitHub. You set up an OAuth blueprint, register it with your Flask app, and handle user login via the provider's authorization flow.Syntax
Use Flask-Dance to create an OAuth blueprint for your provider. Then register this blueprint with your Flask app. The main parts are:
make_: creates OAuth setup for the provider._blueprint() app.register_blueprint(): adds OAuth routes to your app.- Use
@app.routeto protect routes and check login status.
python
from flask import Flask, redirect, url_for from flask_dance.contrib.github import make_github_blueprint, github app = Flask(__name__) app.secret_key = "supersekrit" github_bp = make_github_blueprint(client_id="your-client-id", client_secret="your-client-secret") app.register_blueprint(github_bp, url_prefix="/login") @app.route("/") def index(): if not github.authorized: return redirect(url_for("github.login")) resp = github.get("user") assert resp.ok return f"You are @{resp.json()['login']} on GitHub"
Example
This example shows a Flask app using GitHub OAuth. When you visit the home page, it redirects you to GitHub to log in. After login, it shows your GitHub username.
python
from flask import Flask, redirect, url_for from flask_dance.contrib.github import make_github_blueprint, github app = Flask(__name__) app.secret_key = "supersekrit" github_bp = make_github_blueprint( client_id="your-client-id", client_secret="your-client-secret", ) app.register_blueprint(github_bp, url_prefix="/login") @app.route("/") def index(): if not github.authorized: return redirect(url_for("github.login")) resp = github.get("user") if not resp.ok: return "Failed to fetch user info." username = resp.json()["login"] return f"You are logged in as @{username} on GitHub" if __name__ == "__main__": app.run(debug=True)
Output
Running the app and visiting '/' redirects to GitHub login. After login, the page shows: You are logged in as @your-github-username on GitHub
Common Pitfalls
- Forgetting to set
app.secret_keycauses session errors. - Not registering the OAuth blueprint with
app.register_blueprint()means OAuth routes won't work. - Using wrong client ID or secret leads to authorization failure.
- Not handling the case when user denies permission causes errors.
- Not checking
github.authorizedbefore API calls can cause crashes.
python
from flask import Flask, redirect, url_for from flask_dance.contrib.github import make_github_blueprint, github app = Flask(__name__) # Missing secret key causes session issues # app.secret_key = "supersekrit" github_bp = make_github_blueprint(client_id="wrong-id", client_secret="wrong-secret") # Forgot to register blueprint # app.register_blueprint(github_bp, url_prefix="/login") @app.route("/") def index(): # Not checking if authorized resp = github.get("user") if not resp.ok: return "Failed to fetch user info." username = resp.json()["login"] return f"You are logged in as @{username} on GitHub" # Correct way: # 1. Set app.secret_key # 2. Register blueprint # 3. Check github.authorized before API calls # 4. Handle denied permissions gracefully
Quick Reference
OAuth with Flask-Dance Cheat Sheet:
- Install:
pip install flask-dance - Create OAuth blueprint:
make__blueprint(client_id, client_secret) - Register blueprint:
app.register_blueprint(blueprint, url_prefix='/login') - Check login:
if not provider.authorized - Fetch user info:
provider.get('user') - Set
app.secret_keyfor sessions
Key Takeaways
Use Flask-Dance to simplify OAuth integration in Flask apps.
Always set app.secret_key to enable secure sessions.
Register the OAuth blueprint to add login routes.
Check if the user is authorized before accessing provider APIs.
Handle login denial and errors gracefully to avoid crashes.