Django-allauth Tutorial
Django comes with a robust built-in authentication system for users but it does not provide support for third-party (social) authentication via services like Github, Gmail, or Facebook. Fortunately, the excellent 3rd party django-allauth package does.
In this tutorial, we'll cover how to add login with GitHub to a basic Django site, but the process is almost identical for other 3rd party services, including Facebook, Gmail, and dozens and dozens more.
Initial Setup
Let's begin by creating a new Django project. We'll put the code on the desktop for convenience, but really it can live anywhere on your computer. Make a new directory called django_allauth
, create a new virtual environment called .venv
and activate it.
# Windows $ cd onedrive\desktop\ $ mkdir django_auth $ cd django_auth $ python -m venv .venv $ .venv\Scripts\Activate.ps1 (.venv) $ python -m pip install django~=5.0.0 # macOS $ cd ~/desktop/ $ mkdir django_auth $ cd django_auth $ python3 -m venv .venv $ source .venv/bin/activate (.venv) $ python3 -m pip install django~=5.0.0
Then create a new project called django_project
, migrate the initial database, and execute the runserver
command to start up the local web server.
(.venv) $ django-admin startproject django_project . (.venv) $ python manage.py migrate (.venv) $ python manage.py runserver
If you navigate to http://127.0.0.1:8000/, you should see the default Django welcome screen.
django-allauth
Install and configure django-allauth
using pip
. Press the Control+c
keys to quit the server, and then on the command line, type the following:
(.venv) $ python -m pip install django-allauth==0.60.0
There are several configuration changes to make in the django_project/settings.py
file, and the order here is important, so make sure to match the same hierarchy as the code below:
- update
INSTALLED_APPS
withdjango.contrib.sites
,allauth
,allauth.account
,allauth.socialaccount
, andallauth.socialaccount.providers.github
for GitHub - update
MIDDLEWARE
withallauth.account.middleware.AccountMiddleware
- make AUTHENTICATION_BACKENDS explicit and add
allauth.account.auth_backends.AuthenticationBackend
- set a
SITE_ID
of1
- set
ACCOUNT_EMAIL_VERIFICATION
tonone
. You can change this later if desired. - set
LOGIN_REDIRECT_URL
to the home page,/
# django_project/settings.py INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "django.contrib.sites", # new "allauth", # new "allauth.account", # new "allauth.socialaccount", # new "allauth.socialaccount.providers.github", # new for GitHub provider ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "allauth.account.middleware.AccountMiddleware", # new "django.middleware.clickjacking.XFrameOptionsMiddleware", ] AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend", # new ] SITE_ID = 1 # new ACCOUNT_EMAIL_VERIFICATION = "none" # new LOGIN_REDIRECT_URL = "/" # new # new below SOCIALACCOUNT_PROVIDERS = { "github": { "APP": { "client_id": "123", "secret": "456", } } }
We need to configure django-allauth
in the django_project/urls.py
file. Make sure to add the import for include
on the second line and add a new path for accounts/
.
# django_project/urls.py from django.contrib import admin from django.urls import path, include # new urlpatterns = [ path("admin/", admin.site.urls), path("accounts/", include("allauth.urls")), # new ]
Update the database with these changes using the migrate
command.
(.venv) $ python manage.py migrate
GitHub OAuth
OAuth is an open standard for authentication between systems. When a user logs into our site with their GitHub account, we will redirect them to Github, which then sends us a token representing the user.
To configure a new OAuth application on Github, go to https://github.com/settings/applications/new. It's important to fill out the Application Name, Homepage URL, and Authorization callback URL. The Application description is optional.
The Application name is what the user will see requesting permission to access their Github account. The Homepage URL is as described. The Authorization callback URL takes a particular form for each integration as defined in the django-allauth docs. For example, here it is for GitHub.
You'll be redirected to the following page after hitting the "Register application" button.
Pay particular attention to the Client ID and Client secrets. We'll be using those shortly. Also, note that in the real world, you'd never want to reveal either of these keys publicly! They should be stored in environment variables.
Django admin
Next we need to configure the admin section of our Django project to work with django-allauth
. To start, create a new superuser so we can log in. Make sure the email provided is not the same as the email for your GitHub account.
(.venv) $ python manage.py createsuperuser
Now we can start the server again with python manage.py runserver
and navigate to the admin page http://127.0.0.1:8000/admin
. Use your newly created superuser credentials to log in.
The admin homepage should look like this now:
We need to make two updates in the admin for django-allauth
to work correctly:
- update
Sites
- update
Social Applications
Let's begin with Sites. Click on the link and set the domain to 127.0.0.1
; the display name can remain as is.
When you deploy your Django application live, you'd replace 127.0.0.1
here and on GitHub with your actual production homepage.
Next, go back to the admin homepage and click on the add button for Social Applications
at the bottom. This is where you configure each third-party OAuth. We're using Github, so that's the Provider
. We add a name and then the Client ID and Secret ID from GitHub. The final step--and easy to forget--is to add our site to the Chosen sites
at the bottom. Then click save.
Believe it or not, things are all wired up now. The last step is to create a homepage we can try it out on. Click on the "Log out" link in the upper right-hand corner of the admin.
Basic Homepage
We'll build a simple homepage that will allow us to confirm the GitHub social authentication works. Typically, these would go in a dedicated app, but for demonstration purposes, we can do it mainly within the existing django_project/urls.py
file. At the top, import TemplateView
and create a route using the template home.html
.
# django_project/urls.py from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView # new urlpatterns = [ path("admin/", admin.site.urls), path("accounts/", include("allauth.urls")), path("", TemplateView.as_view(template_name="home.html")), # new ]
Create a templates
directory on the command line.
(.venv) $ mkdir templates
And edit the TEMPLATES
configuration within the settings.py
file by setting DIRS
to point to this new directory. Now Django's template loader will know to look within the templates
directory for any templates we add.
# django_project/settings.py TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [BASE_DIR / "templates"], # new ...
As a final step, create a new file called templates/home.html
file that loads the socialaccount
tag from django-allauth
. If a user is logged in, the template will provide a greeting; otherwise, it will display a "Sign Up with GitHub" link.
<!-- templates/home.html --> {% load socialaccount %} <h1>Django Allauth Tutorial</h1> {% if user.is_authenticated %} <p>Welcome {{ user.username }} !!!</p> {% else %} <a href="#">Sign Up with GitHub</a> {% endif %}
Putting It All Together
Start the local server with the runserver
command and view the logged-out page.
Click on the button for "Sign Up with GitHub," and you'll be redirected to the Github authorize page.
Click on the "Authorize" button and you'll be redirected back to our homepage with a greeting for your Github account name.
Conclusion
We're all done! The process for adding social authentication from other providers is almost identical. django-allauth
also comes with a robust list of customizations we can add, including a logout link, requiring email confirmation, and much more. I encourage you to refer to
the official docs from here for more information.