Skip to content

Multi-Factor Authentication — Adding Extra Security Layers to API Access

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about Multi. We cover key concepts, practical examples, and best practices to help you master this topic.

Multi-factor authentication (MFA) requires two or more verification factors — something you know, something you have, or something you are — to access an API.

What You'll Learn

How MFA works, common factors (TOTP, SMS, hardware keys), implementing MFA verification in your API, and when to require MFA.

Why It Matters

Passwords alone are vulnerable to phishing, data breaches, and brute force. MFA adds a second factor. Even if the password is compromised, the attacker cannot authenticate without the second factor.

Real-World Use

GitHub requires MFA for high-privilege operations, Google prompts for MFA on suspicious logins, and Durga Antivirus Pro requires MFA for partner API access that modifies threat intelligence data.

flowchart LR
    A["User"] -->|"Password (Factor 1)"| B["Auth Server"]
    B -->|"Password valid"| C["Request Factor 2"]
    A -->|"TOTP Code (Factor 2)"| C
    C -->|"Both valid"| D["Issue Token"]
    C -->|"Invalid"| E["Access Denied"]
    style A fill:#dbeafe,stroke:#2563eb
    style B fill:#fef3c7,stroke:#d97706
    style D fill:#dcfce7,stroke:#16a34a
    style E fill:#fecaca,stroke:#dc2626

Authentication Factors

Factor Type Examples Security
Knowledge (something you know) Password, PIN Low
Possession (something you have) Phone, hardware key, authenticator app High
Inherence (something you are) Fingerprint, face, voice High
Location (somewhere you are) IP address, GPS Medium

Code Example: TOTP-Based MFA

import pyotp
import qrcode
import io
import base64
from flask import Flask, request, jsonify

app = Flask(__name__)

# Store user secrets (in production, use database with encryption)
user_secrets = {}

@app.route("/api/mfa/setup", methods=["POST"])
def setup_mfa():
    """Generate TOTP secret and return QR code for authenticator app."""
    user_id = request.json.get("user_id")
    secret = pyotp.random_base32()
    user_secrets[user_id] = secret

    totp = pyotp.TOTP(secret)
    provisioning_uri = totp.provisioning_uri(
        name=user_id,
        issuer_name="DodaTech API"
    )

    return jsonify({
        "secret": secret,
        "provisioning_uri": provisioning_uri,
        "message": "Scan QR code with authenticator app"
    })

@app.route("/api/mfa/verify", methods=["POST"])
def verify_mfa():
    """Verify a TOTP code from the authenticator app."""
    user_id = request.json.get("user_id")
    code = request.json.get("code")

    secret = user_secrets.get(user_id)
    if not secret:
        return jsonify({"error": "MFA not configured"}), 400

    totp = pyotp.TOTP(secret)
    if totp.verify(code):
        return jsonify({"verified": True, "message": "MFA code valid"})
    else:
        return jsonify({"verified": False, "message": "Invalid code"}), 401

@app.route("/api/login", methods=["POST"])
def login_with_mfa():
    """Login with password + MFA."""
    data = request.json
    # Verify password (simplified)
    if data.get("password") != "correct-password":
        return jsonify({"error": "Invalid password"}), 401

    # Verify MFA
    secret = user_secrets.get(data.get("user_id"))
    if secret:
        totp = pyotp.TOTP(secret)
        if not totp.verify(data.get("mfa_code")):
            return jsonify({"error": "MFA required or invalid"}), 401

    return jsonify({"token": "successful-auth-token"})

if __name__ == "__main__":
    app.run()

Code Example: Requiring MFA for Sensitive Operations

@app.route("/api/threat-intel", methods=["POST"])
def update_threat_intel():
    """High-security endpoint requiring MFA."""
    token = request.headers.get("Authorization", "").replace("Bearer ", "")

    # Check if token was issued with MFA
    payload = jwt.decode(token, SECRET, algorithms=["HS256"])
    if not payload.get("mfa_verified"):
        return jsonify({
            "error": "MFA required",
            "message": "Re-authenticate with MFA for this operation"
        }), 403

    return jsonify({"message": "Threat intelligence updated"})

Common Mistakes

1. Allowing MFA Bypass

If the user can skip MFA or the API falls back to password-only, MFA provides no benefit.

2. Not Rate-Limiting MFA Attempts

Attackers can brute force TOTP codes (6 digits, 1M combinations). Rate limit to prevent brute force.

3. Using SMS Instead of TOTP

SMS is vulnerable to SIM swapping and SS7 attacks. TOTP (authenticator app) or hardware keys are more secure.

4. MFA Fatigue

Repeated push notifications to approve login cause users to approve without thinking. Require explicit code entry.

5. Not Providing Recovery Codes

Users lose phones. Provide one-time recovery codes during setup and document the recovery Process.

Practice Questions

  1. What three types of authentication factors exist?
  2. Why is TOTP more secure than SMS for MFA?
  3. How does MFA impact the user experience in API authentication?
  4. What is a recovery code and why is it important?
  5. How should an API indicate that MFA is required?

Answers:

  1. Knowledge (password), Possession (phone, hardware key), Inherence (fingerprint, face).
  2. SMS is vulnerable to SIM swapping and SS7 interception. TOTP generates codes on the device without network transmission.
  3. MFA adds friction. Use step-up authentication — require MFA only for sensitive operations, not for every login.
  4. A recovery code is a one-time code generated during MFA setup for when the user loses access to their MFA device.
  5. Return 403 with a specific error code (mfa_required) and include a list of available MFA methods in the response.

Challenge: Implement step-up MFA — allow read operations with password only, but require MFA for write operations. Issue different tokens with and without MFA claim.

FAQ

Is MFA required for all API users?

No. Require MFA for admin accounts, sensitive operations, and external integrations. Standard read-only users may not need it.

Does MFA work with OAuth2?

Yes. The authorization server can prompt for MFA during authentication. The tokens issued include an MFA claim.

What is step-up authentication?

The user authenticates with password first for basic access. When they attempt a sensitive operation, the system prompts for MFA.

Can MFA be used with API keys?

API keys are for machines that cannot interact with MFA prompts. For human users, use JWT or OAuth2 with MFA support.

How do hardware keys (FIDO2/WebAuthn) work with APIs?

The browser handles WebAuthn interaction. The API receives a verified assertion. WebAuthn is phishing-resistant and more secure than TOTP.

Mini Project

Build a login system with step-up MFA. Users log in with password to get a basic token. Sensitive operations (e.g., delete data) require a TOTP verification that upgrades the token with an MFA claim.

What's Next

Now learn about Authentication Headers — the standard HTTP headers used for different authentication schemes.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro