How to Validate TOTP Codes with n8n Using Python Code Node

Learn how to validate 6-digit TOTP codes using a Python Code node in n8n without creating credentials. This workflow solves the need to verify 2FA codes efficiently and securely in an automated process.
manualTrigger
code
if
+2
Workflow Identifier: 2478
NODES in Use: Manual Trigger, Set, Code, IF, Sticky Note

Press CTRL+F5 if the workflow didn't load.

Learn how to Build this Workflow with AI:

Visit through Desktop for Best experience

Opening Problem Statement

Meet Sarah, a developer responsible for maintaining user authentication security within her company’s application. She frequently encounters a challenge: validating Time-based One-Time Passwords (TOTP) that users provide during two-factor authentication (2FA). This involves verifying if the 6-digit codes users submit actually match their unique secret keys. Without automation, she must manually check each code or rely on clunky third-party tools that either demand credential setup or expose security risks.

Every minute Sarah spends validating these codes manually is time lost that could be invested in improving core features. Errors in validation can cause login failures or security breaches. Imagine managing hundreds of users daily — even a 1% mistake rate means dozens of frustrated customers or security vulnerabilities.

Sarah needs a reliable, secure, and streamlined method to verify TOTP codes automatically without the overhead of creating complex credentials or external dependencies.

What This Automation Does

This n8n workflow empowers Sarah to validate any 6-digit TOTP code based on a provided base32 secret key using a Python script inside a Code node—no credential creation required. Here’s what happens when it runs:

  • Manual trigger initiates the workflow: You start the validation process at will, perfect for testing and integration.
  • Example TOTP secret and code are set: The workflow inputs example values to simulate real user input.
  • Python Code node generates and validates: It runs a Python script that decodes the base32 secret, calculates the current valid TOTP code, and compares it with the user-submitted one.
  • Conditional check: The workflow uses an IF node to determine if the TOTP code is valid.
  • Decision branch output: Depending on validation, the workflow branches to handle valid or invalid codes (extendable for further processing).

This solution saves Sarah several hours weekly by removing manual TOTP verification steps while enhancing security by adhering to the TOTP algorithm standards directly within n8n.

Prerequisites ⚙️

  • n8n Automation Platform: An active n8n instance where you can import and run workflows.
  • Python environment in n8n: The Python Code node requires n8n’s setup that supports executing Python code.
  • Basic knowledge of TOTP concepts: Understanding 6-digit authentication codes and secret keys helps but not mandatory.

Step-by-Step Guide to Set Up TOTP Validation Workflow

Step 1: Launch n8n and Create a New Workflow

Open your n8n dashboard. Click New to create a fresh workflow canvas where we’ll build the validation process.

You should see a blank canvas ready to add nodes.

Common mistake: Forgetting to save the workflow early might lose progress.

Step 2: Add the Manual Trigger Node

Click the + button → Search for Manual Trigger → Select it.

This node lets you start the workflow by clicking the Execute Workflow button manually during tests.

Position it on the left side—you should see a node labeled “When clicking ‘Test workflow’”.

Step 3: Add the Set Node for Example Fields

Click + → Search and add the Set node.

Configure it with two fields:
code_to_verify_example set to 516620
totp_secret_example set to CNSUKUMZLQJEZJ3
These simulate the code and secret you want to verify.

Connect the Manual Trigger node output to this Set node.

Common mistake: Not properly naming or setting these fields can cause errors downstream.

Step 4: Insert the Python Code Node for TOTP Validation

Add a Code node → Set language to Python.

Paste the TOTP validation script that:

  • Decodes the base32 secret key
  • Calculates the current valid TOTP code
  • Compares it with the user-provided code
  • Outputs {"status": 1} if valid, else {"status": 0}

Ensure input parameters are set to accept totp_secret_example and code_to_verify_example.

Connect the Set node output to this Code node.

Common mistake: Forgetting to update the variable names in the script to match your node’s input will cause failures.

Python Code Explained

import hmac
import hashlib
import time
import base64

def base32_decode(key):
    key += '=' * (-len(key) % 8)  # Padding for base32
    return base64.b32decode(key.upper(), casefold=True)

def generate_totp(secret, interval=30, digits=6):
    interval_count = int(time.time() // interval)
    interval_bytes = interval_count.to_bytes(8, 'big')
    hmac_hash = hmac.new(secret, interval_bytes, hashlib.sha1).digest()
    offset = hmac_hash[-1] & 0x0F
    binary_code = ((hmac_hash[offset] & 0x7F) << 24 |
                   (hmac_hash[offset + 1] & 0xFF) << 16 |
                   (hmac_hash[offset + 2] & 0xFF) << 8 |
                   (hmac_hash[offset + 3] & 0xFF))
    otp_code = binary_code % (10 ** digits)
    return str(otp_code).zfill(digits)

def verify_totp(secret, code, interval=30, digits=6):
    secret_bytes = base32_decode(secret)
    generated_code = generate_totp(secret_bytes, interval, digits)
    return generated_code == code

secret = _input.item.json.totp_secret_example
code = _input.item.json.code_to_verify_example

if verify_totp(secret, code):
    return [{"status": 1}]
else:
    return [{"status": 0}]

Step 5: Add an IF Node to Check Validation Status

Add an IF node.

Set the condition to check if $json.status equals 1.

Connect the Code node output to the IF node input.

This node determines the success or failure step based on the validation result.

Step 6: Connect Outputs for True and False Branches

From the IF node, you can create two branches:

  • True branch: Continue workflow for valid TOTP, e.g., log success, allow authentication.
  • False branch: Handle invalid codes, e.g., notify user or block access.

This separation allows custom downstream operations depending on validation.

Step 7: Test the Workflow

Click Execute Workflow in n8n.

Watch the flow pass through nodes:

  • You should see status 1 if code is valid.
  • If wrong code, status will be 0 and follow the false branch.

Common mistake: Using expired or incorrect code values will give false failures.

Customizations ✏️

  • Use dynamic TOTP inputs: Replace the Set node fields with input data from a database or form submissions so real-time validation occurs.
  • Extend IF branching: Add more conditions in the IF node to handle multiple TOTP statuses or logging error reasons.
  • Integrate notification system: Connect the true/false branches with Email or Slack nodes to alert users or admins immediately after validation.

Troubleshooting 🔧

Problem: "Code always invalid despite correct input"

Cause: Time synchronization issues or incorrect secret format.

Solution: Check your server’s clock; it must be accurate. Verify the secret is properly base32 encoded. Use NTP service for time sync.

Problem: "Python code node throws syntax or module errors"

Cause: Environment lacks Python dependencies or wrong Python version.

Solution: Ensure n8n supports Python code execution and correct dependencies like hmac, hashlib, base64, and time are available. Update n8n if needed.

Pre-Production Checklist ✅

  • Verify the example secret and code match a valid current TOTP generation.
  • Ensure the Manual Trigger node works as expected in the test run.
  • Confirm the Code node returns a JSON with status field properly set.
  • Test IF node branching accurately reflects validation result.
  • Check error handling paths for invalid or malformed inputs.

Deployment Guide

Activate the workflow by toggling it live in n8n once testing is complete.

Use the Manual Trigger for occasional manual runs or integrate upstream triggers like Webhook nodes in your actual environment.

Monitor execution logs for any anomalies, especially time sync or code mismatches.

FAQs

  • Q: Can I use this workflow with user secrets stored in a database?
    Yes! Replace the Set node with a database query node to fetch dynamic secrets and codes.
  • Q: Does this consume API credits?
    No external API calls are made; all computation runs locally in the Python Code node.
  • Q: Is the validation secure?
    Yes, as it follows the standard TOTP algorithm using HMAC-SHA1 entirely within your environment without exposing secrets externally.
  • Q: Can this handle multiple simultaneous requests?
    Yes, but ensure your n8n instance resources and concurrency settings meet your scale needs.

Conclusion

Today, you built an essential security component to verify TOTP codes directly inside n8n using a Python Code node. This automation saves time previously spent on manual verification and increases security by adhering strictly to the TOTP RFC standards.

By integrating this workflow into your app, you bring seamless 2FA validation without relying on external credential stores or services.

Next, consider expanding this workflow by adding user database integrations, notification alerts for failed attempts, or automating user lockouts after repeated invalid tries.

Keep exploring n8n's versatile nodes and custom code capabilities—you’re on your way to mastering secure, efficient automation.

Promoted by BULDRR AI

Related Workflows

Automate Viral UGC Video Creation Using n8n + Degaus (Beginner-Friendly Guide)

Learn how to automate viral UGC video creation using n8n, AI prompts, and Degaus. This beginner-friendly guide shows how to import, configure, and run the workflow without technical complexity.
Form Trigger
Google Sheets
Gmail
+37
Free

AI SEO Blog Writer Automation in n8n (Beginner Guide)

A complete beginner guide to building an AI-powered SEO blog writer automation using n8n.
AI Agent
Google Sheets
httpRequest
+5
Free

Automate CrowdStrike Alerts with VirusTotal, Jira & Slack

This workflow automates processing of CrowdStrike detections by enriching threat data via VirusTotal, creating Jira tickets for incident tracking, and notifying teams on Slack for quick response. Save hours daily by transforming complex threat data into actionable alerts effortlessly.
scheduleTrigger
httpRequest
jira
+5
Free

Automate Telegram Invoices to Notion with AI Summaries & Reports

Save hours on financial tracking by automating invoice extraction from Telegram photos to Notion using Google Gemini AI. This workflow extracts data, records transactions, and generates detailed spending reports with charts sent on schedule via Telegram.
lmChatGoogleGemini
telegramTrigger
notion
+9
Free

Automate Email Replies with n8n and AI-Powered Summarization

Save hours managing your inbox with this n8n workflow that uses IMAP email triggers, AI summarization, and vector search to draft concise replies requiring minimal review. Automate business email processing efficiently with AI guidance and Gmail integration.
emailReadImap
vectorStoreQdrant
emailSend
+12
Free

Automate Email Campaigns Using n8n with Gmail & Google Sheets

This n8n workflow automates personalized email outreach campaigns by integrating Gmail and Google Sheets, saving hours of manual follow-up work and reducing errors in email sequences. It ensures timely follow-ups based on previous email interactions, optimizing communication efficiency.
googleSheets
gmail
code
+5
Free