Django: Google Account Authentication

1. Inside your virtualenv, install the following: django-openid-auth and python-openid

pip install django-openid-auth python-openid

2. Open your “” and do the following:

a. Add ‘django_openid_auth’ to your INSTALLED_APPS

b. Add the following to your AUTHENTICATION_BACKENDS


c. Add the following variables to your settings:

LOGIN_URL = '/login/'
LOGOUT_URL = '/logout/'

3. Open the of your project and add the following:

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

4. Create a file in your project root and name it “”.

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)
            # Make sure that the e-mail is unique.
            user = User.objects.get(email=google_email)
        except User.DoesNotExist:
            user = User.objects.create_user(google_email, google_email, 'password')
            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

The code above makes sure that the e-mail of a particular user is unique. If an existing user has already taken a particular gmail account, it automatically logs the user in. If there is no registered user who is using the e-mail address, it will create a new user and assign “password” as the default password.

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.

The login can be accessed via:

9 thoughts on “Django: Google Account Authentication”

  1. I cant read or even open massages found in my box. They are asking me to insert my code, they gave me during time of configurating my account.

  2. from openid.consumer.consumer import SUCCESS
    This line gives an error. Unresolved import SUCCESS. Could you please explain why?

Leave a Reply