Django Google Login using django-allauth Example

Published On: 29/07/2022 | Category: Django Python


Hi Dev,

This article will give you example of user registration in django using google oauth. you can understand a concept of django-allauth google tutorial. step by step explain django allauth social login. This article will give you simple example of django google authentication using django-allauth. follow bellow step for django login with google example.

So, Open Authorization (OAuth) is a service that allows websites or apps to share user information with other websites without being given a users password. Users can log in to multiple websites with the same account without creating other credentials.

As we know OAuth service providers Google, Facebook and GitHub. In this tutorial, we look at registering users in a Django app using Google OAuth.

So if you want to also implement login with google gmail account then i will help you step by step instruction. let's follow tutorial and implement it.

Step 1 : Create a Project

In this step, we’ll create a new django project using the django-admin. Head back to your command-line interface and run the following command:

django-admin startproject example
Step 2 : Create a App
python3 manage.py startapp oauth_app
Step 3 : Update setting.py

In this step we require to do two things in our settings.py file, register the oauth_app to the example project by adding it to installed_apps in settings.py add the below lines to your settings.py file:

Next, you need to add it in the settings.py file as follows:

settings.py
....
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'oauth_app',
]

Add static and media folder directory in STATIC_ROOT

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Next, you need to migrate your database using the following command:

python manage.py migrate
Step 4 : Installing django-allauth

The django-allauth is an integrated set of Django applications addressing authentication, registration, account management as well as 3rd party (social) account authentication.

pip install django-allauth
Step 5 : Configuring django-allauth

In this step we need to configuring after installing the package, register django-allauth by adding it to INSTALLED_APPS in settings.py

settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app_name',

    # Add the following django-allauth apps
    'allauth',
    'allauth.account',
    'django.contrib.sites',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.google', # for Google OAuth 2.0
]

AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'allauth.account.auth_backends.AuthenticationBackend'
]

Continue to add SITE_ID and specify redirect URL upon successful Google login. You can also add additional configuration settings as shown below:

SITE_ID = 2
LOGIN_REDIRECT_URL = '/'

# Additional configuration settings
SOCIALACCOUNT_QUERY_EMAIL = True
ACCOUNT_LOGOUT_ON_GET= True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_EMAIL_REQUIRED = True

Finally, enable email scope to receive user’s email addresses after successful social login:

SOCIALACCOUNT_PROVIDERS = {
    'google': {
        'SCOPE': [
            'profile',
            'email',
        ],
        'AUTH_PARAMS': {
            'access_type': 'online',
        }
    }
}
Step 6 : Create Google App

In this step we need google client id and secret that way we can get information of other user. so if you don't have google app account then you can create from here : Google Developers Console. you can find bellow screen :



Now you have to click on Credentials and choose first option oAuth and click Create new Client ID button. now you can see following slide:



Step 7 : Create New API Credentials

Back to 'Dashboard', go to 'Credentials' on left panel and click 'Create Credentials' button at the top. On the dropdown, choose 'OAuth Client ID' option.

Under 'Authorized JavaScript origins', add the following URIs:

  • http://localhost:8000
  • http://127.0.0.1:8000

Under 'Authorized redirect URIs', add the following URIs:

  • http://127.0.0.1:8000/accounts/google/login/callback/
  • http://localhost:8000/accounts/google/login/callback/

The reason why we have two near-identical facsimiles of URIs is because Django web server can be accessed utilizing either localhost:8000 or 127.0.0.1:8000. Withal, should the app be in engenderment, the URIs should be amended to include the domain name instead.



after create account you can copy client id and secret.

Step 8 : Add a social app in Django admin

In this step create a superuser by running the following command in a terminal.

python manage.py createsuperuser

Run the app using:

python manage.py runserver

Here, Open http://127.0.0.1:8000/admin and login to Django Admin. Under Sites click Add and put 127.0.0.1:8000 as both the Domain name and Display name.


Then, under Social Applications click Add and fill in the details as follows:

  1. Provider: Google
  2. Name: OAuth App
  3. Client id: Your Clint ID
  4. Secret key: Your Secret ID
  5. Sites: 127.0.0.1:8000
  6. Sites: Select your Site in 'Available sites' and click the arrow to move it into 'Chosen sites'

Step 9 : Creating the Views

In this step, we need to create the views for performing fetch record to the database.Open the cropper/views.py file and add:

cropper/views.py
from django.shortcuts import render

# Create your views here.

def home(request):
    return render(request, 'home.html', {})
Step 10 : Creating the Templates

Here, in this step we need to create a new folder named croppers in the templates folder of croppers.

Next, open the cropper/templates/home.html file and the add:

cropper/templates/home.html
{% load socialaccount %}
<html>

<head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
    <title>Google Registration</title>
</head>

<body>
    <div class="container mt-5 pt-5">
        <div class="row d-flex justify-content-center">
            <div class="col-lg-7">
                <div class="card">
                    <div class="card-header">
                        <h4>Django Login with Google Example - Tuts-Station.com</h4>
                    </div>
                    <div class="card-body">
                        {% if user.is_authenticated %}
                        <p>Welcome, <strong>{{ user.username }} !</strong></p>

                        {% else %}
                        <div class="row">
                            <div class="col-md-12 text-center">
                                <a href="{% provider_login_url 'google' %}" class="btn btn-primary"><i class="fa fa-google" aria-hidden="true"></i> Login with Google</a>
                            </div>
                        </div>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
    </div>

</body>


Step 11 : Creating URLs

In this section, we’ll create the urls to access our views.Go to the urls.py cropper/urls.py file and update it as follows:

cropper/urls.py
from django.contrib import admin
from django.urls import path, include
from .views import home

urlpatterns = [
    path('', home, name="home"),
]

Next, we will require the modify the urls.py your root preoject folder lets update the file.

example/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('app_name.urls')),
    path('accounts/', include('allauth.urls')),
]
Run the Server

In this step, we’ll run the local development server for playing with our app without deploying it to the web.

python manage.py runserver

Next, go to the http://localhost:8000/ address with a web browser.

Preview
Home Page

I Hope It will help you....