Geek Culture
Published in

Geek Culture

Django Social Authentication: Sign In With GitHub

How to sign in and sign up using GitHub in Django framework web apps

Login with GitHub using the Django framework

Hello, Django Developers..!!

My name is Rohit Kumar Thakur. I generally write about React Native, Django, Data Science, Machine Learning, and Python.

In this article, I am going to show you how to use social authentication in Django applications. When you are building a web application, then adding GithHub authentication is the most common feature you can add. It will help users to log in to your website easily. So, without wasting any time let’s start this project.

Here is the step by step video tutorial of this article:

Project Setup

  • I always suggest starting a Django project in a virtual environment because it’s a good habit to practice.
  • Choose a directory. Open the terminal or command prompt window in that directory and start a virtual environment. Activate that virtual environment. I wrote a separate article on how to start a virtual environment in Windows and Linux. You can check if you need help.
  • After activating the virtual environment, install the following python library:
pip install django
pip install social-auth-app-django
  • Start a Django project:
django-admin startproject github
cd github
python manage.py startapp mainApp
  • Open this project in your favorite text editor. I mean VS Code. xd:)

Code

settings.py

INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'social_django', #add this
'mainApp', #add this
]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',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'social_django.middleware.SocialAuthExceptionMiddleware', #add this
]TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'social_django.context_processors.backends', #add this
],
},
},
]
#Add this at the bottom in settings.py
#social app custom settings

AUTHENTICATION_BACKENDS = [
'social_core.backends.github.GithubOAuth2',
'django.contrib.auth.backends.ModelBackend'
]
LOGIN_URL = 'login'
LOGIN_REDIRECT_URL = 'home'
LOGOUT_URL = 'logout'
LOGOUT_REDIRECT_URL = 'login'
SOCIAL_AUTH_GITHUB_KEY = '############'
SOCIAL_AUTH_GITHUB_SECRET = '########################'

In the settings.py. We need to add a few lines of code to INSTALLED_APPS, MIDDLEWARE, and TEMPLATES sections. After that, we have to add a few lines of code at the bottom as shown above.

views.py

from django.shortcuts import render
from django.contrib.auth.decorators import login_required
# Create your views here.def login(request):
return render(request, 'login.html')
@login_required
def home(request):
return render(request, 'home.html')

In views.py, first, we are going to import all the required libraries. After that, write two functions to render the login and home screen.

Now inside the mainApp directory. Make a new directory “templates”. Inside the templates directory, make three new files: base.html, login.html, home.html

Make a static folder too. Inside the mainApp directory. And inside the static directory, make a file “index.css

You can customize the CSS part on your own if you want. But for a minimal UI reference, you can add the following codes to the index.css file.

.container-fluid {
height: 100vh;
background-color: #fff;
display: flex;
justify-content: center;
align-items: center;
}.container-fluid > div {
width: 85%;
min-width: 300px;
max-width: 500px;
}.card{
width: 100%;
background-color: #282c34;
}.social-container {
display: flex;
flex-direction: column;
justify-content: center;
}.btn a, .btn a:hover {
color: white;
text-decoration: none;
}

base.html

{% load static %}<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="{% static 'index.css' %}" />
<title>DJANGO SOCIAL AUTH</title>
</head>
<body>
<div class="container-fluid">
<div>
<h1 class="text-white text-center">
{% block title %}
{% endblock %}
</h1>
<div class="card p-5">
{% block content %}
{% endblock %}
</div>
</div>
</div>
</body>
</html>

This is the code of the base.html file. We are going to take reference and relative tag elements in login.html and base.html.

login.html

{% extends 'base.html' %} 
{% block title %}Sign in{% endblock %}
{% block content %}
<div class="row">
<div class="col-md-8 mx-auto social-container my-2 order-md-1">
<button class="btn btn-primary mb-2">
<a href="{% url 'social:begin' 'github' %}">
LOGIN WITH GITHUB
</a>
</button>
</div>
</div>
{% endblock %}

home.html

{% extends 'base.html' %} 
{% block title %}HOME{% endblock %}
{% block content %}
<div class="row">
<div class="col-sm-12 mb-3">
<h4 class="text-center">Welcome {{ user.username }}</h4>
</div>
</div>
{% endblock %}

This is the basic code of login and home screen. After the successful login, we are going to display the name of the user on the home screen.

github/urls.py

from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from mainApp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', views.login, name='login'),
path('logout', auth_views.LogoutView.as_view(), name='logout'),
path('social-auth/', include('social_django.urls', namespace='social')),
path("", views.home, name='home'),
]

Add the URLs in the main directory.

Configure Github Developer Console

Now we have to do only one thing. Let’s set up Github Developer Profile. I recommend you watch the video after 18:32. The video is here.

  • You need a GitHub account.
  • Click on your profile. Then click on settings
  • Scroll down and click on developer settings (Left-Hand side)
  • Click on OAuth Apps
  • Click on Register a new application
  • Add application name: test
  • Homepage URL: http://localhost:8000
  • Authorization callback URL: http://localhost:8000/social-auth/complete/github/
  • Click on Register application
  • Generate client secret code.
  • Copy the client id and client secret and past it here:
SOCIAL_AUTH_GITHUB_KEY = '############'
SOCIAL_AUTH_GITHUB_SECRET = '########################'
  • If you checked the video then make sure to hit the subscribe button. I make cool Django and react native applications. Your support will be admired.

Now, Open your terminal or command prompt and migrate the Django application.

python manage.py makemigrations
python manage.py migrate
python manage.py runserver

Now click on the “Login with GitHub” button. You are good to go now.

GitHub Code Link

Now, clap, clap and clap! And do follow for more project-based articles on Django Framework.

Thanks for reading.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store