Flask-Dance

7.1.0 · active · verified Sat Apr 11

Flask-Dance is a Python library that simplifies OAuth authentication for Flask applications. It enables Flask apps to act as OAuth consumers, allowing users to log in with various third-party providers like GitHub, Google, and more. The library is actively maintained with frequent updates, currently at version 7.1.0.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up a Flask application with GitHub OAuth using Flask-Dance. It registers a GitHub blueprint, which handles the OAuth flow. The root route checks if the user is authorized; if not, it redirects them to the GitHub login page. Once authorized, it fetches and displays the GitHub username. Ensure to set `FLASK_SECRET_KEY`, `GITHUB_OAUTH_CLIENT_ID`, and `GITHUB_OAUTH_CLIENT_SECRET` environment variables. For local development without HTTPS, `OAUTHLIB_INSECURE_TRANSPORT=1` must be set.

import os
from flask import Flask, redirect, url_for, session
from flask_dance.contrib.github import make_github_blueprint, github

app = Flask(__name__)
app.secret_key = os.environ.get("FLASK_SECRET_KEY", "supersekrit")

github_blueprint = make_github_blueprint(
    client_id=os.environ.get("GITHUB_OAUTH_CLIENT_ID"),
    client_secret=os.environ.get("GITHUB_OAUTH_CLIENT_SECRET"),
)
app.register_blueprint(github_blueprint, url_prefix="/login")

@app.route("/")
def index():
    if not github.authorized:
        return redirect(url_for("github.login"))
    resp = github.get("/user")
    assert resp.ok, resp.text
    return f"You are @{resp.json()['login']} on GitHub"

if __name__ == "__main__":
    # For local development with HTTP, set OAUTHLIB_INSECURE_TRANSPORT=1
    # Example: export OAUTHLIB_INSECURE_TRANSPORT=1
    app.run(debug=True)

view raw JSON →