Two-Factor Authentication (2FA) in Python

NeuralNine · Beginner ·📰 AI News & Updates ·3y ago

Key Takeaways

This video demonstrates how to implement two-factor authentication (2FA) in Python using the Pi OTP library and Google Authenticator app, covering the generation and verification of one-time passwords (OTPs) for secure login.

Full Transcript

what is going on guys welcome back in today's video we're going to learn how to do two-factor authentication with one-time passwords in Python so let us get right into it [Music] all right so I think most people are familiar with the concept of two-factor authentication and one-time passwords the basic idea is that you have an extra layer of security when you log into a service so you enter username and password but then to make sure it's really you you also get a code for example onto your phone in your authenticator app and you need to enter this code to finish the login process so if someone else knows your username and password they can try to log in even though they have the correct combination they will not be able to log in because they don't know the code that was sent to your phone for example so they would need to have both these things to log into your account and this is harder to crack harder to hack essentially if you have two-factor authentication and in this video today what we're going to do is we're going to implement that in Python we're going to see how we can generate one-time passwords and how we can verify them with our own secret key so we're going to choose a secret key or to generate a secret key and then we're going to issue new one-time passwords and we can also verify them and this can be used then in a secure login system so we're going to start by opening up the command line and saying pip install Pi OTP so Pi one-time password is the library that we're going to use in this video today and what we're going to do first is we're going to import time we're going to also import Pi OTP and the first thing we need to decide on is the key now as I said we can just generate the key so we can say key equals piotp dot random base 32 and then we can print that key and this would then be our key now one thing that you need to understand is if someone has this key this same key they will generate the same one-time password so this is something that should be completely secret only you as the service provider should have that key and no one else should have that key because if they have the same key they don't need to request uh your one-time passwords they can just generate it themselves so if someone has the same key as you they will generate the same one-time passwords as you so they don't need you to get the one-time passwords this is very important we can also set this manually so we can say key equals I don't know neural 9 my super secret key or something like that um and this can then be the uh the the uh the base key for our one-time passwords and we're going to start with time-based one-time passwords the basic idea here being that every 30 seconds we get a new one-time password this is what you oftentimes uh have in different Services I think on Steam for example you have the steam guard where you log into your steam account and then you have to if you have enabled two-factor authentication you have to enter a six digit code and after 30 seconds it expires and you have to enter another code to log in so in order to do that here in Python we have to say totp for time-based one-time password this is going to be equal to piotp.totp in capital letters and we're going to pass here the key as the base and what we can do now is we can just say print totp Dot dot now since this is a time-based one it's always based on the time so now you can see it's zero zero zero two seven four I can run this again now um it's it's a different one but if I run it now again it's always the same one for 30 seconds so I can run this a lot of times after 30 seconds it will be a different code so I can always rerun this you can see it's the same code this would be the correct code for verification but after 30 seconds it will be a different code and we can actually try this out so we can actually say time sleep 30 and then print the same thing so now it's still the same we can just keep this running here as um we talk about one-time passwords but that's the basic idea so if you want to have a secure login system where you also integrate two-factor authentication you would um have a QR code to be scanned by the user I'm going to show you how to do that in the end and then the user would just uh on their app on the Google Authenticator app for example see okay this is the one-time password if I want to log into the service I have to enter this and we can verify this using the verify method that I'm going to show you here in a second as you can see now the code is a different one because enough time has passed um and we can actually go ahead now and just say something like input code is equal to input enter to f a code and then we're going to say the code that we should interest totp dot now and we're going to print whether the input code is the same as the code um oh sorry uh this was not how we want to do it I mean this is probably also a possibility but what you actually want to do is want to say totp.verify and you want to verify the input code because this does this automatically so we get the code that we put in and then we verified with that totp object with which we'll just check if this code is the same as the now code but it will do so in the exact moment so if I do this fast enough 585 zero seven nine if I'm not unlucky now okay in this case we also need to print the result obviously five eight five zero seven nine true okay so if I try the same code obviously now at the moment it's still a code if I wait now I don't know 20 seconds or something and then I enter the same code it will say it's no longer the valid code because the code has expired I will now have a new code that's the basic idea I'm not sure if this is already the case I'm going to just wait a couple more seconds and this is how you can check that right so you have a login you say okay please enter your one-time password then you look into your authenticator app you enter it fast enough so I can try this now it says false even though it was true a couple of seconds ago now it's false because the code has expired that's the basic idea of the totp now we also have the hotp which is the counter-based password so we can say the counter is equal to zero and then we can say hotp is equal to Pi T piotp dot hotp based on this key and we can say print hotp at and then we can just provide a number so this will always be the same this is not time based so the value at 0 will always be the same for this key and I can also change this to one two three four you can see those values will always be the same that's the basic idea here and we can also uh verify now so we can uh we can just say for example four counter in Range Five For example we can say print hotp dot verify and we want to verify whatever we put in so input enter code and we want to verify it for a certain counter so we're going to pass the counter here and we're going to say counter plus equals one and then I can do one for uh one seven one eight this should be true if I put in something else so if I do the same thing one for one seven one eight it says false because I should have entered this one it still increased the counter so the next code that I would have to enter here oh I cannot type because my Vim plugin is a little bit buggy so let me just restart this briefly uh so again the first one is one for one seven one eight now I can put in something else here it doesn't work and then the next one would be seven eight four eight four three this would work again so it's a counter based one it will always have the same values for the same number and for the same key so that's the basic idea of the different of these two uh one-time passwords now we're going to take a look at how we can generate a URI that can be scanned by a Google authenticator app in the form of a QR code if you want to do this in the form of a QR code you have to install an additional Library so you want to open up your command line pip install QR code is the library so you want to do it like that um and then what we want to do is we we just want to generate the URI by saying URI equals Pi otp.totp.totp then we pass the key and then we say dot provisioning URI and the name is the name of the user so if you have the username of the respective person you can say okay uh mic smith123 is the username for example in the service so the issuer name we issue these one-time passwords is neural 9 app or something like that so the application name this will also be displayed in the authenticator app so we can print this your eye and this is already enough so we can already take this here this OTP off URI and you can use it like that but if you want to scan it with a QR code all you need to do is you need to say QR code.make URI dot safe and then totp dot PNG for example just a file name we also need to import QR code and then when I run this I get this image here you can try to scan it with your Google Authenticator app I'm going to do exactly that so I'm going to go into my authenticator right now you can hopefully see let me just see my camera here on the second screen um I have two authentication for Discord and another service and now I'm going to just scan this with a QR code so you can just in the Google Authenticator app you have this QR code scanner I can scan this and it automatically added here the neural 9 app I'm not sure if you're seeing this correctly here but you can see neural 9 app for Mike smith123 and we can always see how the uh code expires and how it refreshes and gives me a new one so I can actually now go ahead and without generating anything in this script here I can just say totp equals Pi OTP dot verify or actually sorry I need to create the object first so key and then I can just say print or I can see while true print totp verify and I can just input enter code so I can run this now and I can always enter the code and it's going to tell me if it's valid or not so let me just enter something here this is false and now on my app I see what the current code is it's three five two five five six true there you go so it's still that code but if I try it now here in a second so three five two five five six it's false but now it's one nine eight seven five three there you go true again so this works with the Google Authenticator app um and yeah this is how you do two-factor authentication in Python so that's it for today's video I hope you enjoyed it and hope you learned something if so let me know by hitting a like button and leaving a comment in the comment section down below and of course don't forget to subscribe to this Channel and hit the notification Bell to not miss a single future video for free other than that thank you much for watching see you next video and bye foreign [Music]

Original Description

Today we learn how to generate and verify one-time passwords (OTP) for two-factor authentication (2FA) in Python. ◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾◾ 📚 Programming Books & Merch 📚 🐍 The Python Bible Book: https://www.neuralnine.com/books/ 💻 The Algorithm Bible Book: https://www.neuralnine.com/books/ 👕 Programming Merch: https://www.neuralnine.com/shop 🌐 Social Media & Contact 🌐 📱 Website: https://www.neuralnine.com/ 📷 Instagram: https://www.instagram.com/neuralnine 🐦 Twitter: https://twitter.com/neuralnine 🤵 LinkedIn: https://www.linkedin.com/company/neuralnine/ 📁 GitHub: https://github.com/NeuralNine 🎙 Discord: https://discord.gg/JU4xr8U3dm 🎵 Outro Music From: https://www.bensound.com/ Timestamps: (0:00) Intro (0:18) Time-Based OTP (6:25) Counter-Based OTP (8:28) Google Authenticator QRCode (11:46) Outro
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from NeuralNine · NeuralNine · 0 of 60

← Previous Next →
1 Visualizing Stock Data With Candlestick Charts in Python
Visualizing Stock Data With Candlestick Charts in Python
NeuralNine
2 Python Beginner Tutorial #1 - Installation and First Program
Python Beginner Tutorial #1 - Installation and First Program
NeuralNine
3 Python Beginner Tutorial #2 - Variables and Data Types
Python Beginner Tutorial #2 - Variables and Data Types
NeuralNine
4 Python Beginner Tutorial #3 - Operators and User Input
Python Beginner Tutorial #3 - Operators and User Input
NeuralNine
5 Python Beginner Tutorial #4 - If Statements and Conditions
Python Beginner Tutorial #4 - If Statements and Conditions
NeuralNine
6 Python Beginner Tutorial #5 - Loops
Python Beginner Tutorial #5 - Loops
NeuralNine
7 Python Beginner Tutorial #6 - Sequences and Collections
Python Beginner Tutorial #6 - Sequences and Collections
NeuralNine
8 Python Beginner Tutorial #7 - Functions
Python Beginner Tutorial #7 - Functions
NeuralNine
9 Python Beginner Tutorial #8 - Exception Handling
Python Beginner Tutorial #8 - Exception Handling
NeuralNine
10 Python Beginner Tutorial #9 - File Operations
Python Beginner Tutorial #9 - File Operations
NeuralNine
11 Python Beginner Tutorial #10 - String Functions
Python Beginner Tutorial #10 - String Functions
NeuralNine
12 Python Intermediate Tutorial #1 - Classes and Objects
Python Intermediate Tutorial #1 - Classes and Objects
NeuralNine
13 Python Intermediate Tutorial #2 - Inheritance
Python Intermediate Tutorial #2 - Inheritance
NeuralNine
14 Python Intermediate Tutorial #3 - Multithreading
Python Intermediate Tutorial #3 - Multithreading
NeuralNine
15 Python Intermediate Tutorial #4 - Synchronizing Threads
Python Intermediate Tutorial #4 - Synchronizing Threads
NeuralNine
16 Python Intermediate Tutorial #5 - Events and Daemon Threads
Python Intermediate Tutorial #5 - Events and Daemon Threads
NeuralNine
17 Python Intermediate Tutorial #6 - Queues
Python Intermediate Tutorial #6 - Queues
NeuralNine
18 Python Intermediate Tutorial #7 - Sockets and Network Programming
Python Intermediate Tutorial #7 - Sockets and Network Programming
NeuralNine
19 Python Intermediate Tutorial #8 - Database Programming
Python Intermediate Tutorial #8 - Database Programming
NeuralNine
20 Python Intermediate Tutorial #9 - Recursion
Python Intermediate Tutorial #9 - Recursion
NeuralNine
21 Python Intermediate Tutorial #10 - XML Processing
Python Intermediate Tutorial #10 - XML Processing
NeuralNine
22 Python Intermediate Tutorial #11 - Logging
Python Intermediate Tutorial #11 - Logging
NeuralNine
23 Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
Python Data Science Tutorial #1 - Anaconda and PyCharm Setup
NeuralNine
24 Python Data Science Tutorial #2 - NumPy Arrays
Python Data Science Tutorial #2 - NumPy Arrays
NeuralNine
25 Python Data Science Tutorial #3 - Numpy Functions
Python Data Science Tutorial #3 - Numpy Functions
NeuralNine
26 Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
Python Data Science Tutorial #4 - Plotting Functions With Matplotlib
NeuralNine
27 Python Data Science Tutorial #5 - Subplots and Multiple Windows
Python Data Science Tutorial #5 - Subplots and Multiple Windows
NeuralNine
28 Python Data Science Tutorial #6 - Matplotlib Styling
Python Data Science Tutorial #6 - Matplotlib Styling
NeuralNine
29 Python Data Science Tutorial #7 - Bar Charts with Matplotlib
Python Data Science Tutorial #7 - Bar Charts with Matplotlib
NeuralNine
30 Python Data Science Tutorial #8 - Pie Charts with Matplotlib
Python Data Science Tutorial #8 - Pie Charts with Matplotlib
NeuralNine
31 Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
Python Data Science Tutorial #9 - Plotting Histograms with Matplotlib
NeuralNine
32 Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
Python Data Science Tutorial #10 - Scatter Plots with Matplotlib
NeuralNine
33 Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
Python Data Science Tutorial #11 - 3D Plotting with Matplotlib
NeuralNine
34 Python Data Science Tutorial #12 - Pandas Series
Python Data Science Tutorial #12 - Pandas Series
NeuralNine
35 Python Data Science Tutorial #13 - Pandas Data Frames
Python Data Science Tutorial #13 - Pandas Data Frames
NeuralNine
36 Python Data Science Tutorial #14 - Pandas Statistics
Python Data Science Tutorial #14 - Pandas Statistics
NeuralNine
37 Python Data Science Tutorial #15 - Pandas Sorting and Functions
Python Data Science Tutorial #15 - Pandas Sorting and Functions
NeuralNine
38 Python Data Science Tutorial #16 - Pandas Merging Data Frames
Python Data Science Tutorial #16 - Pandas Merging Data Frames
NeuralNine
39 Python Data Science Tutorial #17 - Pandas Queries
Python Data Science Tutorial #17 - Pandas Queries
NeuralNine
40 Python Machine Learning Tutorial #1 - What is Machine Learning?
Python Machine Learning Tutorial #1 - What is Machine Learning?
NeuralNine
41 Python Machine Learning Tutorial #2 - Linear Regression
Python Machine Learning Tutorial #2 - Linear Regression
NeuralNine
42 Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
Python Machine Learning Tutorial #3 - K-Nearest Neighbors Classification
NeuralNine
43 Python Machine Learning #4 - Support Vector Machines
Python Machine Learning #4 - Support Vector Machines
NeuralNine
44 Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
Python Machine Learning Tutorial #5 - Decision Trees and Random Forest Classification
NeuralNine
45 Python Machine Learning Tutorial #6 - K-Means Clustering
Python Machine Learning Tutorial #6 - K-Means Clustering
NeuralNine
46 Python Machine Learning Tutorial #7 - Neural Networks
Python Machine Learning Tutorial #7 - Neural Networks
NeuralNine
47 Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
Python Machine Learning Tutorial #8 - Handwritten Digit Recognition with Tensorflow
NeuralNine
48 Generating Poetic Texts with Recurrent Neural Networks in Python
Generating Poetic Texts with Recurrent Neural Networks in Python
NeuralNine
49 Stock Portfolio Visualization with Matplotlib in Python
Stock Portfolio Visualization with Matplotlib in Python
NeuralNine
50 Analyzing Coronavirus with Python (COVID-19)
Analyzing Coronavirus with Python (COVID-19)
NeuralNine
51 Making Text Images Readable Again with Python and OpenCV
Making Text Images Readable Again with Python and OpenCV
NeuralNine
52 Neural Networks Simply Explained (Theory)
Neural Networks Simply Explained (Theory)
NeuralNine
53 Motion Filtering with OpenCV in Python
Motion Filtering with OpenCV in Python
NeuralNine
54 Top 5 Programming Languages To Learn in 2020
Top 5 Programming Languages To Learn in 2020
NeuralNine
55 Simple TCP Chat Room in Python
Simple TCP Chat Room in Python
NeuralNine
56 Image Classification with Neural Networks in Python
Image Classification with Neural Networks in Python
NeuralNine
57 Edge Detection with OpenCV in Python
Edge Detection with OpenCV in Python
NeuralNine
58 S&P 500 Web Scraping with Python
S&P 500 Web Scraping with Python
NeuralNine
59 Simple Sentiment Text Analysis in Python
Simple Sentiment Text Analysis in Python
NeuralNine
60 Introduction - Algorithms & Data Structures #1
Introduction - Algorithms & Data Structures #1
NeuralNine

This video teaches how to add an extra layer of security to login systems using 2FA and OTPs in Python, which is essential for protecting user accounts from unauthorized access. By following the steps outlined in the video, viewers can implement 2FA in their own Python projects.

Key Takeaways
  1. Install Pi OTP library using pip
  2. Import time and Pi OTP libraries in Python
  3. Generate a secret key using Pi OTP's random base 32 function
  4. Use Pi OTP's totp function to generate a time-based OTP
  5. Simulate code expiration using time.sleep(30)
  6. Verify input code using totp.verify
  7. Generate counter-based password using hotp
  8. Verify input code using hotp.verify
  9. Install QR code library with pip
  10. Generate URI for QR code scanning
💡 Using a secret key to generate OTPs is crucial for preventing unauthorized access, and the Pi OTP library provides a secure way to implement 2FA in Python.

Related AI Lessons

You Are Not Behind. The World Is.
You're not behind, the world is still adapting to AI, and it's okay to take your time to learn and grow
Medium · AI
Career choice with the advent of AI - pure Computer Science or learn software with a background of core engineering area
Learn how to choose between a Computer Science and Engineering career path or combining programming with a core engineering background in the age of AI
Dev.to AI
The AI Hype Cycle: Calm Before the Next Breakthrough?
Understand the AI hype cycle to anticipate the next breakthrough and make informed decisions
Medium · Programming
AI won’t replace scientists. It will make the current model of science obsolete
AI is not replacing scientists, but rather making the current model of science obsolete, enabling new forms of discovery and collaboration
Medium · Data Science
Up next
Motorist saved by human chain | 9 News Australia
9 News Australia
Watch →