Enabling GitHub OAuth in Django

PythonServer Side ProgrammingProgramming

In many developer websites, we get to see GitHub social authentication which is very handy. In this article, we will see how to add Github Auth in our Django website.

Go to https://github.com/settings/developers/ and create an Oauth application and add these two URLs

Then, you will get a Client ID and a secret key. Now, let's move to the coding part.


Install the django-allauth library −

pip install django-allauth

In settings.py add the following lines of code −





n INSTALLED APPS, we added the import libraries we need and then we added GitHub default authentication backend. We also enabled a Redirect URL which will tell where to redirect on login.

In urls.py of project root −

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

urlpatterns = [
   path('admin/', admin.site.urls),

   # this is module path copy this as it is
path('accounts/', include('allauth.urls')),

# this is my app path
path('', include("githubAuthentication.urls"))

Here, we added the default path that is needed to add; it is allauth library path for enabling GitHub login. Second one is the app path that we made.

Now go to http://localhost:8000/admin and go to social application.

And, add an application −

Paste the client ID and secret key that you copied earlier and the name should be application name, choose provider github.

In sites section, click example.com and then click the arrow key and hit save. This will register github on your Django project as an authentication backend.

Now, create home.html in the templates folder and add the following lines −

<!DOCTYPE html>
      {% load socialaccount %}
      {% providers_media_js %}
<a href="{% provider_login_url 'github' method='js_sdk' %}?n
ext=https://github.com">login with github</a>

Here, we simply rendered the JS and loaded the allauth library on frontend. In <a> we provided the github login page on which we set up our default github login page.

In view.py

from django.shortcuts import render

# Create your views here.
def home(request):
   return render(request,"home.html")

We rendered our frontend here

In urls.py (app urls) −

from django.urls import path,include
from . import views
urlpatterns = [
   path('',views.home, name="Home" ),


We set up urls here and rendered our views.

Everything is done, now you can proceed to check the output.


Published on 26-Aug-2021 11:36:02