Set up Django social authentication

Problem

You want to allow users the ability to register with a Django application using their social account (Facebook, Google, Twitter).

Solution

Create a django-allauth base installation as described in the previous recipe. Next, add the desired social authentication providers to the list of INSTALLED_APPS in settings.py.

To setup Facebook social authentication create an app at https://developers.facebook.com/apps and then integrate its credentials into django-allauth. To setup Google social authentication create a project at https://console.developers.google.com/ and integrate its credentials into django-allauth. To setup Twitter social authentication create an app at https://apps.twitter.com/app/new and integrate its credentials into django-allauth.

How it works

Note The following instruction use the django-allauth package

Because social authentication can be a time consuming process, this recipe uses the django-allauth package to simplify the process.

The following recipe assumes you already set up a base django-allauth configuration. Details on why and how to set up a base django-allauth installation are described in the previous recipe Set up Django user authentication, account creation with email & password management..

Social authentication involves creating workflows -- also known as applications -- on third party sites (e.g. Google, Facebook, Twitter) to allow users of such sites the ability to re-use their identity to access external resources -- which in our case are Django applications. This ability is a very valuable feature in Django applications that require authentication to access certain features, as it allows users to register in a few clicks, instead of going through a more involved registration process.

At the most basic level, social authentication process involves tokens that are authorized by users, which are then exchanged between third party sites and the requesting party (i.e. us) to indicate a user's consent. In addition, depending on the application and its configuration, the requesting party (i.e. us) can solicit basic user information (e.g. email), as well as more elaborate information (e.g. a user's friends in a Facebook application) from the third party site.

Now that you have a basic overview of how social authentication works, let's get started on doing this in a Django project.

Setup django-allauth for different social providers

There are many social providers supported by django-allauth and each provider is supported through its own package that needs to be added to the list of INSTALLED_APPS in settings.py as illustrated in listing 1.

Listing 1 - Social provider app installation for django-allauth in settings.py

INSTALLED_APPS = (
    # Django sites framework is required
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.facebook',
    'allauth.socialaccount.providers.google',
    'allauth.socialaccount.providers.twitter',  
)


SOCIALACCOUNT_PROVIDERS = {'facebook': {}, 'google':{}, 'twitter':{}}


As you can see in listing 1, the last apps in the INSTALLED_APPS list correspond to three social providers which are Facebook, Google and Twitter. Adding these providers to INSTALLED_APPS is the first step to enable them in django-allauth.

In addition to the google, facebook and twitter providers, django-allauth also supports the following providers under the same allauth.socialaccount.providers package: angellist, bitbucket, bitly, coinbase, dropbox, dropbox_oauth2, edmodo, evernote, flickr, feedly, fxa, github, hubic, instagram, linkedin, linkedin_oauth2, odnoklassniki, openid, persona, soundcloud, spotify, stackexchange, tumblr, twitch, vimeo, vk, weibo and xing.

In listing 1 you can also see the SOCIALACCOUNT_PROVIDERS variable with a dictionary of keys that correspond to each social provider. Each key has an empty dictionary value that will eventually contain the configuration for each social provider. In the next sections, I'll describe how to set up each social provider and fill in these configuration values.

In addition to the configuration parameters in SOCIALACCOUNT_PROVIDERS you'll also need to add each social provider's application credentials in the Django admin. Go to the Django admin and click on the 'Social applications' model. Note this last model is created with a base django-allauth installation, described in the past recipe Set up Django user authentication, account creation with email & password management -- you can specifically see this Django model in Figure 14 of this last recipe.

Next, you'll be presented with a screen like the one in Figure 1 where you can edit and add social applications, click on the 'Add social application' button in the top right button. On this page, you'll see a screen like the one in Figure 2 where you can select a social provider and introduce various values associated with a social application (e.g. name, client id, secret key). For the moment we don't have any of these values, just like the configuration values for SOCIALACCOUNT_PRODIVDERS in settings.py. But keep this Django admin page open, next I'll describe where to get these values for each of the social providers used in the recipe.

Django social application list page
Figure 1.- Django social application list page
Django social application create/edit page
Figure 2.- Django social application create/edit page

Setup Facebook app with django-allauth

To setup Facebook social authentication you'll need a Facebook account to create an application on their site. Head over to https://developers.facebook.com/apps. If you've previously created a Facebook application you'll see a screen like the one in Figure 3, if you've never created an application then you won't see a list of applications, but you'll still see the 'Add a new app' button in the top right corner like Figure 3.

Facebook application list page
Figure 3.- Facebook application list page

Click on the 'Add a new app' button and you'll see a pop-up like the one in Figure 4, click on the 'Website' option. Next, you'll see a screen like the one in Figure 5, fill out all the options -- skipping configuration options you're not sure of -- until you reach the application list in Figure 3 again.

Facebook create application type pop-up
Figure 4.- Facebook create application type pop-up
Facebook quick start website application
Figure 5.- Facebook quick start website application

While on the Facebook application list in Figure 3, hover over the top right corner of the application until an arrow appears, click on the arrow and from the pop-up menu click on the 'Create Test App' option as illustrated in Figure 6. Next, fill out all the options, upon termination you'll see a screen like the one in Figure 7 with all the app configuration parameters. If you don't see Figure 7, go back to the Facebook application list in Figure 3, hover over the top right corner again and select the test application you created from the list.

Facebook create application type pop-up
Figure 6.- Facebook create application type pop-up
Facebook quick start website application
Figure 7.- Facebook quick start website application

In Figure 7, you can see there's an 'App ID' value, as well as a hidden 'App Secret' value you can see by clicking on the 'Show' button. In addition, on the left hand side you can see a series of tabs to further customize an application's parameters. Next, go to the Django admin and in the social application create/edit page -- illustrated in Figure 2 -- create a Facebook application by selecting 'Facebook' from the provider list, introducing a friendly name in the 'Name' box, introducing the 'App ID' value in the 'Client Id' box and introducing the 'App Secret' value in the 'Secret key' box.

Next, open your Django project's settings.py file and update the SOCIALACCOUNT_PROVIDERS variable with the Facebook configuration parameters illustrated in listing 2.

Listing 2 - Facebook social provider configuration for django-allauth in settings.py

SOCIALACCOUNT_PROVIDERS =     {'facebook':
       {'METHOD': 'oauth2',
        'SCOPE': ['email'],
        'AUTH_PARAMS': {'auth_type': 'reauthenticate'},
        'LOCALE_FUNC': lambda request: 'en_US',
        'VERSION': 'v2.4'}}

The settings in listing 2 are the most basic set of values to run Facebook authentication, there are many other options you can consult in the django-allauth documentation. Next, start your Django application and visit the /accounts/login/ page to attempt to log-in, you should see a page like the one illustrated in Figure 8.

Django log-in with social authentication options
Figure 8.- Django log-in with social authentication options

As you can see in Figure 8, unlike the log-in page from the last recipe, there are now options to sign-up with Facebook, Google and Twitter. Click on the Facebook link and you'll be re-directed to Facebook to grant authorization, as illustrated in the Figure 9.

Facebook social authorization pop-up
Figure 9.- Facebook social authorization pop-up

As you can see in Figure 9, a user is told he will share his public profile and email upon confirmation. If the user clicks 'Cancel' nothing happens, but if the user clicks 'OK, Got it!' Facebook contacts the application with a token and the user's information (i.e. public profile info and email). At this juncture, django-allauth creates a user and puts him through the regular django-allauth user creation workflow. Because, in the previous recipe we enforced email verification -- to avoid garbage emails -- a user is sent a verification email in which he has to click on a link to finish activation -- this is not specific or required for social authentication and you can see the previous recipe Set up Django user authentication, account creation with email & password management if you wish to deactivate this behavior.

Once a user confirms his Facebook email by clicking on the verification email link, he can sign-in to the Django application by clicking on the 'Facebook' sign-in link every time. Under the hood, django-allauth keeps track of social authentication tokens and accounts in the 'Social application tokens' and 'Social accounts' models, which are both accessible in the Django admin. In addition, django-allauth also creates a regular user -- the django.contrib.auth.models.User kind -- so the same user is capable of leveraging Django's standard authentication system -- although note there is no password assignment for this kind of user, given a user of this type relies on a Facebook authorization token.

Bare in mind that in addition to the multiple Facebook specific configuration options which would go beyond the scope of this basic setup to describe, there are other social authentication concepts (e.g. token revocation, callback URLs) that you'll need to explore and configure on your own -- given they are not Django specific -- to offer a streamlined social authentication process to end users.

Setup Google app with django-allauth

To setup Google social authentication you'll need a Google account to create an application on their site. Head over to https://console.developers.google.com/. If you've previously created Gooogle projects you'll land on a default project, while you could create the social authentication workflow on any project, I recommend you create a new project for this purpose. On the top menu bar -- besides the 'Google Developers Console' logo -- there's a drop-down menu, click on the menu and select the last option 'Create a new project', a pop-up menu like the one in Figure 10 appears, introduce the project name and click on the 'Create button'.

Google create project pop-up
Figure 10.- Google create project pop-up

After you click on the 'Create button', you'll be taken to the project's home page which is like the image in Figure 11. From the left hand side menu, click on the 'Credentials' option. Next, on the main page click on the 'Add credentials' button and from the drop-down menu select the 'OAuth 2.0 client ID' option as illustrated in Figure 12.

Google project main page
Figure 11.- Google project main page
Google project main page
Figure 12.- Google project main page

Next, you'll see the 'Create Client ID' page illustrated in Figure 13. You should select the 'Web application' option, however, because of the warning at the bottom you won't be able to. Click on the 'Configure consent screen' button that takes you to a page like the one in Figure 14.

Google project create client ID page
Figure 13.- Google project create client ID page
Google project OAuth consent screen
Figure 14.- Google project OAuth consent screen

The consent screen in Figure 14 is used to customize how an end user is greeted when authorization is seeked. Fill in the necessary fields, after saving the changes you'll be taken back to the screen in Figure 13 where you can select the 'Web Application' option. Fill out the 'Web application' fields and save the changes. Once you do this, you'll see a pop-up like the one in Figure 15 with the application client ID and client secret -- if you close the pop-up you can later access the same values in the main 'Credentials' menu on the left hand side.

Google project Client ID and Client Secret
Figure 15.- Google project Client ID and Client Secret

Next, go to the Django admin and in the social application create/edit page -- illustrated in Figure 2 -- create a Google application by selecting 'Google' from the provider list, introducing a friendly name in the 'Name' box, introducing the 'Client ID' value in the 'Client Id' box and introducing the 'Client Secret' value in the 'Secret key' box.

Next, open your Django project's settings.py file and update the SOCIALACCOUNT_PROVIDERS variable with the Google configuration parameters illustrated in listing 3.

Listing 3 - Google social provider configuration for django-allauth in settings.py

SOCIALACCOUNT_PROVIDERS =      { 'google':
        { 'SCOPE': ['email'],
          'AUTH_PARAMS': { 'access_type': 'online' }
        }
      }

The settings in listing 3 are the most basic set of values to run Google authentication, there are many other options you can consult in the django-allauth documentation. Next, start your Django application and visit the /accounts/login/ page to attempt to log-in as illustrated in Figure 8. Click on the 'Google' sign-up link and you'll be re-directed to Google to grant authorization, as illustrated in the Figure 16.

Google social authorization page
Figure 16.- Google social authorization page

As you can see in Figure 16, a user is told he will share who he is and his email upon confirmation. If the user clicks 'Cancel' nothing happens, but if the user clicks 'Accept' Google contacts the application with a token and the user's information (i.e. public profile info and email). At this juncture, django-allauth creates a user so he can sign-in to the Django application by clicking on the 'Google' sign-in link every time. Because by using Google it's implied a user is using an active and valid email, django-allauth skips the email verification process -- this unlike Facebook on which users can keep using the platform with a stale and potentially invalid email.

Under the hood, django-allauth keeps track of social authentication tokens and accounts in the 'Social application tokens' and 'Social accounts' models, which are both accessible in the Django admin. In addition, django-allauth also creates a regular user -- the django.contrib.auth.models.User kind -- so the same user is capable of leveraging Django's standard authentication system -- although note there is no password assignment for this kind of user, given a user of this type relies on a Google authorization token.

Setup Twitter app with django-allauth

To setup Twitter social authentication you'll need a Twitter account to create an application on their site. Head over to https://apps.twitter.com/app/new and you'll see a screen like the one in Figure 17, fill out the required details for the application.

Twitter create app page
Figure 17.- Twitter create app page

Once you create an application you'll be re-directed to the Twitter application's main page. Next, click on the 'Keys and Access Tokens' tab and you should see a screen like the one in Figure 18.

Twitter app Key and Access Tokens page
Figure 18.- Twitter app Key and Access Tokens page

Next, go to the Django admin and in the social application create/edit page -- illustrated in Figure 2 -- create a Twitter application by selecting 'Twitter' from the provider list, introducing a friendly name in the 'Name' box, introducing the 'Consumer Key (API Key)' value in the 'Client Id' box and introducing the 'Consumer Secret' value in the 'Secret key' box.

Next, start your Django application and visit the /accounts/login/ page to attempt to log-in as illustrated in Figure 8. Click on the 'Twitter' sign-up link and you'll be re-directed to Twitter to grant authorization, as illustrated in the Figure 19.

Twitter social authorization page
Figure 19.- Twitter social authorization page

As you can see in Figure 19, a user is told he will share tweets and other information upon confirmation. If the user clicks 'Cancel' nothing happens, but if the user clicks 'Sign In' Twitter contacts the application with a token and the user's information (i.e. public profile info). At this juncture, the user is re-directed back to the site and django-allauth asks a user for his email to finish the account creation process, as illustrated in Figure 20. Note this email request is necessary because Twitter does not provide an email with their social authentication, this may be hard to believe, but it's a known Twitter social authentication limitation.

Django allauth email request for Twitter social authorization
Figure 20.- Django allauth email request for Twitter social authorization

Because in the previous recipe we enforced email verification -- to avoid garbage emails -- a user is sent a verification email in which he has to click on a link to finish activation -- this is not specific or required for social authentication and you can see the previous recipe Set up Django user authentication, account creation with email & password management if you wish to deactivate this behavior.

Once a user confirms his email by clicking on the verification email link, he can sign-in to the Django application by clicking on the 'Twitter' sign-in link every time. Under the hood, django-allauth keeps track of social authentication tokens and accounts in the 'Social application tokens' and 'Social accounts' models, which are both accessible in the Django admin. In addition, django-allauth also creates a regular user -- the django.contrib.auth.models.User kind -- so the same user is capable of leveraging Django's standard authentication system -- although note there is no password assignment for this kind of user, given a user of this type relies on a Twitter authorization token.