Django Authentication With GitHub

Django Authentication With GitHub


In this tutorial, we will build a Django application that allow users to sign in via their GitHub account.

Sample Project


$ mkdir django-github-authentication && cd django-github-authentication
$ pipenv install django django-allauth
$ pipenv shell
$ django-admin startproject config .
$ python manage.py startapp posts

Open settings.py and make the following changes:


from django.urls import reverse_lazy

INSTALLED_APPS = [
    ...
    'django.contrib.sites',
    'allauth',
    'allauth.account',
    'allauth.socialaccount',
    'allauth.socialaccount.providers.github',

    'posts.apps.PostsConfig',
]

TEMPLATES = [
    {
        ...
        'DIRS': [BASE_DIR, 'templates'],
        ...
    },
]

AUTHENTICATION_BACKENDS = (
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
)

ACCOUNT_EMAIL_VERIFICATION = 'none'

LOGIN_REDIRECT_URL = reverse_lazy('posts:post-list')

SITE_ID = 1

Open the models.py in posts applications and make it look like the following:


from django.db import models


class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()

    def __str__(self):
        return self.title

Run database migrations using the following commands.


$ python manage.py makemigrations
$ python manage.py migrate

Python interactive shell
We will use the interactive Python shell to create new posts. To start the Python shell, use the following command:


$ python manage.py shell

>>> from posts.models import Post
>>> Post.objects.create(title='My First Post', content='My First Content')
>>> Post.objects.create(title='My Second Post', content='My Second Content')

Now that we have create a few posts, we can proceed and create a list view.
Open views.py in posts application and add the following:


from django.views.generic import ListView

from .models import Post


class PostListView(ListView):
    model = Post
    context_object_name = 'posts'

Now we have to create a template for our view, in the root of the project create a templates folder and inside that create a posts folder and inside posts folder create a file called post_list.html.
Your directory structure should look like following:


➜ tree .
.
├── Pipfile
├── Pipfile.lock
├── config
│   ├── __init__.py
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── db.sqlite3
├── manage.py
├── posts
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   │   ├── 0001_initial.py
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
└── templates
    └── posts
        └── post_list.html

Now open post_list.html and make it look like following:

{% load socialaccount %}
{% load account %}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

{% if user.is_authenticated %}
Hi: {% user_display user %}
{% for post in posts %}
    {{ post.title }}
    {{ post.content }}
{% endfor %}
{% else %}
<p>Please <a href="{% provider_login_url 'github' %}">Authenticate with GitHub</a></p>
{% endif %}


</body>
</html>
This is only for test purpose, we want to see that our GitHub authentication works.
Inside posts application create urls.py file with the following content:


from django.urls import path

from .views import PostListView

app_name = 'posts'

urlpatterns = [
    path('', PostListView.as_view(), name='post-list'),
]

We should include posts urls in our root urls, open urls.py in config application and modify it too look like this:


from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('allauth.urls')),
    path('posts/', include('posts.urls'))
]

Now start the development server and navigate to http://localhost:8000/posts
You should see the Please Authenticate with Github message.
Navigate to https://github.com/settings/applications/new and create a new OAuth application:





Create a superuser and navigate to http://localhost:8000/admin


$ python manage.py createsuperuser

Open sites and change the domain to 127.0.0.1



Now go to Social applications in the admin dashboard and add the credentials you got from GitHub.
We need the Client ID and the Secret ID.



Logout from the Django admin and navigate to http://localhost:8000/posts and click on the link to authenticate with GitHub.
If everything worked you should see the Authorize page, click on Authorize <your github username> and you will be redirected back and you should see the posts you created earlier.



That's it, we have implemented the GitHub authentication and you could also try implementing authentication with Facebook or LinkedIn.



Check out sample project at GitHub


Share this: