Open Authorization (OAuth) is a service that allows websites or apps to share user data with other websites without requiring a password from the user. Users can use the same account to log in to numerous websites without having to create new credentials.
Google, Facebook, and GitHub are some of the most common OAuth service providers. In this lesson, we’ll look at how to use Google OAuth to register users in a Django app.
We’ll be using be using django-allauth plugin to implement OAuth functionality into our application.
Prerequisites
To follow along with this tutorial, you need Python3 installed on your machine.
Step 1 – Create and set up a new Django project
Create a new virtual environment using the command below.
Copied!$ python3 -m venv virtual
Activate the created virtual environment by running the command below.
Copied!$ source virtual/bin/activate
Then, install the latest version of Django from PyPI by running the following command.
Copied!$ pip install django
Then, create a new Django project using the command:
Copied!$ django-admin startproject oauth_project .
Then, create a Django app using this command:
Copied!$ python manage.py startapp oauth_app
Then, apply the database migrations using the migrate
command:
Copied!$ python manage.py migrate
Register the oauth_app
to the oauth_project
project by adding it to INSTALLED_APPS
in settings.py
.
djangooauth/settings.py
Copied!INSTALLED_APPS = [ #... 'django.contrib.sites', 'oauth_app', ]
Step 2 – Install and set up django-allauth
To integrate Google OAuth features into our app, we will use django-allauth.
Install the package from Pypi by running the command:
Copied!$ pip install django-allauth
Then register django-allauth
by adding it to INSTALLED_APPS
in settings.py
.
djangooauth/settings.py
Copied!INSTALLED_APPS = [ #... 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', ]
The line allauth.socialaccount.providers.google
specifies the OAuth provider since django-allauth
supports many OAuth providers.
We will also set django-allauth
as the authentication backend for our application in the AUTHENTICATION_BACKEND
configurations.
At the bottom of settings.py
, add the following code:
djangooauth/settings.py
Copied!AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend' ]
Then set Google as the OAuth provider under SOCIALACCOUNT_PROVIDERS
configurations.
djangooauth/settings.py
Copied!SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', } } }
The SCOPE
specifies what is requested from Google APIs. If the scope is not specified, it defaults to profile
. To refresh authentication in the background, set AUTH_PARAMS['access_type']
to offline
.
Then add a site ID and redirect users to the base route after a successful login or logout.
djangooauth/settings.py
Copied!SITE_ID = 2 LOGIN_REDIRECT_URL = '/' LOGOUT_REDIRECT_URL = '/'
Step 3 – Create and configure templates
The Login with Google button will be displayed using Django templates. In your base directory, create a new folder named templates
. Then, inside the templates folder, make a file called index.html
.
Copied!$ mkdir templates $ cd templates $ touch index.html
Open index.html
and put the following code:
templates/index.html
Copied!{% load socialaccount %} <html> <body> <h1>My Google OAuth Project </h1> {% if user.is_authenticated %} <p>Welcome, You are logged in as {{ user.username }}</p> {% else %} <a href="{% provider_login_url 'google' %}">Login With Google</a> {% endif %} </body> </html>
The code above checks if the user is authenticated. If true, the username is displayed. If not, the “Login with Google” link is displayed. On clicking the link, the user will be directed to the Google OAuth dialog.
Then, register this templates
folder in the TEMPLATES
configurations in settings.py
.
djangooauth/settings.py
Copied!TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / 'templates'], 'APP_DIRS': True, #... } ]
Step 4 – Configure OAuth URLs
Open the project’s urls.py
and put add the following code.
djangooauth/urls.py
Copied!#... from django.urls import path, include from django.views.generic import TemplateView from django.contrib.auth.views import LogoutView urlpatterns = [ #... path('', TemplateView.as_view(template_name="index.html")), path('accounts/', include('allauth.urls')), path('logout', LogoutView.as_view()), ]
We create a base route that will display our index.html
template. We also add the /accounts
route, which “includes” django-allauth URLs. This route will be used for all OAuth activities. At /logout
, we also include the normal Django logout view.
Step 4 – Create and configure a new Google APIs project
Head over to Google Developer APIs Console and create a new project.
Then, register your app by filling the OAuth consent screen.
Then, create a new OAuth client ID under Credentials. Select Web application for the Application type.
Then, add:
-
http://127.0.0.1:8000
under Authorized JavaScript origins. -
http://127.0.0.1:8000/accounts/google/login/callback/
under Authorized redirect URIs.
After a successful OAuth client ID creation, copy Your Client ID
and Your Client Secret
, you will need them in step 5.
Step 5 – Add a social app in Django admin
Now, make the migrations using this command:
Copied!$ python manage.py migrate
Then, create a superuser by running the following command in a terminal.
Copied!$ python manage.py createsuperuser
Run the app using:
Copied!$ python manage.py runserver
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:
- Provider: Google
- Name: OAuth App
- Client id: <The client ID you created in step 4>
- Secret key: <The Secret key you created in step 4>
- Sites: 127.0.0.1:8000
Since you are currently logged in as a superuser, logout and login again using your Google account.
If you get an error: SocialApp matching query does not exist
at http://127.0.0.1:8000/accounts/google/login/, it means that the ID of the site you created in Django admin is not the same as the one in settings.py
. Consider playing around with the SITE_ID
value.
For example: SITE_ID = 3
, etc.
For more information look at Django “sites” framework docs.
After signing in with Google, you can check the user information obtained from Google at: http://127.0.0.1:8000/admin/socialaccount/socialaccount/
.
Google provides little information about its users. To get more user information from Google, your app needs to be verified.
Conclusion
With Django OAuth packages like django-allauth, you can incorporate Google OAuth into your Django application. Django-allauth can also be used to incorporate other OAuth services.
Please share your thoughts on the Django Google OAUTH lesson in the comments area below. We look forward to hearing from you.
Leave a Reply