Skip to content


Subversion checkout URL

You can clone with
Download ZIP
Fetching contributors…
Cannot retrieve contributors at this time
502 lines (343 sloc) 15.1 KB

Django Social Auth

Django Social Auth is an easy to setup social authentication/authorization mechanism for Django projects.

Crafted using base code from django-twitter-oauth and django-openid-auth, implements a common interface to define new authentication providers from third parties.


There's a demo at, it lacks Orkut support at the moment.


This application provides user registration and login using social sites credentials, some features are:


Dependencies that must be meet to use the application:


From pypi:

$ pip install django-social-auth


$ easy_install django-social-auth

or clone from github:

$ git clone git://

and add social_auth to PYTHONPATH:

$ export PYTHONPATH=$PYTHONPATH:$(pwd)/django-social-auth/


$ cd django-social-auth
$ sudo python install


  • Add social_auth to PYTHONPATH and installed applications:

  • Add desired authentication backends to AUTHENTICATION_BACKENDS setting:


    Note: this was introduced in a recent change and it's not backward compatible, take into account that saved sessions won't be able to login because the backend string stored in session (like backends.TwitterBackend) won't match the new paths.

  • The application will try to import custom backends from the sources defined in:


    This way it's easier to add new providers, check the already defined ones in social_auth.backends for examples.

    Take into account that backends must be defined in AUTHENTICATION_BACKENDS or Django won't pick them when trying to authenticate the user.

  • Setup Twitter, Facebook, Orkut and Google OAuth keys (see OAuth section for details):

    FACEBOOK_APP_ID          = ''
    ORKUT_CONSUMER_KEY       = ''
  • Setup login URLs:

    LOGIN_URL          = '/login-form/'
    LOGIN_REDIRECT_URL = '/logged-in/'
    LOGIN_ERROR_URL    = '/login-error/'

    Check Django documentation at Login URL and Login redirect URL

    In case of authentication error, the message can be stored in session if the following setting is defined:

    SOCIAL_AUTH_ERROR_KEY = 'social_errors'

    This defines the desired session key where last error message should be stored. It's disabled by default.

  • Configure authentication and association complete URL names to avoid possible clashes:

    SOCIAL_AUTH_ASSOCIATE_URL_NAME = 'associate_complete'
  • Add URLs entries:

    urlpatterns = patterns('',
        url(r'', include('social_auth.urls')),
  • Sync database to create needed models:

    ./manage syncdb
  • Not mandatory, but recommended:

    SOCIAL_AUTH_DEFAULT_USERNAME = 'new_social_auth_user'


    import random
    SOCIAL_AUTH_DEFAULT_USERNAME = lambda: random.choice(['Darth Vader', 'Obi-Wan Kenobi', 'R2-D2', 'C-3PO', 'Yoda'])


    from django.template.defaultfilter import slugify
    SOCIAL_AUTH_USERNAME_FIXER = lambda u: slugify(u)

    in case your user layout needs to purify username on some weird way.

    Final user name will have an integer suffix in case it's already taken.

  • Backends will store extra values from response by default, set this to False to avoid such behavior:


    Also more extra values will be stored if defined, details about this setting are listed below on OpenId and OAuth sections.

    Session expiration time is an special value, it's recommended to define:


    to and use such setting name where expiration times are returned. View that completes login process will set session expiration time to this value if it's present.

  • It's possible to override the used User model if needed:

    SOCIAL_AUTH_USER_MODEL = 'myapp.CustomUser'

    This class must have a custom Model Manager with a create_user method that resembles the one on auth.UserManager.

    Also, it's highly recommended that this class define the following fields:

    username   = CharField(...)
    last_login = DateTimeField(blank=True)
    is_active  = BooleanField(...)

    and the method:


    These are needed to ensure a better django-auth integration, in other case login_required won't be usable. A warning is displayed if any of these are missing. By default auth.User is used.

    Check example application for implementation details, but first, please take a look to User Profiles, it might be what you were looking for.


A pre_update signal is sent when user data is about to be updated with new values from authorization service provider, this apply to new users and already existent ones. This is useful to update custom user fields or User Profiles, for example, to store user gender, location, etc. Example:

from social_auth.signals import pre_update
from social_auth.backends.facebook import FacebookBackend

def facebook_extra_values(sender, user, response, details, **kwargs):
    user.gender = response.get('gender')
    return True

pre_update.connect(facebook_extra_values, sender=FacebookBackend)

New data updating is made automatically but could be disabled and left only to signal handler if this setting value is set to True:


Take into account that when defining a custom User model and declaring signal handler in, the imports and handler definition must be made after the custom User model is defined or circular imports issues will be raised.


OpenId support is simpler to implement than OAuth. Google and Yahoo providers are supported by default, others are supported by POST method providing endpoint URL.

OpenId backends can store extra data in UserSocialAuth.extra_data field by defining a set of values names to retrieve from any of the used schemas, pettributeExchange and SimpleRegistration. As their keywords differ we need two settings.

Settings is per backend, so we have two possible values for each one. Name is dynamically checked using uppercase backend name as prefix:

<uppercase backend name>_SREG_EXTRA_DATA
<uppercase backend name>_AX_EXTRA_DATA


GOOGLE_AX_EXTRA_DATA = [(..., ...)]

Settings must be a list of tuples mapping value name in response and value alias used to store.


OAuth communication demands a set of keys exchange to validate the client authenticity prior to user approbation. Twitter, Facebook and Orkut facilitates these keys by application registration, Google works the same, but provides the option for unregistered applications.

Check next sections for details.

OAuth backends also can store extra data in UserSocialAuth.extra_data field by defining a set of values names to retrieve from service response.

Settings is per backend and it's name is dynamically checked using uppercase backend name as prefix:

<uppercase backend name>_EXTRA_DATA


FACEBOOK_EXTRA_DATA = [(..., ...)]

Settings must be a list of tuples mapping value name in response and value alias used to store.


Twitter offers per application keys named "Consumer Key" and "Consumer Secret". To enable Twitter these two keys are needed. Further documentation at Twitter development resources:

  • Register a new application at Twitter App Creation,

  • mark the "Yes, use Twitter for login" checkbox, and

  • fill "Consumer Key" and "Consumer Secret" values:

  • You need to specify an URL callback or the application will be marked as Client type instead of the Browser. Almost any dummy value will work if you plan some test.


Facebook works similar to Twitter but it's simpler to setup and redirect URL is passed as a parameter when issuing an authorization. Further documentation at Facebook development resources:

  • Register a new application at Facebook App Creation, and

  • fill "App Id" and "App Secret" values in values:

  • also it's possible to define extra permissions with:


If you define a redirect URL in Facebook setup page, be sure to not define or http://localhost:8000 because it won't work when testing. Instead I define and setup a mapping on /etc/hosts or use dnsmasq.


Orkut offers per application keys named "Consumer Key" and "Consumer Secret". To enable Orkut these two keys are needed.

Check Google support and Orkut API for details on getting your consumer_key and consumer_secret keys.

  • fill "Consumer Key" and "Consumer Secret" values:

  • add any needed extra data to:

  • configure extra scopes in:


Google OAuth

Google provides "Consumer Key" and "Consumer Secret" keys to registered applications, but also allows unregistered application to use their authorization system with, but beware that this method will display a security banner to the user telling that the application is not trusted.

Check Google OAuth and make your choice.

  • fill "Consumer Key" and "Consumer Secret" values:


anonymous values will be used if not configured as described in their OAuth reference

  • configure the display name to be used in the "grant permissions" dialog that Google will display to users in:


    shows 'Social Auth' by default, but that might not suite your application.

  • setup any needed extra scope in:


check which Apps are included in their Google Data Protocol Directory


Maybe several, please create issues in github


Attributions to whom deserves:

  • caioariede (Caio Ariede):
    • Improvements and Orkut support
  • krvss (Stas Kravets):
    • Initial configuration
  • jezdez (Jannis Leidel):
    • Improvements and documentation update
  • alfredo (Alfredo Ramirez)
    • Facebook and Doc improvements
  • mattucf (Matt Brown)
    • Twitter and OAuth improvements


Base work is copyrighted by:

  • django-twitter-oauth:

    Original Copyright goes to Henrik Lied (henriklied)
    Code borrowed from
  • django-openid-auth:

    django-openid-auth -  OpenID integration for django.contrib.auth
    Copyright (C) 2007 Simon Willison
    Copyright (C) 2008-2010 Canonical Ltd.
Jump to Line
Something went wrong with that request. Please try again.