oauth2client.flask_util module

Utilities for the Flask web framework

Provides a Flask extension that makes using OAuth2 web server flow easier. The extension includes views that handle the entire auth flow and a @required decorator to automatically ensure that user credentials are available.

Configuration

To configure, you’ll need a set of OAuth2 web application credentials from the Google Developer’s Console.

from oauth2client.flask_util import UserOAuth2

app = Flask(__name__)

app.config['SECRET_KEY'] = 'your-secret-key'

app.config['GOOGLE_OAUTH2_CLIENT_SECRETS_JSON'] = 'client_secrets.json'

# or, specify the client id and secret separately
app.config['GOOGLE_OAUTH2_CLIENT_ID'] = 'your-client-id'
app.config['GOOGLE_OAUTH2_CLIENT_SECRET'] = 'your-client-secret'

oauth2 = UserOAuth2(app)

Usage

Once configured, you can use the UserOAuth2.required() decorator to ensure that credentials are available within a view.

 # Note that app.route should be the outermost decorator.
 @app.route('/needs_credentials')
 @oauth2.required
 def example():
     # http is authorized with the user's credentials and can be used
     # to make http calls.
     http = oauth2.http()

     # Or, you can access the credentials directly
     credentials = oauth2.credentials

If you want credentials to be optional for a view, you can leave the decorator off and use UserOAuth2.has_credentials() to check.

 @app.route('/optional')
 def optional():
     if oauth2.has_credentials():
         return 'Credentials found!'
     else:
         return 'No credentials!'

When credentials are available, you can use UserOAuth2.email and UserOAuth2.user_id to access information from the ID Token, if available.

 @app.route('/info')
 @oauth2.required
 def info():
     return "Hello, {} ({})".format(oauth2.email, oauth2.user_id)

URLs & Trigging Authorization

The extension will add two new routes to your application:

  • "oauth2.authorize" -> /oauth2authorize
  • "oauth2.callback" -> /oauth2callback

When configuring your OAuth2 credentials on the Google Developer’s Console, be sure to add http[s]://[your-app-url]/oauth2callback as an authorized callback url.

Typically you don’t not need to use these routes directly, just be sure to decorate any views that require credentials with @oauth2.required. If needed, you can trigger authorization at any time by redirecting the user to the URL returned by UserOAuth2.authorize_url().

 @app.route('/login')
 def login():
     return oauth2.authorize_url("/")

Incremental Auth

This extension also supports Incremental Auth. To enable it, configure the extension with include_granted_scopes.

oauth2 = UserOAuth2(app, include_granted_scopes=True)

Then specify any additional scopes needed on the decorator, for example:

 @app.route('/drive')
 @oauth2.required(scopes=["https://www.googleapis.com/auth/drive"])
 def requires_drive():
     ...

 @app.route('/calendar')
 @oauth2.required(scopes=["https://www.googleapis.com/auth/calendar"])
 def requires_calendar():
     ...

The decorator will ensure that the the user has authorized all specified scopes before allowing them to access the view, and will also ensure that credentials do not lose any previously authorized scopes.

Storage

By default, the extension uses a Flask session-based storage solution. This means that credentials are only available for the duration of a session. It also means that with Flask’s default configuration, the credentials will be visible in the session cookie. It’s highly recommended to use database-backed session and to use https whenever handling user credentials.

If you need the credentials to be available longer than a user session or available outside of a request context, you will need to implement your own oauth2client.Storage.

class oauth2client.flask_util.FlaskSessionStorage[source]

Bases: oauth2client.client.Storage

Storage implementation that uses Flask sessions.

Note that flask’s default sessions are signed but not encrypted. Users can see their own credentials and non-https connections can intercept user credentials. We strongly recommend using a server-side session implementation.

locked_delete()[source]
locked_get()[source]
locked_put(credentials)[source]
class oauth2client.flask_util.UserOAuth2(app=None, *args, **kwargs)[source]

Bases: object

Flask extension for making OAuth 2.0 easier.

Configuration values:

  • GOOGLE_OAUTH2_CLIENT_SECRETS_JSON path to a client secrets json file, obtained from the credentials screen in the Google Developers console.
  • GOOGLE_OAUTH2_CLIENT_ID the oauth2 credentials’ client ID. This is only needed if GOOGLE_OAUTH2_CLIENT_SECRETS_JSON is not specified.
  • GOOGLE_OAUTH2_CLIENT_SECRET the oauth2 credentials’ client secret. This is only needed if GOOGLE_OAUTH2_CLIENT_SECRETS_JSON is not specified.

If app is specified, all arguments will be passed along to init_app.

If no app is specified, then you should call init_app in your application factory to finish initialization.

authorize_url(return_url, **kwargs)[source]

Creates a URL that can be used to start the authorization flow.

When the user is directed to the URL, the authorization flow will begin. Once complete, the user will be redirected to the specified return URL.

Any kwargs are passed into the flow constructor.

authorize_view()[source]

Flask view that starts the authorization flow.

Starts flow by redirecting the user to the OAuth2 provider.

callback_view()[source]

Flask view that handles the user’s return from OAuth2 provider.

On return, exchanges the authorization code for credentials and stores the credentials.

credentials

The credentials for the current user or None if unavailable.

email

Returns the user’s email address or None if there are no credentials.

The email address is provided by the current credentials’ id_token. This should not be used as unique identifier as the user can change their email. If you need a unique identifier, use user_id.

has_credentials()[source]

Returns True if there are valid credentials for the current user.

http(*args, **kwargs)[source]

Returns an authorized http instance.

Can only be called if there are valid credentials for the user, such as inside of a view that is decorated with @required.

Parameters:
  • *args – Positional arguments passed to httplib2.Http constructor.
  • **kwargs – Positional arguments passed to httplib2.Http constructor.
Raises:

ValueError if no credentials are available.

init_app(app, scopes=None, client_secrets_file=None, client_id=None, client_secret=None, authorize_callback=None, storage=None, **kwargs)[source]

Initialize this extension for the given app.

Parameters:
  • app – A Flask application.
  • scopes – Optional list of scopes to authorize.
  • client_secrets_file – Path to a file containing client secrets. You can also specify the GOOGLE_OAUTH2_CLIENT_SECRETS_JSON config value.
  • client_id – If not specifying a client secrets file, specify the OAuth2 client id. You can also specify the GOOGLE_OAUTH2_CLIENT_ID config value. You must also provide a client secret.
  • client_secret – The OAuth2 client secret. You can also specify the GOOGLE_OAUTH2_CLIENT_SECRET config value.
  • authorize_callback – A function that is executed after successful user authorization.
  • storage – A oauth2client.client.Storage subclass for storing the credentials. By default, this is a Flask session based storage.
  • kwargs – Any additional args are passed along to the Flow constructor.
required(decorated_function=None, scopes=None, **decorator_kwargs)[source]

Decorator to require OAuth2 credentials for a view.

If credentials are not available for the current user, then they will be redirected to the authorization flow. Once complete, the user will be redirected back to the original page.

user_id

Returns the a unique identifier for the user

Returns None if there are no credentials.

The id is provided by the current credentials’ id_token.