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
1if code is valid. - If wrong code, status will be
0and 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
statusfield 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.