Skip to content

Two-Factor Authentication Solution

Introduction

Two-factor authentication (2FA) is a method of adding additional security to your account. The first "factor" is your usual password that is standard for any account. The second "factor" is a verification code retrieved from an app on a mobile device or computer. 2FA is conceptually similar to a security token device that banks in some countries require for online banking. Other names for 2FA systems include OTP (one-time password) and TOTP (Time-based One-time Password algorithm).

2FA works in a similar way for your online accounts. When you sign in with your username and password, you also need to provide a second factor, such as a code sent to your phone, a push notification on your device, or a physical security key that you plug in. This makes it harder for hackers to access your accounts, even if they know your password.

To understand how 2FA works, let's look at an example of a web application that uses 2FA. The web application has two parts: the frontend and the backend. The frontend is what you see and interact with on your browser, such as the login page and the dashboard. The backend is what runs on the server, such as the database and the logic. The frontend and the backend communicate with each other through HTTP requests and responses.

Solution

I'm going to implement a 2FA (TOTP) system in my project. For some reason, I'll make it a two-step login (one-step is also no problem). I'll create an API for each of these two steps:

  • Pre-Login
  • 2FA

2FA

Step-1: Pre-Login

This step is the account-password login. However, as you can see, this API returns a QRCode_URL only (if it is the first time to log in) instead of a token.

Step-2: 2FA

After the user passes the account password authentication, it will immediately jump to the 2FA page and prompt the user to enter the 2FA code.

There are two scenarios for the frontend at this step:

  • If it is the first time for the user to log in, the page will convert the QRCode_URL with the secret-key returned by the server into a QRCode and display it, so that the user can scan it (via a 2FA mobile App like Google-Authenticator or Microsoft-Authenticator) and record the secret-key to view the one_time_password (OTP).
  • If it's not, the page will only display the OTP input box, and then the user needs to find the secret-key in the App to view the OTP.

If the OTP is verified, the backend will mark the account as logged-in, generate a token and return it to the frontend. After that, the frontend and backend can interact with each other using this token.