How to setup a Google Account Authentication

One of the awesome things that Django offers us is it lets us use our Google account as authentication to the website that we are building. I am going to show you simple steps to set it up.

Here are the steps:
1. install django-openid-auth in your virtualenv:
pip install django-openid-auth

2. install python-openid:
pip install python-openid

3. Open your “”.

4. add this to your installed apps: ‘django_openid_auth’

5. add these following setups:

AUTHENTICATION_BACKENDS = (‘django.contrib.auth.backends.ModelBackend’,’auth.GoogleBackend’,)
LOGIN_URL = ‘/login/’
LOGOUT_URL = ‘/logout/’

6. open your in your project root.

7. Add this to your urlconf:

url(r’^login/$’, ‘django_openid_auth.views.login_begin’, name=’openid-login’),
url(r’^login-complete/$’, ‘django_openid_auth.views.login_complete’, name=’openid-complete’),
url(r’^logout/$’, ‘django.contrib.auth.views.logout’, {‘next_page’: ‘/’,}, name=’logout’),

8. Create a file in your project root and name it

9. Insert this code to the file you just created:

from django.contrib.auth.models import User
from openid.consumer.consumer import SUCCESS
from django.core.mail import mail_admins

class GoogleBackend:

    def authenticate(self, openid_response):
        if openid_response is None:
            return None
        if openid_response.status != SUCCESS:
            return None

        google_email = openid_response.getSigned('',  '')
        google_firstname = openid_response.getSigned('', 'value.firstname')
        google_lastname = openid_response.getSigned('', 'value.lastname')
            user = User.objects.get(username=google_email)
        except User.DoesNotExist:
            user = User.objects.create_user(google_email, google_email,
            user = User.objects.get(username=google_email)
            return user

        return user

    def get_user(self, user_id):

            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

That’s it. Those are the steps you need to setup Google Account authentication.

Some information you need to know:

In step 7, we added the link to login using Google account and a logout link which logs out the user in the website. The login link which brings the user to Google Account login page looks like this “”. If the user has successfully login with his Google account, it automatically redirects back to the site. The user is already logged in to “”. The logout link looks like this “”. This will logout the user to “”.

In the file, we have a class GoogleBackend with a function authenticate. The way authenticate function works here is it creates a user with the username equal to it’s google email. You can always modify the code according to your needs.