> For the complete documentation index, see [llms.txt](https://www.pranaypourkar.co.in/the-programmers-guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.pranaypourkar.co.in/the-programmers-guide/spring/spring-features/spring-security/authentication/authentication-mechanism/multi-factor-authentication-mfa.md).

# Multi-Factor Authentication (MFA)

## About

Multi-Factor Authentication (MFA) is an authentication mechanism that requires users to provide **two or more verification factors** to gain access to an application or system. It enhances security by reducing the risk of unauthorized access even if one factor (like a password) is compromised.

MFA is **widely used in modern security systems**, including banking, enterprise applications, and cloud services.

## **How MFA Works (Step-by-Step Flow)**

1. **User Enters Credentials**
   * The user provides a **username and password** (something they know).
2. **First-Factor Authentication**
   * The system verifies the **password** and checks if MFA is enabled for the user.
3. **Second-Factor Authentication Prompt**
   * If MFA is enabled, the system requests a **second authentication factor** (e.g., OTP, biometric scan).
4. **User Provides Second Factor**
   * The user enters an **OTP (One-Time Password)** sent via SMS, email, or authenticator app.
   * Alternatively, the user may perform **biometric authentication** (fingerprint, facial recognition).
5. **Authentication Verification**
   * The system verifies the **second factor**.
   * If valid, access is granted; otherwise, the authentication fails.

## **Types of Authentication Factors in MFA**

MFA requires at least two different types of authentication factors:

<table data-header-hidden data-full-width="true"><thead><tr><th width="214"></th><th width="313"></th><th></th></tr></thead><tbody><tr><td><strong>Factor Type</strong></td><td><strong>Description</strong></td><td><strong>Examples</strong></td></tr><tr><td><strong>Something You Know</strong></td><td>A secret only the user knows.</td><td>Passwords, PINs, Security Questions</td></tr><tr><td><strong>Something You Have</strong></td><td>A physical object the user possesses.</td><td>Mobile phone, Smart Card, Security Token</td></tr><tr><td><strong>Something You Are</strong></td><td>Biometric characteristics.</td><td>Fingerprint, Face ID, Retina Scan</td></tr><tr><td><strong>Somewhere You Are</strong></td><td>Location-based authentication.</td><td>IP address, GPS location</td></tr><tr><td><strong>Something You Do</strong></td><td>Behavioral patterns.</td><td>Typing speed, Mouse movements</td></tr></tbody></table>

### **MFA Methods & Examples**

<table data-header-hidden data-full-width="true"><thead><tr><th width="245"></th><th width="439"></th><th></th></tr></thead><tbody><tr><td><strong>MFA Method</strong></td><td><strong>Description</strong></td><td><strong>Example Services</strong></td></tr><tr><td><strong>SMS/Email OTP</strong></td><td>A one-time password is sent via SMS or email.</td><td>Google, Microsoft, Banks</td></tr><tr><td><strong>Authenticator App (TOTP)</strong></td><td>Uses a time-based one-time password (TOTP) generated by an app.</td><td>Google Authenticator, Authy</td></tr><tr><td><strong>Hardware Token (HOTP)</strong></td><td>A physical device generates a one-time password.</td><td>YubiKey, RSA SecurID</td></tr><tr><td><strong>Biometric Authentication</strong></td><td>Uses fingerprint, facial recognition, or retina scan.</td><td>Apple Face ID, Windows Hello</td></tr><tr><td><strong>Push Notification</strong></td><td>Sends a push notification to a trusted device for approval.</td><td>Microsoft Authenticator, Duo Security</td></tr><tr><td><strong>Security Questions</strong></td><td>The user answers pre-configured questions.</td><td>Online Banking</td></tr></tbody></table>

## MFA Workflow with Spring Security

### **1. Dependencies**

```xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>com.github.bastiaanjansen</groupId>
    <artifactId>otp-java</artifactId>
    <version>2.0.0</version>
</dependency>
```

### **2. Generate TOTP Secret Key**

Users must **register their device** by scanning a QR code linked to a **TOTP secret key**.

```java
import dev.samstevens.totp.secret.DefaultSecretGenerator;
import dev.samstevens.totp.secret.SecretGenerator;

public class MFAService {
    public String generateSecretKey() {
        SecretGenerator generator = new DefaultSecretGenerator();
        return generator.generate();
    }
}
```

### **3. Verify OTP During Login**

After password authentication, verify the TOTP code:

```java
import dev.samstevens.totp.code.CodeVerifier;
import dev.samstevens.totp.code.DefaultCodeVerifier;
import dev.samstevens.totp.time.SystemTimeProvider;

public class MFAService {
    private final CodeVerifier verifier = new DefaultCodeVerifier(new SystemTimeProvider());

    public boolean verifyCode(String secret, String otp) {
        return verifier.isValidCode(secret, otp);
    }
}
```

### **4. Integrate MFA with Spring Security**

```java
@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/login").permitAll()
                .anyRequest().authenticated()
            )
            .formLogin(login -> login
                .loginPage("/login")
                .defaultSuccessUrl("/mfa", true) // Redirect to MFA verification page
            );

        return http.build();
    }
}
```

### **5. MFA Verification Endpoint**

```java
@RestController
@RequestMapping("/mfa")
public class MFAController {
    private final MFAService mfaService;

    @PostMapping("/verify")
    public ResponseEntity<String> verify(@RequestParam String secret, @RequestParam String otp) {
        if (mfaService.verifyCode(secret, otp)) {
            return ResponseEntity.ok("MFA Verified");
        }
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid MFA Code");
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://www.pranaypourkar.co.in/the-programmers-guide/spring/spring-features/spring-security/authentication/authentication-mechanism/multi-factor-authentication-mfa.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
