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='HMAC-SHA1', signature_type='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, storage=None, rule_kwargs=None, **kwargs)[source]¶
Most of the constructor arguments are forwarded either to the
flask.Blueprint
constructor or therequests_oauthlib.OAuth1Session
constructor, including**kwargs
(which is forwarded toOAuth1Session
). 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 eitherredirect_url
orredirect_to
, the user will be redirected to the root path (/
).session_class – The class to use for creating a Requests session between the consumer (your website) and the provider (e.g. Twitter). Defaults to
OAuth1Session
.storage – A token storage class, or an instance of a token storage class, to use for this blueprint. Defaults to
SessionStorage
.rule_kwargs (dict, optional) – Additional arguments that should be passed when adding the login and authorized routes. Defaults to
None
.
- session[source]¶
An
OAuth1Session
instance that automatically loads tokens for the OAuth provider from the token storage. This instance is automatically created the first time it is referenced for each request to your Flask application.
- storage¶
The token storage that this blueprint uses.
- token¶
This property functions as pass-through to the token storage. If you read from this property, you will receive the current value from the token storage. If you assign a value to this property, it will get set in the token storage.
- config¶
A special dictionary that holds information about the current state of the application, which the token storage 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 storage when any attribute in the dictionary is changed, so that the storage’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, storage=None, rule_kwargs=None, use_pkce=False, code_challenge_method='S256', **kwargs)[source]¶
Most of the constructor arguments are forwarded either to the
flask.Blueprint
constructor or therequests_oauthlib.OAuth2Session
constructor, including**kwargs
(which is forwarded toOAuth2Session
). 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 eitherredirect_url
orredirect_to
, the user will be redirected to the root path (/
).session_class – The class to use for creating a Requests session between the consumer (your website) and the provider (e.g. Twitter). Defaults to
OAuth2Session
.storage – A token storage class, or an instance of a token storage class, to use for this blueprint. Defaults to
SessionStorage
.rule_kwargs (dict, optional) – Additional arguments that should be passed when adding the login and authorized routes. Defaults to
None
.use_pkce – If true then the authorization flow will follow the PKCE (Proof Key for Code Exchange). For more details please refer to RFC7636
code_challenge_method – Code challenge method to be used in authorization code flow with PKCE instead of client secret. It will be used only if
use_pkce
is set to True. Defaults toS256
.
- session[source]¶
An
OAuth2Session
instance that automatically loads tokens for the OAuth provider from the storage. This instance is automatically created the first time it is referenced for each request to your Flask application.
- storage¶
The token storage that this blueprint uses.
- token¶
This property functions as pass-through to the token storage. If you read from this property, you will receive the current value from the token storage. If you assign a value to this property, it will get set in the token storage.
- config¶
A special dictionary that holds information about the current state of the application, which the token storage 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 storage when any attribute in the dictionary is changed, so that the storage’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"]
Storages¶
- class flask_dance.consumer.storage.session.SessionStorage(...)[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.storage.sqla.SQLAlchemyStorage(...)[source]¶
Stores and retrieves OAuth tokens using a relational database through the SQLAlchemy ORM.
- __init__(model, session, user=None, user_id=None, user_required=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 atoken
column. If tokens are to be associated with individual users in the application, it must also have auser
relationship to your User model. It is recommended, though not required, that your model class inherit fromOAuthConsumerMixin
.session – The
SQLAlchemy session
for the database. If you’re using Flask-SQLAlchemy, this isdb.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
anduser_id
are provided,user_id
will take precendence.user_required – If set to
True
, an exception will be raised if you try to set or retrieve an OAuth token without an associated user. If set toFalse
, OAuth tokens can be set with or without an associated user. The default is auto-detection: it will beTrue
if you pass auser
oruser_id
parameter,False
otherwise.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-Caching. Providing a caching system is highly recommended, but not required.
- get(blueprint, user=None, user_id=None)[source]¶
When you have a statement in your code that says “if <provider>.authorized:” (for example “if twitter.authorized:”), a long string of function calls result in this function being used to check the Flask server’s cache and database for any records associated with the current_user. The user and user_id parameters are actually not set in that case (see base.py:token(), that’s what calls this function), so the user information is instead loaded from the current_user (if that’s what you specified when you created the blueprint) with blueprint.config.get(‘user_id’).
- Parameters:
blueprint –
user –
user_id –
- Returns:
Sessions¶
- class flask_dance.consumer.requests.OAuth1Session(blueprint=None, base_url=None, *args, **kwargs)[source]¶
A
requests.Session
subclass that can do some special things:lazy-loads OAuth1 tokens from the storage via the blueprint
handles OAuth1 authentication (from
requests_oauthlib.OAuth1Session
superclass)has a
base_url
property used for relative URL resolution
Note that this is a session between the consumer (your website) and the provider (e.g. Twitter), and not a session between a user of your website and your website.
- property authorized¶
This is the property used when you have a statement in your code that reads “if <provider>.authorized:”, e.g. “if twitter.authorized:”.
The way it works is kind of complicated: this function just tries to load the token, and then the ‘super()’ statement basically just tests if the token exists (see BaseOAuth1Session.authorized).
To load the token, it calls the load_token() function within this class, which in turn checks the ‘token’ property of this class (another function), which in turn checks the ‘token’ property of the blueprint (see base.py), which calls ‘storage.get()’ to actually try to load the token from the cache/db (see the ‘get()’ function in storage/sqla.py).
- property authorization_required¶
New in version 1.3.0.
This is a decorator for a view function. If the current user does not have an OAuth token, then they will be redirected to the
login()
view to obtain one.
- class flask_dance.consumer.requests.OAuth2Session(blueprint=None, base_url=None, *args, **kwargs)[source]¶
A
requests.Session
subclass that can do some special things:lazy-loads OAuth2 tokens from the storage via the blueprint
handles OAuth2 authentication (from
requests_oauthlib.OAuth2Session
superclass)has a
base_url
property used for relative URL resolution
Note that this is a session between the consumer (your website) and the provider (e.g. Twitter), and not a session between a user of your website and your website.
- property access_token¶
Returns the
access_token
from the OAuth token.
- property authorized¶
This is the property used when you have a statement in your code that reads “if <provider>.authorized:”, e.g. “if twitter.authorized:”.
The way it works is kind of complicated: this function just tries to load the token, and then the ‘super()’ statement basically just tests if the token exists (see BaseOAuth1Session.authorized).
To load the token, it calls the load_token() function within this class, which in turn checks the ‘token’ property of this class (another function), which in turn checks the ‘token’ property of the blueprint (see base.py), which calls ‘storage.get()’ to actually try to load the token from the cache/db (see the ‘get()’ function in storage/sqla.py).
- property authorization_required¶
New in version 1.3.0.
This is a decorator for a view function. If the current user does not have an OAuth token, then they will be redirected to the
login()
view to obtain one.