Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Django
  • Views
  • Model
  • Template
  • Forms
  • Jinja
  • Python SQLite
  • Flask
  • Json
  • Postman
  • Interview Ques
  • MongoDB
  • Python MongoDB
  • Python Database
  • ReactJS
  • Vue.js
Open In App
Next Article:
Access a Site with Two-Factor Authentication Using Python Requests
Next article icon

Securing Django Admin login with OTP (2 Factor Authentication)

Last Updated : 01 Nov, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

Multi factor authentication is one of the most basic principle when adding security for our applications. In this tutorial, we will be adding multi factor authentication using OTP Method. This article is in continuation of Blog CMS Project in Django. Check this out here – Building Blog CMS (Content Management System) with Django

Setup 2 Factor Authentication for Django Project

We will install TOTP package for our blog CMS which will add OTP security for our admin login. First install django-otp package

pip install django-otp

 and add ‘django_otp, django_otp.plugins.otp_totp‘ in our installed apps and django_otp.middleware.OTPMiddleware in middleware section of our settings file. 

Python3

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_otp',
    'django_otp.plugins.otp_totp'
  
]
  
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',
    'django_otp.middleware.OTPMiddleware'
]
                      
                       

Now run,

# migrate our app  python3 manage.py migrate

Creating a TOTP Device – 

Now log into django admin to create an TOTP device. You can see it after logging in

login page

Click add and fill the details to create a new TOTP qrcode

add TOTP devices

 Now again go into totp device section and open the QRcode and scan it with your TOTP apps like Authy, Google Authenticator apps.

scan the qrcode

Set Admin OTP Class –

Now go into django urls.py file in gfgblog, not in blog urls.py and add the lines

Python3

from django_otp.admin import OTPAdminSite
  
admin.site.__class__ = OTPAdminSite
                      
                       

Output –

Now logout and login into django admin you have enter OTP everytime you need to login into django admin.

django admin with OTP

Some Basic Security Principles to follow

  • Keep Debug = False in Production
  • Limit Allowed hosted to our Server IP, localhost, and hostnames
  • Keep Secret key strong and safe
  • All ways use HTTPS  in Production
  • Keep a check on user uploads if being managed by multiple users
  • Keep your database secure and don’t use SQLite in Production
  • Try to use Security and content headers in production, a few headers are given below add these in Settings.py

Python3

SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_SECURE = True
SECURE_BROWSER_XSS_FILTER = True
SECURE_HSTS_SECONDS = 31536000
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
SECURE_CONTENT_TYPE_NOSNIFF = True
CSRF_COOKIE_SECURE = True
                      
                       


Next Article
Access a Site with Two-Factor Authentication Using Python Requests
author
kushwanthreddy
Improve
Article Tags :
  • Python
  • Technical Scripter
  • Python Django
  • Technical Scripter 2020
Practice Tags :
  • python

Similar Reads

  • JWT Authentication with Django REST Framework
    JSON Web Token is an open standard for securely transferring data within parties using a JSON object. JWT is used for stateless authentication mechanisms for users and providers, this means maintaining session is on the client-side instead of storing sessions on the server. Here, we will implement t
    2 min read
  • Access a Site with Two-Factor Authentication Using Python Requests
    web security is of paramount importance, and many websites implement two-factor authentication (2FA) to enhance security. This additional layer of security ensures that even if someone obtains your password, they cannot access your account without the second form of verification, usually a code sent
    4 min read
  • OAuth2 Authentication with Spring and Github
    OAuth2 is a secure way to allow users to log in to your application using third-party providers like GitHub. Instead of creating a custom login system, we can use GitHub’s authentication to verify users and grant access. Working of OAuth2Imagine a user wants to log in to your app using GitHub. When
    2 min read
  • How to Add Authentication to App with Flask-Login
    We can implement authentication, login/logout functionality in flask app using Flask-Login. In this article, we'll explore how to add authentication to a Flask app using Flask-Login. To get started, install Flask, Flask-Login, Flask-SQLAlchemy and Werkzeug using this command: pip install flask flask
    6 min read
  • Django Authentication Project with Firebase
    Django is a Python-based web framework that allows you to quickly create efficient web applications.. When we are building any website, we will need a set of components: how to handle user authentication (signing up, signing in, signing out), a management panel for managing our website, how to uploa
    7 min read
  • Django Sign Up and login with confirmation Email | Python
    Django by default provides an authentication system configuration. User objects are the core of the authentication system. Today we will implement Django's authentication system. Modules required: Django install, crispy_forms Django Sign Up and Login with Confirmation EmailTo install crispy_forms yo
    7 min read
  • Using JWT for user authentication in Flask
    JWT (JSON Web Token) is a compact, secure, and self-contained token used for securely transmitting information between parties. It is often used for authentication and authorization in web applications. A JWT consists of three parts: Header - Contains metadata (e.g., algorithm used for signing).Payl
    7 min read
  • Python Django | Google authentication and Fetching mails from scratch
    Google Authentication and Fetching mails from scratch mean without using any module which has already set up this authentication process. We'll be using Google API python client and oauth2client which is provided by Google. Sometimes, it really hard to implement this Google authentication with these
    12 min read
  • Implement Token Authentication using Django REST Framework
    Token authentication refers to exchanging username and password for a token that will be used in all subsequent requests so to identify the user on the server side.This article revolves about implementing token authentication using Django REST Framework to make an API. The token authentication works
    2 min read
  • Two-Factor Authentication using Google Authenticator in Python
    Two Factor Authentication or 2FA is an advanced method of user authentication and a subset of multi-factor authentication mechanisms. 2FA enhances the security of its user accounts by adding another layer of authenticity challenge after traditional passwords are used in single-factor authentication.
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences