How to Test Two-Factor Authentication on Web (Complete Guide)
Two-factor authentication (2FA) is a critical security layer, safeguarding user accounts against unauthorized access. Inadequate testing of 2FA mechanisms can lead to significant user frustration, dat
Robust Two-Factor Authentication Testing for Web Applications
Two-factor authentication (2FA) is a critical security layer, safeguarding user accounts against unauthorized access. Inadequate testing of 2FA mechanisms can lead to significant user frustration, data breaches, and reputational damage. Common failures range from bypassed codes to lockout scenarios and accessibility barriers, directly impacting user trust and application security.
Comprehensive 2FA Test Cases
A thorough 2FA testing strategy must cover multiple facets of the user journey and potential failure points.
Happy Path Scenarios:
- Successful Login with Valid Second Factor:
- Enter valid username and password.
- Receive a valid 2FA code (e.g., via SMS, email, authenticator app).
- Enter the valid 2FA code.
- Verify successful login and access to the authenticated section of the application.
- Successful Login with Authenticator App Code:
- Enter valid username and password.
- Open authenticator app and retrieve the current time-based one-time password (TOTP).
- Enter the TOTP.
- Verify successful login.
Error Scenarios:
- Invalid Second Factor Code:
- Enter valid username and password.
- Receive a valid 2FA code.
- Enter an incorrect 2FA code.
- Verify an appropriate error message (e.g., "Invalid code") and that login is denied.
- Expired Second Factor Code:
- Enter valid username and password.
- Receive a valid 2FA code.
- Wait for the code to expire (check the code's validity duration).
- Attempt to enter the expired code.
- Verify an appropriate error message (e.g., "Code has expired") and that login is denied.
- Rate Limiting on Code Attempts:
- Enter valid username and password.
- Attempt to log in with multiple invalid 2FA codes consecutively (e.g., 5-10 times).
- Verify that the account is temporarily locked or that further attempts are rate-limited, preventing brute-force attacks.
- Resend Code Functionality:
- Initiate a login with valid credentials.
- Click the "Resend Code" option before entering the initial code.
- Verify that a new code is sent and that the previous code is invalidated.
- Enter the new, valid code and verify successful login.
- Account Lockout After Multiple Failures:
- Initiate a login with valid credentials.
- Attempt to enter invalid 2FA codes a predefined number of times (e.g., 3-5).
- Verify that the account is locked and that the user receives a notification about the lockout, along with instructions for unlocking.
Edge Cases:
- Simultaneous Login Attempts with Different Devices:
- Log in successfully on Device A with 2FA.
- Immediately attempt to log in on Device B with the same credentials and a valid 2FA code.
- Verify how the system handles concurrent sessions – does it invalidate the first, allow both, or prompt for re-authentication on the first?
- Using a Code from a Different Session:
- Initiate a login, receive a 2FA code.
- Navigate away from the login page or close the tab.
- Re-open the login page, enter valid credentials.
- Attempt to use the *previously received* code.
- Verify it's rejected if codes are session-specific.
Accessibility Considerations for Two-Factor Authentication:
- Screen Reader Compatibility:
- Navigate the 2FA process using a screen reader (e.g., NVDA, JAWS).
- Verify that all form fields, buttons, and error messages are clearly announced.
- Ensure instructions for receiving and entering codes are understandable.
- Keyboard Navigation:
- Complete the entire 2FA flow using only the keyboard (Tab, Shift+Tab, Enter, Spacebar).
- Verify that all interactive elements are focusable and operable.
- Color Contrast:
- Check that error messages and instructions have sufficient color contrast against their background to be legible for users with low vision.
- Time Limits for Code Entry:
- For users who may take longer to input codes (e.g., due to motor impairments or cognitive differences), assess if the time limit is too restrictive. Evaluate options for extending time limits or providing alternative methods.
Manual Testing Approach
Manual testing of 2FA is essential for understanding user experience and uncovering nuanced issues.
- Setup: Ensure you have access to a test account with 2FA enabled and the necessary secondary authentication method (e.g., a phone for SMS, an authenticator app configured).
- Initial Login: Navigate to your web application's login page. Enter valid credentials for a user account.
- Second Factor Prompt: Observe the application's response. It should prompt for the second factor.
- Obtain and Enter Code:
- SMS: Check your test phone for the SMS code.
- Email: Check the associated test email inbox.
- Authenticator App: Open your authenticator app and retrieve the current TOTP.
- Input Code: Enter the obtained code into the designated field on the web application.
- Submit and Verify: Click the submit button. Confirm successful redirection to the authenticated area of the application.
- Error Condition Testing: Repeat steps 2-5 but intentionally introduce errors: use incorrect codes, expired codes, or exceed the allowed number of attempts. Document all error messages and system behaviors.
- Resend/Alternative Method Testing: If available, test the "Resend Code" functionality and any alternative methods (e.g., backup codes).
- Accessibility Testing: Utilize screen readers and keyboard-only navigation to assess usability for users with disabilities.
- Session Management: Test logging in from multiple browsers or incognito windows concurrently.
Automated Testing Approach for Web 2FA
Automated testing for 2FA requires careful consideration due to the dynamic nature of codes.
- Frameworks: Playwright and Selenium WebDriver are standard choices for web automation.
- Code Generation: Frameworks like Playwright can auto-generate initial test scripts.
- Handling Dynamic Codes: This is the primary challenge.
- SMS/Email Codes: This is difficult to automate directly without specialized tools or services that can intercept SMS or email. Services like Twilio can be integrated to send SMS to a test number and then retrieve the message content programmatically.
- Authenticator App Codes (TOTP): Libraries exist in various languages to generate TOTP codes based on a shared secret. For example, in Python, the
pyotplibrary can be used.
import pyotp
import time
# Replace with your shared secret key for the test account
# This secret is typically generated when setting up 2FA for the first time
# and should be securely stored for automated testing.
SECRET_KEY = "YOUR_SUPER_SECRET_KEY_HERE"
totp = pyotp.TOTP(SECRET_KEY)
# Get the current valid code
current_code = totp.now()
print(f"Current TOTP code: {current_code}")
# In your test script, you would then use Playwright/Selenium
# to enter this 'current_code' into the web application's input field.
# page.locator('input[name="twoFactorCode"]').fill(current_code)
- CI/CD Integration: Integrate these automated tests into your CI/CD pipeline (e.g., GitHub Actions). Use JUnit XML reporters for clear test results.
How SUSA Tests Two-Factor Authentication Autonomously
SUSA (SUSATest) approaches 2FA testing autonomously by simulating diverse user behaviors and leveraging its integrated capabilities.
- Autonomous Exploration: Upon uploading an APK or providing a web URL (e.g.,
susatest.com/login), SUSA begins exploring the application without requiring pre-written scripts. It identifies login flows and subsequently the 2FA steps. - Persona-Based Testing: SUSA employs 10 distinct user personas, each influencing how the application is tested.
- Curious, Novice, Student, Teenager: These personas explore standard login flows, revealing issues with clear instructions and straightforward code entry. They might trigger error messages by mistyping codes, testing the robustness of the error handling.
- Impatient: This persona is likely to attempt rapid code entry or resends, stressing rate-limiting mechanisms and the validity of resend codes.
- Adversarial: This persona actively tries to break the system, attempting invalid codes, expired codes, and potentially exploring ways to bypass the 2FA step altogether if vulnerabilities exist. They are key in finding security loopholes.
- Elderly, Accessibility: These personas are critical for testing the accessibility of the 2FA interface. SUSA performs WCAG 2.1 AA accessibility testing, identifying issues like poor color contrast in error messages, non-descriptive labels for code input fields, or keyboard navigation barriers.
- Power User: This persona might attempt to use codes from previous sessions or explore advanced features related to 2FA management, potentially uncovering edge cases in session handling.
- Finding Specific Issues: SUSA's autonomous exploration is designed to detect:
- Crashes and ANRs: If the 2FA process triggers an application crash or Application Not Responding error.
- Dead Buttons: If the "Submit" button for the 2FA code becomes unresponsive.
- Accessibility Violations: As mentioned, through its dedicated accessibility testing.
- Security Issues: By simulating attacks like brute-force attempts on code entry or exploring API calls related to 2FA. SUSA checks against OWASP Top 10 principles and API security.
- UX Friction: Identifying confusing prompts, overly short time limits, or difficult-to-obtain codes.
- Auto-Generated Regression Scripts: After its autonomous exploration, SUSA auto-generates Appium scripts for Android and Playwright scripts for Web. These scripts can be integrated into CI/CD pipelines. For 2FA, this means the "happy path" login scenario, including successful code entry, will be captured and can be re-run automatically to ensure no regressions are introduced
Test Your App Autonomously
Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.
Try SUSA Free