Flask-Dance

Doing the OAuth dance with style using Flask, requests, and oauthlib. Currently, only OAuth consumers are supported, but this project could easily support OAuth providers in the future, as well.

User Guide:

Quickstarts

Contents:

GitHub Quickstart

Setup Application

Visit https://github.com/settings/applications/new to register an application on GitHub. The application’s “authorization callback URL” must be http://localhost:5000/login/github/authorized. Take note of the “Client ID” and “Client Secret” for the application.

Code

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

app = Flask(__name__)
app.secret_key = "supersekrit"
blueprint = make_github_blueprint(
    client_id="my-key-here",
    client_secret="my-secret-here",
)
app.register_blueprint(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
    return "You are @{login} on GitHub".format(login=resp.json()["login"])

if __name__ == "__main__":
    app.run()

Note

You must replace my-key-here and my-secret-here with the client ID and client secret that you got from your GitHub application.

Note

If you are running this code on Heroku, you’ll need to use the werkzeug.contrib.fixers.ProxyFix middleware. See Proxies and HTTPS.

When you run this code, you must set the OAUTHLIB_INSECURE_TRANSPORT environment variable for it to work. For example, if you put this code in a file named github.py, you could run:

$ export OAUTHLIB_INSECURE_TRANSPORT=1
$ python github.py

Visit localhost:5000 in your browser, and you should start the OAuth dance immediately.

Warning

Do NOT set OAUTHLIB_INSECURE_TRANSPORT in production. Setting this variable allows you to use insecure http for OAuth communication. However, for security, all OAuth interactions must occur over secure https when running in production.

Explanation

This code makes a blueprint that implements the views necessary to be a consumer in the OAuth dance. The blueprint has two views: /github, which is the view that the user visits to begin the OAuth dance, and /github/authorized, which is the view that the user is redirected to at the end of the OAuth dance. Because we set the url_prefix to be /login, the end result is that the views are at /login/github and /login/github/authorized. The second view is the “authorized callback URL” that you must tell GitHub about when you create the application.

The github variable is a requests.Session instance, which will be be preloaded with the user’s access token once the user has gone through the OAuth dance. You can check the github.authorized boolean to determine if the access token is loaded. Whether the access token is loaded or not, you can use all the normal requests methods, like get() and post(), to make HTTP requests. If you only specify the path component of the URL, the domain will default to https://api.github.com.

Google Quickstart

Setup Application

Visit the Google Developers Console at https://console.developers.google.com and create a new project. In the “APIs & auth” section, click on “Credentials”, and then click the “Create a new Client ID” button. Select “Web Application” for the application type, and click the “Configure consent screen” button. Put in your application information, and click Save. Once you’ve done that, you’ll see two new fields: “Authorized JavaScript origins” and “Authorized redirect URIs”. Put http://localhost:5000/login/google/authorized into “Authorized redirect URIs”, and click “Create Client ID”. Take note of the “Client ID” and “Client Secret” for the application. As a final step, in the “APIs” section, enable the “Google+ API”.

Code

from flask import Flask, redirect, url_for
from flask_dance.contrib.google import make_google_blueprint, google

app = Flask(__name__)
app.secret_key = "supersekrit"
blueprint = make_google_blueprint(
    client_id="my-key-here",
    client_secret="my-secret-here",
    scope=["profile", "email"]
)
app.register_blueprint(blueprint, url_prefix="/login")

@app.route("/")
def index():
    if not google.authorized:
        return redirect(url_for("google.login"))
    resp = google.get("/plus/v1/people/me")
    assert resp.ok, resp.text
    return "You are {email} on Google".format(email=resp.json()["emails"][0]["value"])

if __name__ == "__main__":
    app.run()

Note

You must replace my-key-here and my-secret-here with the client ID and client secret that you got from your Google application.

Note

If you are running this code on Heroku, you’ll need to use the werkzeug.contrib.fixers.ProxyFix middleware. See Proxies and HTTPS.

When you run this code locally, you must set the OAUTHLIB_INSECURE_TRANSPORT environment variable for it to work. You also must set the OAUTHLIB_RELAX_TOKEN_SCOPE environment variable to account for Google changing the requested OAuth scopes on you. For example, if you put this code in a file named google.py, you could run:

$ export OAUTHLIB_INSECURE_TRANSPORT=1
$ export OAUTHLIB_RELAX_TOKEN_SCOPE=1
$ python google.py

Visit localhost:5000 in your browser, and you should start the OAuth dance immediately.

Warning

Do NOT set OAUTHLIB_INSECURE_TRANSPORT in production. Setting this variable allows you to use insecure http for OAuth communication. However, for security, all OAuth interactions must occur over secure https when running in production.

However, you can (and probably should) set OAUTHLIB_RELAX_TOKEN_SCOPE when running in production.

Explanation

This code makes a blueprint that implements the views necessary to be a consumer in the OAuth dance. The blueprint has two views: /google, which is the view that the user visits to begin the OAuth dance, and /google/authorized, which is the view that the user is redirected to at the end of the OAuth dance. Because we set the url_prefix to be /login, the end result is that the views are at /login/google and /login/google/authorized. The second view is the “authorized redirect URI” that you must tell Google about when you create the application.

The google variable is a requests.Session instance, which will be be preloaded with the user’s access token once the user has gone through the OAuth dance. You can check the google.authorized boolean to determine if the access token is loaded. Whether the access token is loaded or not, you can use all the normal requests methods, like get() and post(), to make HTTP requests. If you only specify the path component of the URL, the domain will default to https://www.googleapis.com.

Twitter Quickstart

Setup Application

Go to Twitter Application Manager at https://apps.twitter.com and create a new app. The application’s “Callback URL” must be http://localhost:5000/login/twitter/authorized. Take note of the “API Key” and “API Secret” for the application.

Code

from flask import Flask, redirect, url_for
from flask_dance.contrib.twitter import make_twitter_blueprint, twitter

app = Flask(__name__)
app.secret_key = "supersekrit"
blueprint = make_twitter_blueprint(
    api_key="my-key-here",
    api_secret="my-secret-here",
)
app.register_blueprint(blueprint, url_prefix="/login")

@app.route("/")
def index():
    if not twitter.authorized:
        return redirect(url_for("twitter.login"))
    resp = twitter.get("account/settings.json")
    assert resp.ok
    return "You are @{screen_name} on Twitter".format(screen_name=resp.json()["screen_name"])

if __name__ == "__main__":
    app.run()

Note

You must replace my-key-here and my-secret-here with the API key and API secret that you got from your Twitter application.

Note

If you are running this code on Heroku, you’ll need to use the werkzeug.contrib.fixers.ProxyFix middleware. See Proxies and HTTPS.

When you run this code locally, you must set the OAUTHLIB_INSECURE_TRANSPORT environment variable for it to work. For example, if you put this code in a file named twitter.py, you could run:

$ export OAUTHLIB_INSECURE_TRANSPORT=1
$ python twitter.py

Visit localhost:5000 in your browser, and you should start the OAuth dance immediately.

Warning

Do NOT set OAUTHLIB_INSECURE_TRANSPORT in production. Setting this variable allows you to use insecure http for OAuth communication. However, for security, all OAuth interactions must occur over secure https when running in production.

Explanation

This code makes a blueprint that implements the views necessary to be a consumer in the OAuth dance. The blueprint has two views: /twitter, which is the view that the user visits to begin the OAuth dance, and /twitter/authorized, which is the view that the user is redirected to at the end of the OAuth dance. Because we set the url_prefix to be /login, the end result is that the views are at /login/twitter and /login/twitter/authorized. The second view is the “Callback URL” that you must tell Twitter about when you create the application.

The twitter variable is a requests.Session instance, which will be be preloaded with the user’s access token once the user has gone through the OAuth dance. You can check the twitter.authorized boolean to determine if the access token is loaded. Whether the access token is loaded or not, you can use all the normal requests methods, like get() and post(), to make HTTP requests. If you only specify the path component of the URL, the domain will default to https://www.googleapis.com.

Dropbox Quickstart

Setup Application

Visit the Dropbox App Console at https://www.dropbox.com/developers/apps and create a new app. Select “Dropbox API app”, not “Drop-ins app”. Decide if your app can be limited to its own folder, provide an app name, and agree to the terms of service. Once the app has been created, you need to add at least one redirect URI under the OAuth 2 section: put in http://localhost:5000/login/dropbox/authorized and click Add. Take note of the “App key” and “App Secret” for the application.

Code

from flask import Flask, redirect, url_for
from flask_dance.contrib.dropbox import make_dropbox_blueprint, dropbox

app = Flask(__name__)
app.secret_key = "supersekrit"
blueprint = make_dropbox_blueprint(
    app_key="my-key-here",
    app_secret="my-secret-here",
)
app.register_blueprint(blueprint, url_prefix="/login")

@app.route("/")
def index():
    if not dropbox.authorized:
        return redirect(url_for("dropbox.login"))
    resp = dropbox.get("account/info")
    assert resp.ok
    return "You are {email} on Dropbox".format(email=resp.json()["email"])

if __name__ == "__main__":
    app.run()

Note

You must replace my-key-here and my-secret-here with the client ID and client secret that you got from your Dropbox application.

Note

If you are running this code on Heroku, you’ll need to use the werkzeug.contrib.fixers.ProxyFix middleware. See Proxies and HTTPS.

When you run this code locally, you must set the OAUTHLIB_INSECURE_TRANSPORT environment variable for it to work. For example, if you put this code in a file named dropbox.py, you could run:

$ export OAUTHLIB_RELAX_TOKEN_SCOPE=1
$ python dropbox.py

Visit localhost:5000 in your browser, and you should start the OAuth dance immediately.

Warning

Do NOT set OAUTHLIB_INSECURE_TRANSPORT in production. Setting this variable allows you to use insecure http for OAuth communication. However, for security, all OAuth interactions must occur over secure https when running in production.

Explanation

This code makes a blueprint that implements the views necessary to be a consumer in the OAuth dance. The blueprint has two views: /dropbox, which is the view that the user visits to begin the OAuth dance, and /dropbox/authorized, which is the view that the user is redirected to at the end of the OAuth dance. Because we set the url_prefix to be /login, the end result is that the views are at /login/dropbox and /login/dropbox/authorized. The second view is the “redirect URI” that you must tell Dropbox about when you create the app.

The dropbox variable is a requests.Session instance, which will be be preloaded with the user’s access token once the user has gone through the OAuth dance. You can check the dropbox.authorized boolean to determine if the access token is loaded. Whether the access token is loaded or not, you can use all the normal requests methods, like get() and post(), to make HTTP requests. If you only specify the path component of the URL, the domain will default to https://api.dropbox.com.

Meetup Quickstart

Setup Application

Visit the Meetup OAuth Consumer page at https://secure.meetup.com/meetup_api/oauth_consumers/ and create a new consumer. Put in http://localhost:5000/login/meetup/authorized for the redirect URI. Agree to the terms of service, and register your consumer to get an OAuth key and secret.

Code

from flask import Flask, redirect, url_for
from flask_dance.contrib.meetup import make_meetup_blueprint, meetup

app = Flask(__name__)
app.secret_key = "supersekrit"
blueprint = make_meetup_blueprint(
    key="my-key-here",
    secret="my-secret-here",
)
app.register_blueprint(blueprint, url_prefix="/login")

@app.route("/")
def index():
    if not meetup.authorized:
        return redirect(url_for("meetup.login"))
    resp = meetup.get("member/self")
    assert resp.ok
    return "You are {name} on Meetup".format(name=resp.json()["name"])

if __name__ == "__main__":
    app.run()

Note

You must replace my-key-here and my-secret-here with the client ID and client secret that you got from your Meetup application.

Note

If you are running this code on Heroku, you’ll need to use the werkzeug.contrib.fixers.ProxyFix middleware. See Proxies and HTTPS.

When you run this code locally, you must set the OAUTHLIB_INSECURE_TRANSPORT environment variable for it to work. For example, if you put this code in a file named meetup.py, you could run:

$ export OAUTHLIB_RELAX_TOKEN_SCOPE=1
$ python meetup.py

Visit localhost:5000 in your browser, and you should start the OAuth dance immediately.

Warning

Do NOT set OAUTHLIB_INSECURE_TRANSPORT in production. Setting this variable allows you to use insecure http for OAuth communication. However, for security, all OAuth interactions must occur over secure https when running in production.

Explanation

This code makes a blueprint that implements the views necessary to be a consumer in the OAuth dance. The blueprint has two views: /meetup, which is the view that the user visits to begin the OAuth dance, and /meetup/authorized, which is the view that the user is redirected to at the end of the OAuth dance. Because we set the url_prefix to be /login, the end result is that the views are at /login/meetup and /login/meetup/authorized. The second view is the “redirect URI” that you must tell Meetup about when you create the app.

The meetup variable is a requests.Session instance, which will be be preloaded with the user’s access token once the user has gone through the OAuth dance. You can check the meetup.authorized boolean to determine if the access token is loaded. Whether the access token is loaded or not, you can use all the normal requests methods, like get() and post(), to make HTTP requests. If you only specify the path component of the URL, the domain will default to https://api.meetup.com.

SQLAlchemy Multi-User Quickstart

This quickstart will help you get started with a multi-user application where OAuth tokens are stored using the SQLAlchemy backend. You should already be familiar with setting up a single-use Flask-Dance application – you can consult some of the other quickstarts for that.

Code

Create a file called multi.py with the following contents:

import sys
from flask import Flask, redirect, url_for, flash, render_template
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm.exc import NoResultFound
from flask_dance.contrib.github import make_github_blueprint, github
from flask_dance.consumer.backend.sqla import OAuthConsumerMixin, SQLAlchemyBackend
from flask_dance.consumer import oauth_authorized, oauth_error
from flask_login import (
    LoginManager, UserMixin, current_user,
    login_required, login_user, logout_user
)

# setup Flask application
app = Flask(__name__)
app.secret_key = "supersekrit"
blueprint = make_github_blueprint(
    client_id="my-key-here",
    client_secret="my-secret-here",
)
app.register_blueprint(blueprint, url_prefix="/login")

# setup database models
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///multi.db"
db = SQLAlchemy()

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(256), unique=True)
    # ... other columns as needed

class OAuth(db.Model, OAuthConsumerMixin):
    user_id = db.Column(db.Integer, db.ForeignKey(User.id))
    user = db.relationship(User)

# setup login manager
login_manager = LoginManager()
login_manager.login_view = 'github.login'

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

# setup SQLAlchemy backend
blueprint.backend = SQLAlchemyBackend(OAuth, db.session, user=current_user)

# create/login local user on successful OAuth login
@oauth_authorized.connect_via(blueprint)
def github_logged_in(blueprint, token):
    if not token:
        flash("Failed to log in with {name}".format(name=blueprint.name))
        return
    # figure out who the user is
    resp = blueprint.session.get("/user")
    if resp.ok:
        username = resp.json()["login"]
        query = User.query.filter_by(username=username)
        try:
            user = query.one()
        except NoResultFound:
            # create a user
            user = User(username=username)
            db.session.add(user)
            db.session.commit()
        login_user(user)
        flash("Successfully signed in with GitHub")
    else:
        msg = "Failed to fetch user info from {name}".format(name=blueprint.name)
        flash(msg, category="error")

# notify on OAuth provider error
@oauth_error.connect_via(blueprint)
def github_error(blueprint, error, error_description=None, error_uri=None):
    msg = (
        "OAuth error from {name}! "
        "error={error} description={description} uri={uri}"
    ).format(
        name=blueprint.name,
        error=error,
        description=error_description,
        uri=error_uri,
    )
    flash(msg, category="error")

@app.route("/logout")
@login_required
def logout():
    logout_user()
    flash("You have logged out")
    return redirect(url_for("index"))

@app.route("/")
def index():
    return render_template("home.html")

# hook up extensions to app
db.init_app(app)
login_manager.init_app(app)

if __name__ == "__main__":
    if "--setup" in sys.argv:
        with app.app_context():
            db.create_all()
            db.session.commit()
            print("Database tables created")
    else:
        app.run(debug=True)

Make a templates directory next to multi.py. In that directory, create a file called home.html with the following contents:

<!DOCTYPE html>
<head>
    <title>Flask-Dance Multi-User SQLAlchemy</title>
</head>
<body>
{% with messages = get_flashed_messages(with_categories=true) %}
  {% if messages %}
    <ul class="flash">
    {% for category, message in messages %}
      <li class="{{ category }}">{{ message }}</li>
    {% endfor %}
    </ul>
  {% endif %}
{% endwith %}
{% if current_user.is_authenticated() %}
  You are logged in as {{ current_user.username }}!
  <a href="{{ url_for("logout") }}">Log out</a>
{% else %}
  You are not logged in.
  <a href="{{ url_for("github.login") }}">Log in</a>
{% endif %}
</body>

For this to work properly, you must also do these things:

  1. Register an application with GitHub, where the “authorization callback URL” is http://localhost:5000/login/github/authorized
  2. Replace my-key-here and my-secret-here with the client ID and client secret that you got from your GitHub application
  3. Install Flask-Dance, Flask-SQLAlchemy, Flask-Login, and blinker
  4. Run python multi.py --setup to create your sqlite database
  5. Set the OAUTHLIB_INSECURE_TRANSPORT environment variable, so OAuthlib doesn’t complain about running over http (for testing only!)
  6. Run python multi.py to run the application, and visit http://localhost:5000 in your browser.

Explanation

There’s a lot going on here, so let’s break it down. This code uses Flask-Dance, Flask-SQLAlchemy for a database, and Flask-Login for user management. It also hooks into several signals, powered by the blinker library.

# setup Flask application
app = Flask(__name__)
app.secret_key = "supersekrit"
blueprint = make_github_blueprint(
    client_id="my-key-here",
    client_secret="my-secret-here",
)
app.register_blueprint(blueprint, url_prefix="/login")

This is the standard pattern for creating a Flask-Dance blueprint and attaching it to your Flask application.

# setup database models
app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///multi.db"
db = SQLAlchemy()

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(256), unique=True)
    # ... other columns as needed

class OAuth(db.Model, OAuthConsumerMixin):
    user_id = db.Column(db.Integer, db.ForeignKey(User.id))
    user = db.relationship(User)

This code sets up Flask-SQLAlchemy, and configures it to use a sqlite database called multi.db. You can change this to use any database that SQLAlchemy supports. This code also defines two database models: a User model that inherits from flask_login.UserMixin (to ensure it has the methods that Flask-Login expects), and an OAuth model for actually storing OAuth tokens.

# setup login manager
login_manager = LoginManager()
login_manager.login_view = 'github.login'

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

This code sets up Flask-Login, informing it about our User model and the “github.login” view, so that it can properly redirect users if they try to access views that are login-protected.

# setup SQLAlchemy backend
blueprint.backend = SQLAlchemyBackend(OAuth, db.session, user=current_user)

This code hooks up the SQLAlchemyBackend backend to Flask-Dance, so that it can store OAuth tokens in the database. Notice that we also pass user=current_user, where current_user is a proxy provided by Flask-Login. This will ensure that OAuth tokens are scoped to individual users.

# create/login local user on successful OAuth login
@oauth_authorized.connect_via(blueprint)
def github_logged_in(blueprint, token):
    if not token:
        flash("Failed to log in with {name}".format(name=blueprint.name))
        return
    # figure out who the user is
    resp = blueprint.session.get("/user")
    if resp.ok:
        username = resp.json()["login"]
        query = User.query.filter_by(username=username)
        try:
            user = query.one()
        except NoResultFound:
            # create a user
            user = User(username=username)
            db.session.add(user)
            db.session.commit()
        login_user(user)
        flash("Successfully signed in with GitHub")
    else:
        msg = "Failed to fetch user info from {name}".format(name=blueprint.name)
        flash(msg, category="error")

This code hooks into the oauth_authorized signal, which is triggered when a user successfully completes the OAuth dance. We make an HTTP request to GitHub using blueprint.session, which already has the OAuth token loaded, in order to determine some basic information for the user, like their GitHub username. Then we look up in our local database to see if we already have a user with that username – if not, we create a new user. We then log that user in, using Flask-Login’s login_user() function.

We also use the flash() function to display status messages to the user, so that they understand that they’ve just logged in. Good feedback to the user is crucial for a good user experience.

# notify on OAuth provider error
@oauth_error.connect_via(blueprint)
def github_error(blueprint, error, error_description=None, error_uri=None):
    msg = (
        "OAuth error from {name}! "
        "error={error} description={description} uri={uri}"
    ).format(
        name=blueprint.name,
        error=error,
        description=error_description,
        uri=error_uri,
    )
    flash(msg, category="error")

Sometimes, the OAuth provider may throw an error message instead of allowing the OAuth dance to complete successfully. If so, Flask-Dance will redirect the user just as though the dance did complete successfully, so it is crucial to provide feedback to the user by hooking into the oauth_error signal.

@app.route("/logout")
@login_required
def logout():
    logout_user()
    flash("You have logged out")
    return redirect(url_for("index"))

@app.route("/")
def index():
    return render_template("home.html")

This code sets up some routes for our application: a logout route, so that users can choose to log out of their user account, and an index route, so that there’s something to see in the application.

# hook up extensions to app
db.init_app(app)
login_manager.init_app(app)

Since we set up the Flask-SQLAlchemy and Flask-Login extensions initally without passing the application object, we have to pass the app to them after they’ve been fully configured. This is called the application factory pattern.

if __name__ == "__main__":
    if "--setup" in sys.argv:
        with app.app_context():
            db.create_all()
            db.session.commit()
            print("Database tables created")
    else:
        app.run(debug=True)

We need a way to set up the database tables before the application is run, so this code checks for a --setup flag when running the code, and if so it sets up the database tables instead of running the application. Note that the application is running in debug mode – be sure to turn this off before running your application in production!

Providers

Flask-Dance comes with pre-set OAuth consumer configurations for a few popular OAuth providers. Flask-Dance also works with providers that aren’t in this list: see the Custom section at the bottom of the page. We also welcome pull requests to add new pre-set provider configurations to Flask-Dance!

Facebook

flask_dance.contrib.facebook.make_facebook_blueprint(client_id=None, client_secret=None, scope=None, redirect_url=None, redirect_to=None, login_url=None, authorized_url=None, session_class=None, backend=None)[source]

Make a blueprint for authenticating with Facebook using OAuth 2. This requires a client ID and client secret from Facebook. You should either pass them to this constructor, or make sure that your Flask application config defines them, using the variables FACEBOOK_OAUTH_CLIENT_ID and FACEBOOK_OAUTH_CLIENT_SECRET.

Parameters:
  • client_id (str) – The client ID for your application on Facebook.
  • client_secret (str) – The client secret for your application on Facebook
  • scope (str, optional) – comma-separated list of scopes for the OAuth token
  • redirect_url (str) – the URL to redirect to after the authentication dance is complete
  • redirect_to (str) – if redirect_url is not defined, the name of the view to redirect to after the authentication dance is complete. The actual URL will be determined by flask.url_for()
  • login_url (str, optional) – the URL path for the login view. Defaults to /facebook
  • authorized_url (str, optional) – the URL path for the authorized view. Defaults to /facebook/authorized.
  • session_class (class, optional) – The class to use for creating a Requests session. Defaults to OAuth2Session.
  • backend – A storage backend class, or an instance of a storage backend class, to use for this blueprint. Defaults to SessionBackend.
Return type:

OAuth2ConsumerBlueprint

Returns:

A blueprint to attach to your Flask app.

flask_dance.contrib.facebook.facebook

A LocalProxy to a requests.Session that already has the Facebook authentication token loaded (assuming that the user has authenticated with Facebook at some point in the past).

GitHub

flask_dance.contrib.github.make_github_blueprint(client_id=None, client_secret=None, scope=None, redirect_url=None, redirect_to=None, login_url=None, authorized_url=None, session_class=None, backend=None)[source]

Make a blueprint for authenticating with GitHub using OAuth 2. This requires a client ID and client secret from GitHub. You should either pass them to this constructor, or make sure that your Flask application config defines them, using the variables GITHUB_OAUTH_CLIENT_ID and GITHUB_OAUTH_CLIENT_SECRET.

Parameters:
  • client_id (str) – The client ID for your application on GitHub.
  • client_secret (str) – The client secret for your application on GitHub
  • scope (str, optional) – comma-separated list of scopes for the OAuth token
  • redirect_url (str) – the URL to redirect to after the authentication dance is complete
  • redirect_to (str) – if redirect_url is not defined, the name of the view to redirect to after the authentication dance is complete. The actual URL will be determined by flask.url_for()
  • login_url (str, optional) – the URL path for the login view. Defaults to /github
  • authorized_url (str, optional) – the URL path for the authorized view. Defaults to /github/authorized.
  • session_class (class, optional) – The class to use for creating a Requests session. Defaults to OAuth2Session.
  • backend – A storage backend class, or an instance of a storage backend class, to use for this blueprint. Defaults to SessionBackend.
Return type:

OAuth2ConsumerBlueprint

Returns:

A blueprint to attach to your Flask app.

flask_dance.contrib.github.github

A LocalProxy to a requests.Session that already has the GitHub authentication token loaded (assuming that the user has authenticated with GitHub at some point in the past).

Google

flask_dance.contrib.google.make_google_blueprint(client_id=None, client_secret=None, scope=None, offline=False, reprompt_consent=False, redirect_url=None, redirect_to=None, login_url=None, authorized_url=None, session_class=None, backend=None)[source]

Make a blueprint for authenticating with Google using OAuth 2. This requires a client ID and client secret from Google. You should either pass them to this constructor, or make sure that your Flask application config defines them, using the variables GOOGLE_OAUTH_CLIENT_ID and GOOGLE_OAUTH_CLIENT_SECRET.

Parameters:
  • client_id (str) – The client ID for your application on Google
  • client_secret (str) – The client secret for your application on Google
  • scope (str, optional) – comma-separated list of scopes for the OAuth token. Defaults to the “profile” scope.
  • offline (bool) – Whether to request offline access for the OAuth token. Defaults to False
  • reprompt_consent (bool) – If True, force Google to re-prompt the user for their consent, even if the user has already given their consent. Defaults to False
  • redirect_url (str) – the URL to redirect to after the authentication dance is complete
  • redirect_to (str) – if redirect_url is not defined, the name of the view to redirect to after the authentication dance is complete. The actual URL will be determined by flask.url_for()
  • login_url (str, optional) – the URL path for the login view. Defaults to /google
  • authorized_url (str, optional) – the URL path for the authorized view. Defaults to /google/authorized.
  • session_class (class, optional) – The class to use for creating a Requests session. Defaults to OAuth2Session.
  • backend – A storage backend class, or an instance of a storage backend class, to use for this blueprint. Defaults to SessionBackend.
Return type:

OAuth2ConsumerBlueprint

Returns:

A blueprint to attach to your Flask app.

flask_dance.contrib.google.google

A LocalProxy to a requests.Session that already has the Google authentication token loaded (assuming that the user has authenticated with Google at some point in the past).

Twitter

flask_dance.contrib.twitter.make_twitter_blueprint(api_key=None, api_secret=None, redirect_url=None, redirect_to=None, login_url=None, authorized_url=None, session_class=None, backend=None)[source]

Make a blueprint for authenticating with Twitter using OAuth 1. This requires an API key and API secret from Twitter. You should either pass them to this constructor, or make sure that your Flask application config defines them, using the variables TWITTER_OAUTH_API_KEY and TWITTER_OAUTH_API_SECRET.

Parameters:
  • api_key (str) – The API key for your Twitter application
  • api_secret (str) – The API secret for your Twitter application
  • redirect_url (str) – the URL to redirect to after the authentication dance is complete
  • redirect_to (str) – if redirect_url is not defined, the name of the view to redirect to after the authentication dance is complete. The actual URL will be determined by flask.url_for()
  • login_url (str, optional) – the URL path for the login view. Defaults to /twitter
  • authorized_url (str, optional) – the URL path for the authorized view. Defaults to /twitter/authorized.
  • session_class (class, optional) – The class to use for creating a Requests session. Defaults to OAuth1Session.
  • backend – A storage backend class, or an instance of a storage backend class, to use for this blueprint. Defaults to SessionBackend.
Return type:

OAuth1ConsumerBlueprint

Returns:

A blueprint to attach to your Flask app.

flask_dance.contrib.twitter.twitter

A LocalProxy to a requests.Session that already has the Twitter authentication token loaded (assuming that the user has authenticated with Twitter at some point in the past).

JIRA

flask_dance.contrib.jira.make_jira_blueprint(base_url, consumer_key=None, rsa_key=None, redirect_url=None, redirect_to=None, login_url=None, authorized_url=None, session_class=None, backend=None)[source]

Make a blueprint for authenticating with JIRA using OAuth 1. This requires a consumer key and RSA key for the JIRA appication link. You should either pass them to this constructor, or make sure that your Flask application config defines them, using the variables JIRA_OAUTH_CONSUMER_KEY and JIRA_OAUTH_RSA_KEY.

Parameters:
  • base_url (str) – The base URL of your JIRA installation. For example, for Atlassian’s hosted Cloud JIRA, the base_url would be https://jira.atlassian.com
  • consumer_key (str) – The consumer key for your Application Link on JIRA
  • rsa_key (str or path) – The RSA private key for your Application Link on JIRA. This can be the contents of the key as a string, or a path to the key file on disk.
  • redirect_url (str) – the URL to redirect to after the authentication dance is complete
  • redirect_to (str) – if redirect_url is not defined, the name of the view to redirect to after the authentication dance is complete. The actual URL will be determined by flask.url_for()
  • login_url (str, optional) – the URL path for the login view. Defaults to /jira
  • authorized_url (str, optional) – the URL path for the authorized view. Defaults to /jira/authorized.
  • session_class (class, optional) – The class to use for creating a Requests session. Defaults to JsonOAuth1Session.
  • backend – A storage backend class, or an instance of a storage backend class, to use for this blueprint. Defaults to SessionBackend.
Return type:

OAuth1ConsumerBlueprint

Returns:

A blueprint to attach to your Flask app.

flask_dance.contrib.jira.jira

A LocalProxy to a requests.Session that already has the JIRA authentication token loaded (assuming that the user has authenticated with JIRA at some point in the past).

Dropbox

flask_dance.contrib.dropbox.make_dropbox_blueprint(app_key=None, app_secret=None, scope=None, force_reapprove=False, disable_signup=False, redirect_url=None, redirect_to=None, login_url=None, authorized_url=None, session_class=None, backend=None)[source]

Make a blueprint for authenticating with Dropbox using OAuth 2. This requires a client ID and client secret from Dropbox. You should either pass them to this constructor, or make sure that your Flask application config defines them, using the variables DROPBOX_OAUTH_APP_KEY and DROPBOX_OAUTH_APP_SECRET.

Parameters:
  • app_key (str) – The client ID for your application on Dropbox.
  • app_secret (str) – The client secret for your application on Dropbox
  • scope (str, optional) – comma-separated list of scopes for the OAuth token
  • redirect_url (str) – the URL to redirect to after the authentication dance is complete
  • redirect_to (str) – if redirect_url is not defined, the name of the view to redirect to after the authentication dance is complete. The actual URL will be determined by flask.url_for()
  • login_url (str, optional) – the URL path for the login view. Defaults to /meetup
  • authorized_url (str, optional) – the URL path for the authorized view. Defaults to /meetup/authorized.
  • session_class (class, optional) – The class to use for creating a Requests session. Defaults to OAuth2Session.
  • backend – A storage backend class, or an instance of a storage backend class, to use for this blueprint. Defaults to SessionBackend.
Return type:

OAuth2ConsumerBlueprint

Returns:

A blueprint to attach to your Flask app.

flask_dance.contrib.dropbox.dropbox

A LocalProxy to a requests.Session that already has the Dropbox authentication token loaded (assuming that the user has authenticated with Dropbox at some point in the past).

Meetup

flask_dance.contrib.meetup.make_meetup_blueprint(key=None, secret=None, scope=None, redirect_url=None, redirect_to=None, login_url=None, authorized_url=None, session_class=None, backend=None)[source]

Make a blueprint for authenticating with Meetup using OAuth 2. This requires an OAuth consumer from Meetup. You should either pass the key and secret to this constructor, or make sure that your Flask application config defines them, using the variables MEETUP_OAUTH_KEY and MEETUP_OAUTH_SECRET.

Parameters:
  • key (str) – The OAuth consumer key for your application on Meetup
  • secret (str) – The OAuth consumer secret for your application on Meetup
  • scope (str, optional) – comma-separated list of scopes for the OAuth token
  • redirect_url (str) – the URL to redirect to after the authentication dance is complete
  • redirect_to (str) – if redirect_url is not defined, the name of the view to redirect to after the authentication dance is complete. The actual URL will be determined by flask.url_for()
  • login_url (str, optional) – the URL path for the login view. Defaults to /meetup
  • authorized_url (str, optional) – the URL path for the authorized view. Defaults to /meetup/authorized.
  • session_class (class, optional) – The class to use for creating a Requests session. Defaults to OAuth2Session.
  • backend – A storage backend class, or an instance of a storage backend class, to use for this blueprint. Defaults to SessionBackend.
Return type:

OAuth2ConsumerBlueprint

Returns:

A blueprint to attach to your Flask app.

flask_dance.contrib.meetup.meetup

A LocalProxy to a requests.Session that already has the Meetup authentication token loaded (assuming that the user has authenticated with Meetup at some point in the past).

Custom

Flask-Dance allows you to build authentication blueprints for any OAuth provider, not just the ones listed above. For example, let’s create a blueprint for a fictional OAuth provider called oauth-example.com. We check the documentation for oauth-example.com, and discover that they’re using OAuth 2, the access token URL is https://oauth-example.com/login/access_token, and the authorization URL is https://oauth-example.com/login/authorize. We could then build the blueprint like this:

from flask import Flask
from flask_dance.consumer import OAuth2ConsumerBlueprint

app = Flask(__name__)
example_blueprint = OAuth2ConsumerBlueprint(
    "oauth-example", __name__,
    client_id="my-key-here",
    client_secret="my-secret-here",
    base_url="https://oauth-example.com",
    token_url="https://oauth-example.com/login/access_token",
    authorize_url="https://oauth-example.com/login/authorize",
)
app.register_blueprint(example_blueprint, url_prefix="/login")

Now, in your page template, you can do something like:

<a href="{{ url_for("oauth-example.login") }}">Login with OAuth Example</a>

And in your views, you can make authenticated requests using the session attribute on the blueprint:

resp = example_blueprint.session.get("/user")
assert resp.ok
print("Here's the content of my response: " + resp.content)

It all follows the same patterns as the Quickstarts. You can also read the code to see how the pre-set configurations are implemented – it’s very short.

Backends

A Flask-Dance blueprint has a backend associated with it, which is simply an object that knows how to store and retrieve OAuth tokens from some kind of persistent storage. The default storage backend uses the Flask session to store OAuth tokens, which is simple and requires no configuration. However, when the user closes their browser, the OAuth token will be lost, so its not a good choice for production usage. Fortunately, Flask-Dance comes with some other backends to choose from.

SQLAlchemy

SQLAlchemy is the “standard” database for Flask applications, and Flask-Dance has great support for it. First, define your database model with a token column and a provider column. Flask-Dance includes a OAuthConsumerMixin class to make this easier:

from flask_sqlalchemy import SQLAlchemy
from flask_dance.consumer.backend.sqla import OAuthConsumerMixin

db = SQLAlchemy()
class OAuth(db.Model, OAuthConsumerMixin):
    pass

Next, create an instance of the SQLAlchemy backend and assign it to your blueprint:

from flask_dance.consumer.backend.sqla import SQLAlchemyBackend

blueprint.backend = SQLAlchemyBackend(OAuth, db.session)

And that’s all you need – if you don’t have user accounts in your application. If you do, it’s slightly more complicated:

from flask_sqlalchemy import SQLAlchemy
from flask_login import current_user
from flask_dance.consumer.backend.sqla import OAuthConsumerMixin, SQLAlchemyBackend

db = SQLAlchemy()

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    # ... other columns as needed

class OAuth(db.Model, OAuthConsumerMixin):
    user_id = db.Column(db.Integer, db.ForeignKey(User.id))
    user = db.relationship(User)

blueprint.backend = SQLAlchemyBackend(OAuth, db.session, user=current_user)

There are two things to notice here. One, the model that you use for storing OAuth tokens must have a user relationship to the user that it is associated with. Two, you must pass a reference to the currently logged-in user (if any) to SQLAlchemyStorage. If you’re using Flask-Login, the current_user proxy works great, but you could instead pass a function that returns the current user, if you want.

You also probably want to use a caching system for your database, so that it is more performant under heavy load. The SQLAlchemy token storage backend also integrates with Flask-Cache if you just pass an Flask-Cache instance to the backend, like this:

from flask import Flask
from flask_cache import Cache

app = Flask(__name__)
cache = Cache(app)

# setup Flask-Dance with SQLAlchemy models...

blueprint.backend = SQLAlchemyBackend(OAuth, db.session, cache=cache)

Custom

Of course, you don’t have to use SQLAlchemy, you’re free to use whatever storage system you want. Writing a custom backend is easy: just subclass flask_dance.consumer.backend.BaseBackend and override the get, set, and delete methods. For example, here’s a backend that uses a file on disk:

import os
import os.path
import json
from flask_dance.consumer.backend import BaseBackend

class FileBackend(BaseBackend):
    def __init__(self, filepath):
        super(FileStorage, self).__init__()
        self.filepath = filepath

    def get(self, blueprint):
        if not os.path.exists(self.filepath):
            return None
        with open(self.filepath) as f:
            return json.load(f)

    def set(self, blueprint, token):
        with open(self.filepath, "w") as f:
            json.dump(f)

    def delete(self, blueprint):
        os.remove(self.filepath)

Then, just create an instance of your backend and assign it to the backend attribute of your blueprint, and Flask-Dance will use it.

Proxies and HTTPS

Running a secure HTTPS website is important, but encrypting and decrypting HTTPS traffic is computationally expensive. Many people running large-scale websites (including Heroku) use a TLS termination proxy to reduce load on the HTTP server. This works great, but means that the webserver running your Flask application is actually speaking HTTP, not HTTPS. As a result, Flask-Dance can get confused, and generate callback URLs that have an http:// scheme, instead of an https:// scheme. This is bad, because OAuth requires that all connections use HTTPS for security purposes, and OAuth providers will reject requests that suggest a callback URL with a http:// scheme.

Fortunately, the fix for this problem is simple: we can just inform Flask that it is running behind a proxy. This will allow Flask to discover that the user actually requested the site from https://, and as a result, Flask-Dance will be sure to generate callback URLs that have an https:// schema. All you have to do is wrap your application with Werkzueg’s ProxyFix middleware, like so:

from flask import Flask
from werkzeug.contrib.fixers import ProxyFix

app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)

After you define your Flask application, usually stored in a variable called app, just wrap the app.wsgi_app parameter in the ProxyFix middleware. This will teach Flask how to determine whether the request actually came in via HTTP or HTTPS, so that any part of your website that uses that information (including Flask-Dance) can work correctly.

Signals

New in version 0.2.

Flask-Dance supports signals, just as Flask does. Signals are perfect for custom processing code that you want to run at a certain point in the OAuth dance. For example, after the dance is complete, you might need to update the user’s profile, kick off a long-running task, or simply flash a message to let the user know that the login was successful. It’s easy, just import the appropriate signal of the ones listed below, and connect your custom processing code to the signal.

The following signals exist in Flask-Dance:

flask_dance.consumer.oauth_authorized

This signal is sent when a user completes the OAuth dance by receiving a response from the OAuth provider’s authorize URL. The signal is invoked with the blueprint instance as the first argument (the sender), and with a dict of the OAuth provider’s response (the token).

Example subscriber:

from flask import flash
from flask_dance.consumer import oauth_authorized

@oauth_authorized.connect
def logged_in(blueprint, token):
    flash("Signed in successfully with {name}!".format(
        name=blueprint.name.capitalize()
    ))

If you’re using OAuth 2, the user may grant you different scopes from the ones you requested: check the scope key in the token dict to determine what scopes were actually granted. If you don’t want the token to be stored, simply return False from one of your signal receiver functions – this can be useful if the user has declined to authorize your OAuth request, has granted insufficient scopes, or in some other way has given you a token that you don’t want.

flask_dance.consumer.oauth_error

This signal is sent when the OAuth provider indicates that there was an error with the OAuth dance. This can happen if your application is misconfigured somehow. The user will be redirected to the redirect_url anyway, so it is your responsibility to hook into this signal and inform the user that there was an error.

Advanced Topics:

How OAuth Works

Definitions

OAuth uses a series of specially-crafted HTTP views and redirects to allow websites to share information with each other securely, and with the user’s consent [1]. There are four roles in an OAuth interaction:

provider
A website that has information about a user. Well-known OAuth providers include Google, Facebook, Twitter, etc.
consumer
A website that wants to obtain some information about a user from the provider.
user
An actual person who controls information stored with the provider.
client
A program (usually a web browser) that interacts with the provider and consumer on behalf of the user.

In order to securely interact with each other, the provider and consumer must exchange secrets ahead of time, before any OAuth communication actually happens. Generally, this happens when someone who runs the consumer website goes to the provider website and registers an application with the provider, putting in information about the name and URL of the consumer website. The provider then gives the consumer a “client secret”, which is a random string of letters and numbers. By presenting this client secret in future OAuth communication, the provider website can verify that the consumer is who they say they are, and not some other website trying to intercept the communication.

Note

Even though it is called a “client secret”, the secret represents the consumer website, not the client (the user’s web browser).

After the consumer has registered an application with the provider and gotten a client secret, the consumer can do the “OAuth dance” to get consent from a user to share information with the consumer. There are two different versions of the dance: OAuth 1, which is the original version; and OAuth 2, the successor to OAuth 1 which is more flexible and more widely used today.

OAuth 2

  1. The client visits the consumer at a special URL, indicating that they want to connect to the provider with OAuth. Typically, there is a button on the consumer’s website labelled “Log In with Google” or similar, which takes the user to this special URL.
  2. The consumer decides how much of the user’s data they want to access, using specfic keywords called “scopes”. The consumer also makes up a random string of letters and numbers, called a “state” token. The consumer crafts a special URL that points to the provider, but has the client secret, the scopes, the state token embedded in it. The consumer asks the client to visit the provider using this special URL.
  3. When the client visits the provider at that URL, the provider notices the client secret, and looks up the consumer that it belongs to. The provider also notices the scopes that the consumer is requesting. The provider displays a page informing the user what information the consumer wants access to – it may be all of the user’s information, or just some of the user’s information. The user gets to decide if this is OK or not. If the user decides that this is not OK, the dance is over.
  4. If the user grants consent, the provider makes up a new secret, called the “authorization code”. The provider crafts a special URL that points to the consumer, but has the authorization code and the state token embedded in it. The provider asks the client to visit the consumer using this special URL.
  5. When the client visits the consumer at that URL, the consumer first checks the state token to be sure that it hasn’t changed, just to verify that no one has tampered with the request. Then, the consumer makes a separate request to the provider, passing along the client secret and the authorization code. If everything looks good to the provider, the provider makes up one final secret, called the “access token”, and sends it back to the consumer. This completes the dance.

OAuth 1

  1. The client visits the consumer at a special URL, indicating that they want to connect to the provider with OAuth. Typically, there is a button on the consumer’s website labelled “Log In with Twitter” or similar, which takes the user to this special URL.
  1. The consumer tells the provider that they’re about to do the OAuth dance. The consumer gives the provider the client secret, to verify that everything’s cool. The provider checks the OAuth secret, and if it looks good, the provider makes up a new secret called a “request token”, and gives it to the consumer.
  2. The consumer crafts a special URL that points to the provider, but has the client secret and request token embedded in it. The consumer asks the client to visit the provider using this special URL.
  3. When the client visits the provider at that URL, the provider notices the request token, and looks up the consumer that it belongs to. The provider tells the user that this consumer wants to access some or all of the user’s information. The user gets to decide if this is OK or not. If the user decides that this is not OK, the dance is over.
  4. If the user grants consent, the provider makes up another new secret, called the “authorization code”. The provider crafts a special URL that points to the consumer, but has the authorization code embedded in it. The provider asks the client to go visit the consumer at that special URL.
  5. When the client visits the consumer at that URL, the consumer notices the authorization code. The consumer makes another request to the provider, passing along the client secret and the authorization code. If everything looks good to the provider, the provider makes up one final secret, called the “access token”, and sends it back to the consumer. This completes the dance.

Dance Complete

Phew, that was complicated! But the end result is, the consumer has an access token, which proves that the user has given consent for the provider to give the consumer information about that user. Now, whenever the consumer needs information from the provider about the user, the consumer simply makes an API request to the provider and passes the access token along with the request. The provider sees the access token, looks up the user that granted consent, and determines whether the requested information falls within what the user authorized. If so, the provider returns that information to the consumer. In effect, the consumer is now the user’s client!

Warning

Keep your access tokens secure! Treat a user’s access token like you would treat their password.

Note

The OAuth dance normally only needs to be performed once per user. Once the consumer has an access token, that access token can be used to make many API requests on behalf of the user. Some OAuth implementations put a lifespan on the access token, after which it must be refreshed, but refreshing an access token does not require any interaction from the user.

[1]Not all OAuth interactions share information about specific users. When no user-specific information is involved, then the consumer is able to get information from the provider without getting a user’s consent, since there is no one to get consent from. In practice, however, most OAuth interactions are about sharing information about users, so this documentation assumes that use-case.

Developer Interface

Consumers

An OAuth consumer is a website that allows users to log in with other websites (known as OAuth providers). Once a user has gone through the OAuth dance, the consumer website is allowed to interact with the provider website on behalf of the user.

class flask_dance.consumer.OAuth1ConsumerBlueprint(...)[source]

A subclass of flask.Blueprint that sets up OAuth 1 authentication.

__init__(name, import_name, client_key=None, client_secret=None, signature_method=u'HMAC-SHA1', signature_type=u'AUTH_HEADER', rsa_key=None, client_class=None, force_include_body=False, static_folder=None, static_url_path=None, template_folder=None, url_prefix=None, subdomain=None, url_defaults=None, root_path=None, login_url=None, authorized_url=None, base_url=None, request_token_url=None, authorization_url=None, access_token_url=None, redirect_url=None, redirect_to=None, session_class=None, backend=None, **kwargs)[source]

Most of the constructor arguments are forwarded either to the flask.Blueprint constructor or the requests_oauthlib.OAuth1Session construtor, including **kwargs (which is forwarded to OAuth1Session). Only the arguments that are relevant to Flask-Dance are documented here.

Parameters:
  • base_url – The base URL of the OAuth provider. If specified, all URLs passed to this instance will be resolved relative to this URL.
  • request_token_url – The URL specified by the OAuth provider for obtaining a request token. This can be an fully-qualified URL, or a path that is resolved relative to the base_url.
  • authorization_url – The URL specified by the OAuth provider for the user to grant token authorization. This can be an fully-qualified URL, or a path that is resolved relative to the base_url.
  • access_token_url – The URL specified by the OAuth provider for obtaining an access token. This can be an fully-qualified URL, or a path that is resolved relative to the base_url.
  • login_url – The URL route for the login view that kicks off the OAuth dance. This string will be formatted with the instance so that attributes can be interpolated. Defaults to /{bp.name}, so that the URL is based on the name of the blueprint.
  • authorized_url – The URL route for the authorized view that completes the OAuth dance. This string will be formatted with the instance so that attributes can be interpolated. Defaults to /{bp.name}/authorized, so that the URL is based on the name of the blueprint.
  • redirect_url – When the OAuth dance is complete, redirect the user to this URL.
  • redirect_to – When the OAuth dance is complete, redirect the user to the URL obtained by calling url_for() with this argument. If you do not specify either redirect_url or redirect_to, the user will be redirected to the root path (/).
  • session_class – The class to use for creating a Requests session. Defaults to OAuth1Session.
  • backend – A storage backend class, or an instance of a storage backend class, to use for this blueprint. Defaults to SessionBackend.
session[source]

An OAuth1Session instance that automatically loads tokens for the OAuth provider from the backend. This instance is automatically created the first time it is referenced for each request to your Flask application.

backend

The token storage backend that this blueprint uses.

token

The OAuth token currently loaded in the session attribute.

config

A special dictionary that holds information about the current state of the application, which the backend can use to look up the correct OAuth token from storage. For example, in a multi-user system, where each user has their own OAuth token, information about which user is currently logged in for this request is stored in this dictionary. This dictionary is special because it automatically alerts the backend when any attribute in the dictionary is changed, so that the backend’s caches are appropriately invalidated.

from_config

A dictionary used to dynamically load variables from the Flask application config into the blueprint at the start of each request. To tell this blueprint to pull configuration from the app, set key-value pairs on this dict. Keys are the name of the local variable to set on the blueprint object, and values are the variable name in the Flask application config. Variable names can be a dotpath. For example:

blueprint.from_config["session.client_id"] = "GITHUB_OAUTH_CLIENT_ID"

Which will cause this line to execute at the start of every request:

blueprint.session.client_id = app.config["GITHUB_OAUTH_CLIENT_ID"]
class flask_dance.consumer.OAuth2ConsumerBlueprint(...)[source]

A subclass of flask.Blueprint that sets up OAuth 2 authentication.

__init__(name, import_name, client_id=None, client_secret=None, client=None, auto_refresh_url=None, auto_refresh_kwargs=None, scope=None, state=None, static_folder=None, static_url_path=None, template_folder=None, url_prefix=None, subdomain=None, url_defaults=None, root_path=None, login_url=None, authorized_url=None, base_url=None, authorization_url=None, authorization_url_params=None, token_url=None, token_url_params=None, redirect_url=None, redirect_to=None, session_class=None, backend=None, **kwargs)[source]

Most of the constructor arguments are forwarded either to the flask.Blueprint constructor or the requests_oauthlib.OAuth2Session construtor, including **kwargs (which is forwarded to OAuth2Session). Only the arguments that are relevant to Flask-Dance are documented here.

Parameters:
  • base_url – The base URL of the OAuth provider. If specified, all URLs passed to this instance will be resolved relative to this URL.
  • authorization_url – The URL specified by the OAuth provider for obtaining an authorization grant. This can be an fully-qualified URL, or a path that is resolved relative to the base_url.
  • authorization_url_params (dict) – A dict of extra key-value pairs to include in the query string of the authorization_url, beyond those necessary for a standard OAuth 2 authorization grant request.
  • token_url

    The URL specified by the OAuth provider for obtaining an access token. This can be an fully-qualified URL, or a path that is resolved relative to the base_url.

  • token_url_params (dict) – A dict of extra key-value pairs to include in the query string of the token_url, beyond those necessary for a standard OAuth 2 access token request.
  • login_url – The URL route for the login view that kicks off the OAuth dance. This string will be formatted with the instance so that attributes can be interpolated. Defaults to /{bp.name}, so that the URL is based on the name of the blueprint.
  • authorized_url – The URL route for the authorized view that completes the OAuth dance. This string will be formatted with the instance so that attributes can be interpolated. Defaults to /{bp.name}/authorized, so that the URL is based on the name of the blueprint.
  • redirect_url – When the OAuth dance is complete, redirect the user to this URL.
  • redirect_to – When the OAuth dance is complete, redirect the user to the URL obtained by calling url_for() with this argument. If you do not specify either redirect_url or redirect_to, the user will be redirected to the root path (/).
  • session_class – The class to use for creating a Requests session. Defaults to OAuth2Session.
  • backend – A storage backend class, or an instance of a storage backend class, to use for this blueprint. Defaults to SessionBackend.
session[source]

An OAuth2Session instance that automatically loads tokens for the OAuth provider from the backend. This instance is automatically created the first time it is referenced for each request to your Flask application.

backend

The token storage backend that this blueprint uses.

token

The OAuth token currently loaded in the session attribute.

config

A special dictionary that holds information about the current state of the application, which the backend can use to look up the correct OAuth token from storage. For example, in a multi-user system, where each user has their own OAuth token, information about which user is currently logged in for this request is stored in this dictionary. This dictionary is special because it automatically alerts the backend when any attribute in the dictionary is changed, so that the backend’s caches are appropriately invalidated.

from_config

A dictionary used to dynamically load variables from the Flask application config into the blueprint at the start of each request. To tell this blueprint to pull configuration from the app, set key-value pairs on this dict. Keys are the name of the local variable to set on the blueprint object, and values are the variable name in the Flask application config. Variable names can be a dotpath. For example:

blueprint.from_config["session.client_id"] = "GITHUB_OAUTH_CLIENT_ID"

Which will cause this line to execute at the start of every request:

blueprint.session.client_id = app.config["GITHUB_OAUTH_CLIENT_ID"]

Backends

class flask_dance.consumer.backend.session.SessionBackend(...)[source]

The default storage backend. Stores and retrieves OAuth tokens using the Flask session.

__init__(key='{bp.name}_oauth_token')[source]
Parameters:key (str) – The name to use as a key for storing the OAuth token in the Flask session. This string will have .format(bp=self.blueprint) called on it before it is used. so you can refer to information on the blueprint as part of the key. For example, {bp.name} will be replaced with the name of the blueprint.
class flask_dance.consumer.backend.sqla.SQLAlchemyBackend(...)[source]

Stores and retrieves OAuth tokens using a relational database through the SQLAlchemy ORM.

__init__(model, session, user=None, user_id=None, anon_user=None, cache=None)[source]
Parameters:
  • model – The SQLAlchemy model class that represents the OAuth token table in the database. At a minimum, it must have a provider column and a token column. If tokens are to be associated with individual users in the application, it must also have a user relationship to your User model. It is recommended, though not required, that your model class inherit from OAuthConsumerMixin.
  • session – The SQLAlchemy session for the database. If you’re using Flask-SQLAlchemy, this is db.session.
  • user – If you want OAuth tokens to be associated with individual users in your application, this is a reference to the user that you want to use for the current request. It can be an actual User object, a function that returns a User object, or a proxy to the User object. If you’re using Flask-Login, this is current_user.
  • user_id – If you want to pass an identifier for a user instead of an actual User object, use this argument instead. Sometimes it can save a database query or two. If both user and user_id are provided, user_id will take precendence.
  • anon_user – If anonymous users are represented by a class in your application, provide that class here. If you are using Flask-Login, anonymous users are represented by the flask_login.AnonymousUserMixin class, but you don’t have to provide that – Flask-Dance treats it as the default.
  • cache – An instance of Flask-Cache. Providing a caching system is highly recommended, but not required.

Indices and tables