In the current digital environment, multi-factor authentication (MFA) has become a crucial practice for many applications, especially those managing sensitive information like financial services. Additionally, MFA is increasingly required by legislation across various sectors in the EU, making it vital for developers to integrate this security feature into their applications. If you are developing an application that necessitates two-factor authentication, this article is a valuable resource.
This article will walk you through the steps to implement a two-factor authentication system for a reactive API created with Spring Webflux. This application employs TOTP (time-based one-time passwords generated by an app on the user's device, such as Google Authenticator) as the second security factor, alongside traditional email and password combinations.
Understanding Two-Factor Authentication
From a technical perspective, two-factor authentication (or multi-factor authentication) is defined as a security method that necessitates users to present two or more verification factors. Typically, this means that a user must enter a password along with another form of identification. This additional identifier can be a one-time password, hardware tokens, biometric data (like fingerprints), or other verification methods.
This security procedure consists of several essential steps:
- The user inputs their email (username) and password.
- Along with their credentials, the user provides a one-time code generated by an authenticator app.
- The app verifies the email (username) and password, and checks the one-time code using the user's secret key, which was issued during the registration process.
Utilizing authenticator apps (such as Google Authenticator, Microsoft Authenticator, or FreeOTP) presents several benefits over SMS-based code delivery. These apps are less vulnerable to SIM attacks and can operate without cellular or internet access.
A Hands-On Example
In this article, we will create a straightforward REST API that integrates two-factor authentication methods. This API requires users to enter both an email-password combination and a short code generated by an app. You can use any compatible app to generate TOTP; for this demonstration, I will utilize Google Authenticator for Android. The source code can be found in this GitHub repository. The application requires JDK 11, Maven, and MongoDB (for user profile storage). Let’s examine the project structure in more detail: