How to implement two-factor authentication in Spring Security

A password alone is a weak boundary for a modern application. Two-factor authentication (2FA) adds a second proof, usually a time-based one-time password (TOTP) generated by an authenticator app. Even if a password is exposed through phishing or credential reuse, an attacker still needs the rotating code.

Spring Security provides the authentication pipeline, but TOTP enrolment and verification usually require a small amount of application code. This approach works well for Java applications using Spring Boot, Spring MVC, JPA, and a server-side session or token-based API.

For Australian users, an authenticator app is often more reliable than SMS in regional areas where mobile coverage can be patchy. It also avoids message delays during busy periods in Sydney or Melbourne and provides a consistent experience for customers using the NBN, mobile broadband, or workplace networks.

Choose the second factor carefully

TOTP is a practical default for most Spring applications. During enrolment, the server creates a secret key and displays it as a QR code. The user scans the code with an app such as Google Authenticator, Microsoft Authenticator, or 1Password. The app then generates a six-digit code that changes every 30 seconds.

SMS codes are easier for some users, but they are vulnerable to SIM-swapping and mobile-network problems. Email codes have similar delivery risks. Hardware security keys using WebAuthn provide stronger phishing resistance, though they require a different implementation and user support process. A sensible rollout can begin with TOTP and add passkeys later.

Store the secret securely, preferably encrypted at rest, and never log it or the submitted code. Add recovery codes during enrolment and hash them in the database. Recovery codes should be single-use, sufficiently random, and protected with the same care as passwords.

Model the authentication state

A user record needs fields such as mfaEnabled, an encrypted TOTP secret, and a collection of hashed recovery codes. The exact design depends on whether one user can register several devices. A separate UserMfaDevice entity is usually more flexible because it supports device names, revocation, creation dates, and multiple authenticators.

After the password is correct, do not immediately create a fully authenticated session when MFA is enabled. Instead, place the user in a temporary authentication state and redirect them to /mfa. Spring Security can represent this with a custom authority such as MFA_REQUIRED, while protected business endpoints require an authority such as MFA_VERIFIED.

A simplified service might look like this:

@Service
public class TotpService {
    public boolean isValid(String secret, String code) {
        return new Totp(secret).verify(code);
    }
}

The Totp implementation can come from a maintained library that supports RFC 6238. Avoid writing cryptographic code from scratch. Also configure a small clock-skew window, such as one time step, because a user’s phone clock may be slightly inaccurate.

Build the enrolment and verification flow

The enrolment endpoint should generate a secret only after the user has passed the normal password authentication. Display the secret as a QR code using an otpauth:// URI, then ask the user to enter the first generated code. Save the secret only after that code is valid.

@PostMapping("/account/mfa/verify")
public String verifySetup(@AuthenticationPrincipal AppUser user,
                          @RequestParam String code) {
    if (!totpService.isValid(user.getPendingSecret(), code)) {
        return "redirect:/account/mfa?error";
    }

    user.enableMfa(encrypt(user.getPendingSecret()));
    userRepository.save(user);
    return "redirect:/account/security";
}

The login verification endpoint should accept the code only for the temporary authentication state. Once it succeeds, replace that state with a fully authenticated session and remove the temporary marker. Rate-limit attempts per account and IP address, add a short lockout after repeated failures, and record security events without storing the submitted TOTP value.

When an Australian customer says the code has “gone bung”, the usual causes are an incorrect phone clock, a copied secret, or a code submitted after the 30-second window. Showing a clear error and allowing one previous or next time step is more useful than simply returning “invalid credentials”.

Configure Spring Security rules

With Spring Security 6, configure the filter chain so that login and MFA endpoints are public, while application resources require the completed MFA authority. The exact arrangement depends on whether the application uses sessions, OAuth2, or stateless JWTs.

@Bean
SecurityFilterChain security(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/login", "/mfa", "/css/**").permitAll()
            .requestMatchers("/app/**").hasAuthority("MFA_VERIFIED")
            .anyRequest().authenticated())
        .formLogin(form -> form.loginPage("/login"))
        .logout(logout -> logout.logoutSuccessUrl("/login"));

    return http.build();
}

In a session-based application, a custom success handler can check whether MFA is enabled and grant the appropriate authority. For a REST API, issue a short-lived token with an mfa_pending claim after password verification, then exchange it for a normal access token after TOTP validation. Never accept a pending token for ordinary API operations.

If you are maintaining an older codebase, check compatibility before changing security configuration. A concise reference to Java 7 guidance can help when legacy syntax or runtime constraints affect the implementation.

Test, deploy, and operate the feature

Test the complete lifecycle: enrolment, valid and invalid codes, clock drift, recovery codes, disabling MFA, password resets, session expiry, and concurrent logins. Use integration tests with a fixed TOTP secret and a controllable clock. Verify that an unauthorised request cannot bypass the MFA page by calling an application URL directly.

Protect QR-code endpoints with CSRF controls and ensure secrets are excluded from logs, tracing headers, exception messages, backups, and analytics. Add audit events for enrolment, successful verification, failed attempts, recovery-code use, and MFA removal. These records support incident response and help meet security expectations under the Australian Privacy Act and Notifiable Data Breaches scheme.

Use environment-specific secret management in production rather than plain configuration files. A managed platform such as QcloudPress hosting may be useful when deploying a Java-backed site, but the application should still keep TOTP secrets in an encrypted store and restrict operational access. Run the service in regions suitable for Australian latency, monitor authentication failures, and provide support documentation in straightforward local language rather than dense security jargon.