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
  • Beautiful Soup
  • Selenium
  • Scrapy
  • urllib
  • Request
  • open cv
  • Data analysis
  • Machine learning
  • NLP
  • Deep learning
  • Data Science
  • Interview question
  • ML math
  • ML Projects
  • ML interview
  • DL interview
Open In App
Next Article:
Authentication using Python requests
Next article icon

Access a Site with Two-Factor Authentication Using Python Requests

Last Updated : 29 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 to your phone or email. However, this added security can pose a challenge for automation tasks, such as web scraping or automated logging in. In this article, we will explore how to access a site with two-factor authentication using Python's requests library.

Introduction to Two-Factor Authentication (2FA)

Two-factor authentication is a security process in which users provide two different authentication factors to verify themselves. These factors can include something they know (password), something they have (a mobile phone or security token), or something they are (biometric verification).

When it comes to automating the login process, handling 2FA requires some additional steps compared to a standard login. Typically, these steps include:

  1. Submitting the login credentials (username and password).
  2. Receiving a 2FA code via SMS, email, or an authenticator app.
  3. Submitting the 2FA code to complete the login process.

Step-by-Step Guide to Accessing a 2FA Site

Step 1: Initial Login Request

First, we need to simulate the login form submission using the requests library. This step involves sending a POST request with the username and password to the login endpoint.

Step 2: Handling the 2FA Challenge

It involves a two-factor authentication (2FA) trial. That is when the server responds by saying that a 2FA code is necessary if the first attempt to log in is convincing, but the site demands confirmation of identity through another means, such as two-factor authentication (2FA). The codes sent via SMS or email usually serve as this verification technique.

Step 3: Submitting the 2FA Code

Submitting a two-factor authentication code is the last step in logging onto an online account. It must be included in the server in order for a human to finish authenticating their identity.

Example Code

Python
import requests  # Start a session session = requests.Session()  # URL for the initial login (using reqres.in mock service) login_url = "https://reqres.in/api/login"  # Payload for the initial login request login_payload = {     "email": "[email protected]",     "password": "cityslicka" }  # Initial login request login_response = session.post(login_url, data=login_payload) print("Initial login response:") print(login_response) print(login_response.json())  # Check the response text to see if 2FA is required  # Simulate a 2FA requirement check two_fa_required = True  if two_fa_required:     # Prompt for the 2FA code     two_fa_code = input("Enter the 2FA code: ")      # Mock URL for the 2FA verification (simulated endpoint)     two_fa_url = "https://reqres.in/api/2fa"      # Payload for the 2FA request     two_fa_payload = {         "2fa_code": two_fa_code     }      # Simulate the 2FA verification response     two_fa_response = {         "status": "success",         "message": "Login successful"     }      # Check if 2FA verification was successful     if two_fa_response["status"] == "success":         print("Login successful!")     else:         print("2FA verification failed.") else:     print("Login failed or 2FA not required.") 

Handling Common Issues

Issue 1: Incorrect Credentials

Wrong Credentials when the first attempt at logging in fails, it means that the email and password provided were not correct.

Issue 2: Incorrect 2FA Code

Wrong 2FA (two-factor authentication) Code if the 2FA code is wrong, then the server would give an error message saying login unsuccessful.

Issue 3: Session Management

Handling Sessions is very important to properly manage sessions in order to keep users logged in through different requests. Persist cookies and session data with requests.Session() method.

Output:

Screenshot-2024-07-07-160512
output

The above example demonstrates handling two-factor authentication (2FA) using Python requests. Please note that the 2FA verification ('two_fa_response') is simulated for demonstration purposes and does not interact with an actual 2FA service.

The code used Reqres.in (login_url, two_fa_url and login_payload) to demonstrate authentication because Reqres.in provides a mock service for developers to simulate login and authentication scenarios in a controlled environment.

Conclusion

Accessing sites with 2FA using Python's 'requests' library involves managing multiple steps and handling additional challenges like captchas and session management. By carefully simulating the 2FA process, it's possible to automate these logins, but always ensure compliance with the website's terms of service.


Next Article
Authentication using Python requests

V

vishnuvardhan1510
Improve
Article Tags :
  • Python
  • Python-requests
  • Web-scraping
Practice Tags :
  • python

Similar Reads

  • 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
  • How to make a request using HTTP basic authentication with PHP curl?
    Making secure API requests is a common requirement in web development, and PHP provides a powerful tool for this purpose, which is cURL. The challenge is to seamlessly integrate HTTP basic authentication with PHP cURL for secure API communication. This involves not only transmitting sensitive user c
    3 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
  • Multi Factor authentication using MERN
    This article will guide you through creating a Multi-Factor Authentication (MFA) project using the MERN. This project aims to enhance security by implementing a multi-step authentication process. Users will be required to provide multiple forms of identification for access, adding an extra layer of
    5 min read
  • Create API Tester using Python Requests Module
    Prerequisites: Python Requests module, API In this article, we will discuss the work process of the Python Requests module by creating an API tester. API stands for Application Programming Interface (main participant of all the interactivity). It is like a messenger that takes our requests to a syst
    3 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
  • 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
  • How to Handle Authentication with Postman API Testing?
    Authentication is very important for securing access to resources and data. When testing APIs, handling authentication correctly is important to ensure that your tests can interact with secured endpoints effectively. Postman, a popular API testing tool, provides robust features for handling various
    4 min read
  • Setup two-factor authentication (2FA/MFA) for Linux systems
    Two-factor authentication, or multi-factor authentication, is a technique or method of security that requires users to provide two different authentication factors before granting access to an account or system. These factors typically include something the user knows (like a password or PIN) and so
    4 min read
  • Server Side Google Authentication using FastAPI and ReactJS
    FastAPI is a modern, fast, web framework for building APIs with Python, and react is a javascript library that can be used to develop single-page applications. So in this article, we are going to discuss the server-side authentication using FastAPI and Reactjs and we will also set the session. First
    4 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