Tutorial: Adding Facebook/Twitter/Google Authentication to a Django Application

Django logo

I needed to add Facebook authentication to a Django app today, and instead of writing it directly against the Facebook API (or re-implementing the OAuth2 dance again), I decided to look around and see if there’s a pre-packaged solution for this common task. Turns out, there’s an excellent project called Python Social Auth, and it covers pretty much any social website with an authentication API.

As it often happens with amazing open-source projects, the documentation is somewhat minimalistic. One key piece that I could not find was a tutorial. This post is aiming to fill that gap. In this tutorial, we will use Facebook, Twitter and Google, as the most common social APIs, but we could easily substitute them with LinkedIn, Yahoo, Forsquare, or a bunch of other providers supported by Python Social Auth library.

If you are comfortable with Django, feel free to skip to Step2.

Step 0. Start a simple Django project

Let’s begin with a barebones Django project named “thirdauth”, named in honour of third-party authentication.

$ django-admin.py startproject thirdauth
$ tree thirdauth/
├── manage.py
└── thirdauth
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py

Running ./manage.py syncdb and then ./manage.py runserver and navigating to localhost:8000 will show the familiar “It worked!” Django page. Let’s put some custom application code in place, so that we can tell whether the current user is authenticated or anonymous.

Step 1. Show current user’s authentication status

Let’s throw together a simple basic page, add CSS, JavaScript and fonts from Twitter Bootstrap, and add a view for home page. For this tutorial, we won’t need custom models or any other views.

NOTE: if you need help with Django views, templates and settings, please check out the Django tutorial.

Another NOTE: Bootstrap is Twitter’s basic set of CSS and JavaScript to help make even minimal web interfaces look and behave consistently well. You do not have to use it for this tutorial, it adds only aesthetic side – it adds a polished feel to things. Bootstrap can be downloaded from http://getbootstrap.com/

Now, the very small customizations we’ll add are:

  • Add ‘thirdauth’ to INSTALLED_APPS
  • Create the template for the home page
  • Add a view for the home page
  • Add a URL pointing to the home page view

Relevant portion of settings.py:


Template: thirdauth/base.html:

<!DOCTYPE html>
<html lang="en">
   <meta charset="utf-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <title>{% block title %}Third-party Authentication Tutorial{% endblock %}</title>

   <!-- Bootstrap -->
   <link href="/static/css/bootstrap.min.css" rel="stylesheet">
   <link href="/static/css/bootstrap-theme.min.css" rel="stylesheet">
   <link href="/static/css/fbposter.css" rel="stylesheet">

   <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
   <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
   <!--[if lt IE 9]>
     <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
     <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
   {% block main %}{% endblock %}
   <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
   <!-- Include all compiled plugins (below), or include individual files as needed -->
   <script src="/static/js/bootstrap.min.js"></script>

Template: thirdauth/home.html:

{% extends 'thirdauth/base.html' %}

{% block main %}
 <h1>Third-party authentication demo</h1>

   {% if user and not user.is_anonymous %}
     Hello {{ user.get_full_name|default:user.username }}!
   {% else %}
     I don’t think we’ve met before.
   {% endif %}
{% endblock %}

File views.py:

from django.shortcuts import render_to_response
from django.template.context import RequestContext

def home(request):
   context = RequestContext(request,
                           {'user': request.user})
   return render_to_response('thirdauth/home.html',

File urls.py:

from django.conf.urls import patterns, include, url

from django.contrib import admin

urlpatterns = patterns('',
   url(r'^$', 'thirdauth.views.home', name='home'),
   url(r'^admin/', include(admin.site.urls)),

Now, when we refresh the page, we will see:

Fair enough – we have not authenticated yet. To make sure our identity-checking template works, try logging in to Django admin with the default Django authentication (assuming you created an admin account on Step 0). You should see a different message: “Hello admin!”, or something like that.

Step 2. Install Python Social Auth

First, let’s add it to our virtualenv:

pip install python-social-auth

Second, let’s make some modifications to our settings.py to include python-social-auth in our project:




Let’s update the urls module to include the new group of URLs:

urlpatterns = patterns('',
url('', include('social.apps.django_app.urls', namespace='social')),

And finally, let’s update the database models:

./manage.py syncdb

Now, if we runserver again, and navigate to Django admin, we’ll see three new tables: Associations, Nonces, and User social auths. This last one will contain the records of our users’ social accounts when they use social networks to authenticate from our app.

We are almost there. Let’s add some links for logging in and logging out, and then we’ll start adding application IDs for social apps.

Step 3. Add links for logging in and logging out.

Since we’ll be logging in and out multiple times, let’s include django.contrib.auth URLs into our URLs configuration:

urlpatterns = patterns('',
   url('', include('django.contrib.auth.urls', namespace='auth')),

Let’s modify our Home page template like this:

{% extends 'thirdauth/base.html' %}

{% block main %}
 <h1>Third-party authentication demo</h1>

   {% if user and not user.is_anonymous %}
       <a>Hello {{ user.get_full_name|default:user.username }}!</a>
       <a href="{% url 'auth:logout' %}?next={{ request.path }}">Logout</a>
   {% else %}
       <a href="{% url 'social:begin' 'facebook' %}?next={{ request.path }}">Login with Facebook</a>
       <a href="{% url 'social:begin' 'google-oauth2' %}?next={{ request.path }}">Login with Google</a>
       <a href="{% url 'social:begin' 'twitter' %}?next={{ request.path }}">Login with Twitter</a>
   {% endif %}
{% endblock %}

For the login and logout links in this template to work correctly, we need to modify a few things. First, let’s take care of logout, it’s easier. Just add ‘request’ to the context object that we pass into template-rendering code. Updated views.py:

from django.shortcuts import render_to_response
from django.template.context import RequestContext

def home(request):
   context = RequestContext(request,
                           {'request': request,
                            'user': request.user})
   return render_to_response('thirdauth/home.html',

For login to work, let’s first add a LOGIN_REDIRECT_URL parameter to settings (to prevent the default /account/profile from raising a 404):


And then start adding API-specific parameters for social networks. Right this moment, if you click on any of the “login with X” links, you’ll get redirected to the corresponding social site, but will get an error about invalid client ID. That’s because we have not provided any client IDs yet.

Step 4. Get Client IDs for the social sites.

For all the social networks we are using in this demo, the process of obtaining an OAuth2 client ID (also known as application ID) is pretty similar. All of them will require that your application has a “real” URL – that is, not or http://localhost. You can add an entry in your /etc/hosts file that maps to something like “test1.com”, and the URL of your application becomes http://test1.com:8000 – that is good enough for testing. You can change it in the social app settings when it goes into production.


  • Go to https://developers.facebook.com/apps/?action=create and click the green “Create New App” button.
  • In the settings of the newly-created application, click “Add Platform”. From the options provided, choose Web, and fill in the URL of the site (http://test1.com:8000 in our example).
  • Copy the App ID and App Secret, and place them into settings.py file:
  • This should be enough to get your app to login with Facebook! Try logging in and out – you should get redirected between your app and FB OAuth2 service, and a new record in the User social auths table will get created, along with a new User record pointing to it.


  • Go to https://console.developers.google.com/ and create a new application.
  • Under APIs and Auth > Credentials, create a new Client ID.
  • Make sure to specify the right callback URL: http://test1.com:8000/complete/google-oauth2/
  • Copy the values into settings file:


  • Go to https://apps.twitter.com/app/new and create the new application
  • The callback URL should be something like http://test1.com:8000/complete/twitter/
  • Copy the values into settings.py:

What’s next?

Python Social Auth can provide more than just authentication. By customizing pipeline, we can get account information for our users, manage accounts through email confirmation, and more. But those topics are beyond the scope of this tutorial.


Creative Commons License

This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.


  1. Danny Greenfeld

    Why are you using render_to_response and RequestContext when django.shortcuts.render does the same thing?

    • Vlad Orlenko

      Out of habit, I guess. I am glad Django keeps older methods around for people who got them ingrained.

      • sanjay

        this tutorial is good and worked well , could you plz tell me hoe to get email id from facebook using pyhton social auth

  2. burke

    a note: while its fine for this tutorial to put oauth keys in settings.py, you should never do this in practice (if your code is open source). Instead, environment variables should be used and they keys should be stored in an untracked file.

    • Vlad Orlenko

      Thanks burke, that’s a fair point. A tutorial may prefer clarity over security, but a note on best practices was needed.

      • Fábio Gelbcke

        Hey, could you educate me on how to do that? I’m a beginner.
        Thanks 🙂

        • Dylan

          In your settings.py

          import os

          SOCIAL_AUTH_TWITTER_KEY = os.environ.get(’23jdf2fefdffsfdf’)
          SOCIAL_AUTH_TWITTER_SECRET = os.environ.get(’23jdf2fefdfdfdffsfdf’)

        • Dylan

          [I tried editing my other comment, but couldn’t]
          On your manchine add it as an evronment variable e.g. on unix
          export TWITTER_KEY=23f2fdvsvsd
          export TWITTER_SECRET=23f2fdvsdfdfvsd
          In your settings.py
          import os
          SOCIAL_AUTH_TWITTER_KEY = os.environ.get(’TWITTER_KEY’)

  3. Dan

    Thank you!

  4. prasanna

    Thanks for the clear tutorial,
    I have used this in my app i got small problem,
    When i logging with facebook or google or twitter its fine and redirecting to my app ,when i click on logout its fine and logging out from my app and redirect to home page, but “Its not logging out from the facebook or google or twitter.

    How to do this, when i logging with social API and logging out in my app then the social API also should be logout.

  5. Seth Williams

    Hey Vlad, Excellent work. This is a thorough tutorial for all python users.If you to explore more about python, you can visit our python course curriculum here http://www.fireboxtraining.com/python.

  6. nawarkhede

    Amazing tutorial . Thanks 🙂

  7. riclags

    Hi, Vlad. This is a very useful tutorial. I hope you can still clarify one thing for me. I’m not sure what you exactly meant by this:

    “Make sure to specify the right callback URL: http://test1.com:8000/complete/google-oauth2/

    Where do I specify that callback?

  8. Sadanand Upase

    I have followed all the steps and when I click on ‘Login with Google’ I am redirected to google sign in page once I login to google and grant access to my app by clicking ‘Accept’ on consent screen I am getting error as “HTTPError at /complete/google-oauth2/” – 403 Client Error: Forbidden.Please help me in solving this.

  9. Gareth Thomas (@quattrofan)

    One point to make is to be sure you have made the google+ API setting AND filled out the Consent screen correctly before creating your Client ID, if you change those settings afterward you will need to regen the Client ID.

  10. Hoolders

    Thank you for this post.
    I follow this tutorial but I am having an issue. When I try to logging with facebook, it told me than one url pass is not valid. However I put my domain app and my site url. They are both good like my id and secret.
    My called url is https://www.facebook.com/dialog/oauth?state=5CNV248EbWPg3A0dtTmHWksmzNqhBwBP&redirect_uri=http%3A%2F%2F172.20.0.125%2Fcomplete%2Ffacebook%2F%3Fredirect_state%3D5CNV248EbWPg3A0dtTmHWksmzNqhBwBP&client_id=xxxxxxxxxx
    How can i resolved it?

  11. suhailvs

    nice tutorial, can i update this and put it in my blog site?

    • Shiva

      Where can i find that fbposter.css

    • Shiva

      I am getting “‘utf8’ codec can’t decode byte 0x92 in position 318: invalid start byte” error

    • Shiva

      Successfully executed your sample project.It is done.But how can i get the other data like ’email, gender, first_name’ etc

  12. Yandry

    The best tutorial EVER for Django and social auth !!!
    Thank you very much man !!!

  13. Nico

    this is probably the one tutorial that worked at first try… but you forgot to add template path in settings.py , if you don’t to that the template base.html and home.html is not found

    • Steve

      If you put the templates in thirdauth/templates/thirdauth/ then you don’t need to specify the template path. The tutorial could be more clear about this.

  14. carlos

    Cool Would love to see the pipeline example to ask for an email. There is very little documentation or examples on how to do that with Django and Python Social.

  15. lmax00@gmail.com

    Perfect Tutorial!! I’m also looking for some tutorial for the next step: get more data like profile image from the user connected with facebook.

    • pushkarparanjpe

      Two more steps needed for the app to find the templates:

      1. Create the tree under the project folder

      Save the home.html and base.html here.

      2. Need to edit the settings.py :

      Add these lines:

      SETTINGS_PATH = os.path.dirname(__file__)
      PROJECT_PATH = os.path.join(SETTINGS_PATH, os.pardir)
      PROJECT_PATH = os.path.abspath(PROJECT_PATH)
      TEMPLATES_PATH = os.path.join(PROJECT_PATH, “templates”)


  16. Abhisek Mandal

    Great tutorial! I am a Django novice and found this very helpful. But there are two very major flaws. Admin please update the post.
    The two flaws are :

    1. for the error: “templates not found” or “cannot locate home.html”
    reason: the template files base.html and home.html are placed incorrectly. In the tutorial the paths are ambiguously mentioned as “thirdauth/base.html” and “thirdauth/home.html”. Although it is a Django rule to place templates in the ‘templates/appname’ folder but stating it in a novice tutorial such as this is always beneficial.
    solution: place the templates base.html and home.html in “/templates/thirdauth/”

    2. for the error: “cannot import name is_secure_transport”
    reason: No real idea but probably the openAuthentication libraries are outdated. Googled and found the solution.
    solution: at the Linux terminal type… “sudo pip install oauthlib –upgrade”

  17. Dmitriy

    Thanks for such a great project and nice tutorial! )

  18. Jonas Rodrigues

    how can I save this data in another table?

  19. sevenearths

    I tried to do a ‘./manage.py syncdb’ and I got:

    django.core.exceptions.ImproperlyConfigured: ImportError social.apps.django_app.default: cannot import name force_text


  20. Zorak

    Thanks! This tutorial helped to setup social login on my website.

  21. Hasan

    Hi. I have followed your tutorial.

    I am having this error:

    no module named thirdauth.social.apps.django_app.

    I don’t know why..

  22. Peter

    Hey thanks for this! Great.

    Is this your site Artandlogic?

  23. anshul

    According to me,this is correct when logging out of application


    url(”,include(‘django.contrib.auth.urls’,namespace=’auth’)) –> this will redirect to standard django admin logout page

  24. Apurva Jha

    Why don’t you create a separate app for your application?

  25. Nick

    Thank you so much for this insightful tutorial Vlad! Now I just need to find out how to get permission to view status updates, friends, and others depending on my companies needs.

  26. Sudeep

    How can i get the facebook user name into my django models

  27. Luke

    got error: relation “social_auth_usersocialauth” does not exist
    any ideas? Thanks.

  28. Noopur Phalak

    Hi, I want to use custom User Model in conjunction with Google OAuth2. How do I do it?

  29. Bhanu

    After login using google api , I am not redirected to a specified page.
    I have specified “LOGIN_REDIRECT_URL = ‘/profile/'” but I am redirected to “http://loc/alhost:8000/accounts/login/?next=/”. How can I change my redirect page

  30. P Rane

    I am using python-social-auth for login in with facebook but the value of next variable isn’t taken into account even thought I have included the following line in my code:

  31. waqas

    what is this error and how to solve this… when running migrations

    C:Python27libsite-packagesdjangodbmodelsfieldssubclassing.py:22: Removed
    InDjango110Warning: SubfieldBase has been deprecated. Use Field.from_db_value in

  32. Sandip s

    when i add ‘social.apps.django_app.default’ to installed app in settings file of server its give me Internal server Error ,i have installed social.apps.django_app.default,why i am getting this error??
    Thanks in advance..

  33. Bob Glover

    Much appreciated Vlad…you’ve really helped me!!
    i’m inspired to blog about Django now….

  34. Sandip S

    I m trying to login via fb in dhango,everything is working fine.problem is i m not getting email id of user.i have added SOCIAL_AUTH_FACEBOOK_SCOPE = [’email’] to settings.py.but not getting email which is important for my database,plz help.
    Thanks in advance


  1. Python/Django Social Auth | DiRaOLinux - […] http://www.alproduction.local/blog/2014/04/tutorial-adding-facebooktwittergoogle-authentication-to-a-dj… […]
  2. Art & Logic – » 2014 Review: Day 4 - […] Tutorial: Adding Facebook/Twitter/Google Authentication to a Django Application […]