Two-Factor Authentication using Google Authenticator in Python
Last Updated :
26 Apr, 2025
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.
This article will show you how to implement Two-Factor Authentication using Google Authenticator App using a general-purpose programming language called Python.
Modules and Apps required
To implement this we need to use 3 modules –
- time – Inbuilt python module for time-related operations
- pyotp – to generate OTP
- QRcode – To generate QRcode
Run the following to install the required modules:
pip install pyotp qrcode
Users also need to Download and install the Google Authenticator app from the Playstore / Appstore onto their phones.
Importing required modules
Here we are going to import the required module.
Python3
import time
import pyotp
import qrcode
|
Generating the Key
Python3
k = pyotp.random_base32()
|
Using the random_base32() method of the pyotp module, random alphanumeric keys can be generated. Every time the code generates a new key making it impossible to recover in case it gets lost.
Python3
secret_key = "GeeksforGeeksIsBestForEverything"
|
We can also define a specific secret key like the above, we just have to pass this in the TOTP method in later steps, this will never change and will be easier to maintain.
Creating a Time-based OTP (TOTP)
In the following snippet, we are passing the secret_key into the TOTP and provisioning a URI (Uniform Resource Identifier) with the name of the user and the issuer_name, this way the issuer can generate multiple keys for different users, making it easier to identify them.
Python3
totp_auth = pyotp.totp.TOTP(
secret_key).provisioning_uri(
name = 'Dwaipayan_Bandyopadhyay' ,
issuer_name = 'GeeksforGeeks' )
print (totp_auth)
|
Output:
otpauth://totp/GeeksforGeeks:Dwaipayan_Bandyopadhyay?secret=GeeksforGeeksIsBestForEverything&issuer=GeeksforGeeks
The above output is the link that gets generated, but as Google Authenticator supports QR code scanning we would convert this into a QR code which we will scan through our Google Authenticator.
Generating a QR Code
Python3
qrcode.make(totp_auth).save( "qr_auth.png" )
totp_qr = pyotp.TOTP(secret_key)
|
Here the QR codes get saved with the name qr_auth and we can scan it and get some new code every time which we can enter in our python script to verify.
Steps to Setup Google Authenticator –
- Download the App from Playstore/AppStore.
- Follow the initial setup procedure till a blank screen is reached.
- Tap on the + sign at the lower right corner and select the Scan a QR Code Option.
- Scan the generated QR code.
- Now, a new account in the following format will be added with a TOTP which is valid for 30 seconds.
IssuerName (UserName)
<Unique Code that lasts for 30 seconds>
Verify the code using Python –
We can also verify the code generated using Python.
Python3
totp = pyotp.TOTP(secret_key)
while True :
print (totp.verify( input (( "Enter the Code : " ))))
|
Output:
The first code was the real one, second was to see what if we give a longer and different code result it returns, we can see that the first code after a while gives us the result False as it has expired, the code at the last line has taken its place for next 30 seconds.
Complete Implementation
Python3
import time
import pyotp
import qrcode
key = "GeeksforGeeksIsBestForEverything"
uri = pyotp.totp.TOTP(key).provisioning_uri(
name = 'Dwaipayan_Bandyopadhyay' ,
issuer_name = 'GeeksforGeeks' )
print (uri)
qrcode.make(uri).save( "qr.png" )
totp = pyotp.TOTP(key)
while True :
print (totp.verify( input (( "Enter the Code : " ))))
|
Note: Make sure to comment out the QR code generation step after the first execution or it will keep on generating a QR code every time the code is executed.
Similar Reads
How To Automate Google Chrome Using Foxtrot and Python
In this article, we are going to see how to automate google chrome using Foxtrot & Python. What is Foxtrot RPA?Robotic process automation (RPA) cuts down employeesâ workloads by automating repetitive, high-volume steps in processes. Software robots, such as Foxtrot RPA emulate the actions of hum
4 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
Simple Chatbot application using Python, GoogleAPIKey
Google-GenerativeAI is Google AI Python SDK. It uses Gemini to build AI-powered features. In this article, we will see how to create a Simple Chatbot application using Python GoogleAPIKey. What is Google-GenerativeAI?Google-GenerativeAI is nothing but Google AI Python SDK. It enables to use of Gemin
4 min read
Securing Django Admin login with OTP (2 Factor Authentication)
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
2 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
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
GUI chat application using Tkinter in Python
Chatbots are computer program that allows user to interact using input methods. The Application of chatbots is to interact with customers in big enterprises or companies and resolve their queries. Chatbots are mainly built for answering standard FAQs. The benefit of this type of system is that custo
7 min read
Authentication using Python requests
Authentication refers to giving a user permissions to access a particular resource. Since, everyone can't be allowed to access data from every URL, one would require authentication primarily. To achieve this authentication, typically one provides authentication data through Authorization header or a
2 min read
OAuth Authentication with Flask - Connect to Google, Twitter, and Facebook
In this article, we are going to build a flask application that will use the OAuth protocol to get user information. First, we need to understand the OAuth protocol and its procedure. What is OAuth? OAuth stands for Open Authorization and was implemented to achieve a connection between online servic
8 min read