oauth2client.contrib.django_util package

Module contents

Utilities for the Django web framework.

Provides Django views and helpers the make using the OAuth2 web server flow easier. It includes an oauth_required decorator to automatically ensure that user credentials are available, and an oauth_enabled decorator to check if the user has authorized, and helper shortcuts to create the authorization URL otherwise.

There are two basic use cases supported. The first is using Google OAuth as the primary form of authentication, which is the simpler approach recommended for applications without their own user system.

The second use case is adding Google OAuth credentials to an existing Django model containing a Django user field. Most of the configuration is the same, except for GOOGLE_OAUTH_MODEL_STORAGE in settings.py. See “Adding Credentials To An Existing Django User System” for usage differences.

Only Django versions 1.8+ are supported.

Configuration

To configure, you’ll need a set of OAuth2 web application credentials from Google Developer’s Console <https://console.developers.google.com/project/_/apiui/credential>.

Add the helper to your INSTALLED_APPS:

settings.py
 INSTALLED_APPS = (
     # other apps
     "django.contrib.sessions.middleware"
     "oauth2client.contrib.django_util"
 )

This helper also requires the Django Session Middleware, so django.contrib.sessions.middleware should be in INSTALLED_APPS as well. MIDDLEWARE or MIDDLEWARE_CLASSES (in Django versions <1.10) should also contain the string ‘django.contrib.sessions.middleware.SessionMiddleware’.

Add the client secrets created earlier to the settings. You can either specify the path to the credentials file in JSON format

settings.py
GOOGLE_OAUTH2_CLIENT_SECRETS_JSON=/path/to/client-secret.json

Or, directly configure the client Id and client secret.

settings.py
GOOGLE_OAUTH2_CLIENT_ID=client-id-field
GOOGLE_OAUTH2_CLIENT_SECRET=client-secret-field

By default, the default scopes for the required decorator only contains the email scopes. You can change that default in the settings.

settings.py
GOOGLE_OAUTH2_SCOPES = ('email', 'https://www.googleapis.com/auth/calendar',)

By default, the decorators will add an oauth object to the Django request object, and include all of its state and helpers inside that object. If the oauth name conflicts with another usage, it can be changed

settings.py
# changes request.oauth to request.google_oauth
GOOGLE_OAUTH2_REQUEST_ATTRIBUTE = 'google_oauth'

Add the oauth2 routes to your application’s urls.py urlpatterns.

urls.py
from oauth2client.contrib.django_util.site import urls as oauth2_urls

urlpatterns += [url(r'^oauth2/', include(oauth2_urls))]

To require OAuth2 credentials for a view, use the oauth2_required decorator. This creates a credentials object with an id_token, and allows you to create an http object to build service clients with. These are all attached to the request.oauth

views.py
from oauth2client.contrib.django_util.decorators import oauth_required

@oauth_required
def requires_default_scopes(request):
   email = request.oauth.credentials.id_token['email']
   service = build(serviceName='calendar', version='v3',
                 http=request.oauth.http,
                developerKey=API_KEY)
   events = service.events().list(calendarId='primary').execute()['items']
   return HttpResponse("email: {0} , calendar: {1}".format(
                        email,str(events)))
   return HttpResponse(
       "email: {0} , calendar: {1}".format(email, str(events)))

To make OAuth2 optional and provide an authorization link in your own views.

views.py
from oauth2client.contrib.django_util.decorators import oauth_enabled

@oauth_enabled
def optional_oauth2(request):
    if request.oauth.has_credentials():
        # this could be passed into a view
        # request.oauth.http is also initialized
        return HttpResponse("User email: {0}".format(
            request.oauth.credentials.id_token['email']))
    else:
        return HttpResponse(
            'Here is an OAuth Authorize link: <a href="{0}">Authorize'
            '</a>'.format(request.oauth.get_authorize_redirect()))

If a view needs a scope not included in the default scopes specified in the settings, you can use [incremental auth](https://developers.google.com/identity/sign-in/web/incremental-auth) and specify additional scopes in the decorator arguments.

views.py
@oauth_enabled(scopes=['https://www.googleapis.com/auth/drive'])
def drive_required(request):
    if request.oauth.has_credentials():
        service = build(serviceName='drive', version='v2',
             http=request.oauth.http,
             developerKey=API_KEY)
        events = service.files().list().execute()['items']
        return HttpResponse(str(events))
    else:
        return HttpResponse(
            'Here is an OAuth Authorize link: <a href="{0}">Authorize'
            '</a>'.format(request.oauth.get_authorize_redirect()))

To provide a callback on authorization being completed, use the oauth2_authorized signal:

views.py
from oauth2client.contrib.django_util.signals import oauth2_authorized

def test_callback(sender, request, credentials, **kwargs):
    print("Authorization Signal Received {0}".format(
            credentials.id_token['email']))

oauth2_authorized.connect(test_callback)

Adding Credentials To An Existing Django User System

As an alternative to storing the credentials in the session, the helper can be configured to store the fields on a Django model. This might be useful if you need to use the credentials outside the context of a user request. It also prevents the need for a logged in user to repeat the OAuth flow when starting a new session.

To use, change settings.py

settings.py
GOOGLE_OAUTH2_STORAGE_MODEL = {
    'model': 'path.to.model.MyModel',
    'user_property': 'user_id',
    'credentials_property': 'credential'
 }

Where path.to.model class is the fully qualified name of a django.db.model class containing a django.contrib.auth.models.User field with the name specified by user_property and a oauth2client.contrib.django_util.models.CredentialsField with the name specified by credentials_property. For the sample configuration given, our model would look like

models.py
from django.contrib.auth.models import User
from oauth2client.contrib.django_util.models import CredentialsField

class MyModel(models.Model):
    #  ... other fields here ...
    user = models.OneToOneField(User)
    credential = CredentialsField()
class oauth2client.contrib.django_util.OAuth2Settings(settings_instance)[source]

Bases: object

Initializes Django OAuth2 Helper Settings

This class loads the OAuth2 Settings from the Django settings, and then provides those settings as attributes to the rest of the views and decorators in the module.

scopes

A list of OAuth2 scopes that the decorators and views will use as defaults.

request_prefix

The name of the attribute that the decorators use to attach the UserOAuth2 object to the Django request object.

client_id

The OAuth2 Client ID.

client_secret

The OAuth2 Client Secret.

class oauth2client.contrib.django_util.UserOAuth2(request, scopes=None, return_url=None)[source]

Bases: object

Class to create oauth2 objects on Django request objects containing credentials and helper methods.

credentials

Gets the authorized credentials for this flow, if they exist.

get_authorize_redirect()[source]

Creates a URl to start the OAuth2 authorization flow.

has_credentials()[source]

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

http

Helper – create HTTP client authorized with OAuth2 credentials.

scopes

Returns the scopes associated with this OAuth2 object.

oauth2client.contrib.django_util.get_storage(request)[source]

Gets a Credentials storage object provided by the Django OAuth2 Helper object.

Parameters:request – Reference to the current request object.
Returns:An oauth2.client.Storage object.