Skip to content
Rishan Solutions
Rishan Solutions
  • PowerApps
  • SharePoint online
    • Uncategorized
    • Uncategorized
  • PowerAutomate
Rishan Solutions
Latest Posts
  • Agentic AI: The Dawn of Autonomous Intelligence Revolutionizing 2025 June 24, 2025
  • Recursive Queries in T-SQL May 7, 2025
  • Generating Test Data with CROSS JOIN May 7, 2025
  • Working with Hierarchical Data May 7, 2025
  • Using TRY_CAST vs CAST May 7, 2025
  • Dynamic SQL Execution with sp_executesql May 7, 2025

Implementing Two-Factor Authentication (2FA) with jQuery

Posted on April 2, 2025April 2, 2025 by Zubair Shaik

Loading

Implementing Two-Factor Authentication (2FA) with jQuery

Table of Contents

  1. Introduction to Two-Factor Authentication (2FA)
  2. Why Implement 2FA?
  3. How 2FA Works
  4. Types of Two-Factor Authentication
  5. Choosing the Right 2FA Method
  6. Project Setup
  7. Frontend Implementation Using jQuery
    • Creating a Login Form
    • Sending an OTP via AJAX
    • Verifying the OTP
  8. Backend Implementation
    • Generating and Sending OTP
    • Storing OTP Securely
    • Validating OTP on the Server
  9. Enhancing Security with Google Authenticator
  10. Using Third-Party APIs for 2FA
  11. Storing User Sessions Securely
  12. Best Practices for Implementing 2FA
  13. Common Mistakes to Avoid
  14. Final Thoughts and Conclusion

1. Introduction to Two-Factor Authentication (2FA)

Two-Factor Authentication (2FA) adds an extra layer of security by requiring users to verify their identity using two methods:

  1. Something they know (Password).
  2. Something they have (One-Time Password, Hardware Token, SMS Code, etc.).

This prevents unauthorized access even if an attacker steals a user’s password.


2. Why Implement 2FA?

  • Enhanced Security – Prevents unauthorized access to accounts.
  • Mitigates Phishing Attacks – Protects users from stolen credentials.
  • Compliance with Security Regulations – Meets GDPR, PCI-DSS, and other standards.
  • Builds User Trust – Users feel secure when their data is protected.

3. How 2FA Works

  1. The user logs in with their username and password.
  2. The server generates a one-time password (OTP) and sends it via email or SMS.
  3. The user enters the OTP in the web application.
  4. If the OTP is correct, the user gains access.

4. Types of Two-Factor Authentication

  1. SMS-Based OTP – A code is sent via SMS.
  2. Email-Based OTP – A code is sent to the user’s email.
  3. Authenticator App (TOTP) – Google Authenticator or Authy generates time-based codes.
  4. Hardware Token – A physical device generates codes.
  5. Biometric Authentication – Fingerprint or facial recognition.

For this tutorial, we will implement email-based OTP authentication using jQuery and PHP.


5. Choosing the Right 2FA Method

MethodProsCons
SMS OTPEasy to implementVulnerable to SIM swapping
Email OTPSecure and widely usedDelayed email delivery
Google AuthenticatorMore secureRequires an app
Hardware TokenExtremely secureCostly implementation

6. Project Setup

Requirements

  • HTML, CSS, jQuery for frontend.
  • PHP and MySQL for backend.
  • An SMTP email server for sending OTPs.

7. Frontend Implementation Using jQuery

A. Creating a Login Form

<!DOCTYPE html>
<html lang="en">
<head>
    <title>2FA Login</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h2>Login</h2>
    <input type="text" id="email" placeholder="Enter Email">
    <input type="password" id="password" placeholder="Enter Password">
    <button id="sendOtp">Login</button>

    <div id="otpSection" style="display:none;">
        <h3>Enter OTP</h3>
        <input type="text" id="otp" placeholder="Enter OTP">
        <button id="verifyOtp">Verify OTP</button>
    </div>

    <p id="response"></p>

    <script>
        $(document).ready(function() {
            $("#sendOtp").click(function() {
                var email = $("#email").val();
                var password = $("#password").val();

                $.ajax({
                    url: "send_otp.php",
                    type: "POST",
                    data: { email: email, password: password },
                    success: function(response) {
                        $("#response").text(response);
                        if (response.includes("OTP sent")) {
                            $("#otpSection").show();
                        }
                    }
                });
            });

            $("#verifyOtp").click(function() {
                var otp = $("#otp").val();

                $.ajax({
                    url: "verify_otp.php",
                    type: "POST",
                    data: { otp: otp },
                    success: function(response) {
                        $("#response").text(response);
                    }
                });
            });
        });
    </script>
</body>
</html>

8. Backend Implementation

A. Generating and Sending OTP (send_otp.php)

<?php
session_start();
require 'PHPMailer/PHPMailerAutoload.php';

function generateOtp() {
    return rand(100000, 999999);
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $email = $_POST['email'];
    $password = $_POST['password'];

    // Validate user credentials (dummy check)
    if ($email == "user@example.com" && $password == "password123") {
        $otp = generateOtp();
        $_SESSION['otp'] = $otp;
        $_SESSION['email'] = $email;

        // Send OTP via Email
        $mail = new PHPMailer;
        $mail->isSMTP();
        $mail->Host = 'smtp.example.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'your_email@example.com';
        $mail->Password = 'your_password';
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;
        $mail->setFrom('no-reply@example.com', '2FA System');
        $mail->addAddress($email);
        $mail->Subject = 'Your OTP Code';
        $mail->Body = 'Your OTP code is ' . $otp;

        if ($mail->send()) {
            echo "OTP sent to your email.";
        } else {
            echo "Failed to send OTP.";
        }
    } else {
        echo "Invalid email or password.";
    }
}
?>

B. Verifying OTP (verify_otp.php)

<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $userOtp = $_POST['otp'];

    if (isset($_SESSION['otp']) && $_SESSION['otp'] == $userOtp) {
        echo "Login successful!";
        unset($_SESSION['otp']);
    } else {
        echo "Invalid OTP!";
    }
}
?>

9. Enhancing Security with Google Authenticator

  • Use Google Authenticator API for time-based OTP (TOTP).
  • Store secret keys securely in the database.
  • Ensure QR code generation for easy setup.

10. Using Third-Party APIs for 2FA

  • Twilio API for SMS OTPs.
  • Google Authenticator API for TOTP-based authentication.
  • Authy API for multi-factor authentication.

11. Storing User Sessions Securely

  • Use HTTP-only cookies for storing authentication tokens.
  • Encrypt OTPs before storing in databases.
  • Set OTP expiry times (e.g., 5 minutes).

12. Best Practices for Implementing 2FA

✅ Use HTTPS for secure data transmission.
✅ Implement rate limiting to prevent brute-force OTP attempts.
✅ Store OTPs securely with hashing.
✅ Enforce short expiry times for OTPs (e.g., 5 minutes).
✅ Log failed login attempts for security monitoring.


13. Common Mistakes to Avoid

❌ Sending OTPs over unsecured connections.
❌ Storing OTPs in plaintext in databases.
❌ Allowing unlimited OTP retry attempts.
❌ Using weak passwords without enforcing strong policies.


Two-Factor Authentication significantly improves account security. This guide covered a step-by-step 2FA implementation using jQuery, PHP, and email-based OTPs.

Would you like a Google Authenticator (TOTP) example next?

Posted Under jQuery2FA AJAX OTP Authentication Best Practices authentication tokens Authenticator App Authy Cybersecurity data privacy Data Protection Email OTP Email Verification Encryption in Authentication Google 2FA Google Authenticator Hardware Token Authentication JavaScript authentication JavaScript security jQuery 2FA jQuery AJAX security jQuery security Login Protection Login with OTP MFA Multi-Factor Authentication OTP Authentication OTP via Email OTP via SMS OWASP Authentication PHP 2FA PHP Security Prevent Brute Force Attacks Prevent Credential Theft Prevent Hacking Prevent Phishing Prevent Unauthorized Access Secure API Calls Secure Authentication Secure Login Secure Login Mechanism Secure Login System Secure User Verification secure web applications Secure Web Login Session Security sms authentication SMS OTP Strong Authentication strong passwords Time-Based OTP Two-Factor Authentication user authentication web application security web development security Web Security

Post navigation

Encrypting user input before sending via AJAX
Using useEffect without handling async cleanup properly

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Agentic AI: The Dawn of Autonomous Intelligence Revolutionizing 2025
  • Recursive Queries in T-SQL
  • Generating Test Data with CROSS JOIN
  • Working with Hierarchical Data
  • Using TRY_CAST vs CAST

Recent Comments

  1. Michael Francis on Search , Filter and Lookup in power apps
  2. A WordPress Commenter on Hello world!

Archives

  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • March 2024
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • June 2023
  • May 2023
  • April 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • January 2022

Categories

  • Active Directory
  • AI
  • AngularJS
  • Blockchain
  • Button
  • Buttons
  • Choice Column
  • Cloud
  • Cloud Computing
  • Data Science
  • Distribution List
  • DotNet
  • Dynamics365
  • Excel Desktop
  • Extended Reality (XR) – AR, VR, MR
  • Gallery
  • Icons
  • IoT
  • Java
  • Java Script
  • jQuery
  • Microsoft Teams
  • ML
  • MS Excel
  • MS Office 365
  • MS Word
  • Office 365
  • Outlook
  • PDF File
  • PNP PowerShell
  • Power BI
  • Power Pages
  • Power Platform
  • Power Virtual Agent
  • PowerApps
  • PowerAutomate
  • PowerPoint Desktop
  • PVA
  • Python
  • Quantum Computing
  • Radio button
  • ReactJS
  • Security Groups
  • SharePoint Document library
  • SharePoint online
  • SharePoint onpremise
  • SQL
  • SQL Server
  • Template
  • Uncategorized
  • Variable
  • Visio
  • Visual Studio code
  • Windows
© Rishan Solutions 2025 | Designed by PixaHive.com.
  • Rishan Solutions