hero

How to secure user authentication by applying 2FA live

Secure user authentication is a critical feature in any application, and Two-Factor Authentication (2FA) has been a trending security concept regarding user authentication for the last few years. Specifically, the 2FA Live approach has become an industry standard, already supported by most of the "big tech" companies. In this article, we will introduce the 2FA Live concept as a simple and robust authentication security practice that you should consider adopting to secure your online accounts. And, if you are a developer, here you will learn how to implement 2FA Live on your applications with a straightforward step-by-step tutorial. It is easier than you might think, and the security of your applications is worth the effort.

Alex Bruno Cáceres

Alex Bruno Cáceres

Why is 2FA Live a relevant topic?

Nowadays, almost everything can be done online, including remote work, shopping, financial transactions, and various other sensitive data operations. Consequently, user login is one of the most targeted exploit points by hackers and malicious software. Gaining access to a user's account can empower hackers with virtually unlimited possibilities.
More and more companies, online services, and applications are adopting 2FA Live to enhance authentication security, not only for user data protection, but also to help safeguard their business.

According to a report by Okta, a leading tech security company, the worldwide average of 2FA Live adoption among Okta clients jumped from 35% in 2019 to 64% in Jan/2023. Additionally, most of the relevant online accounts, such as emails, social media, e-commerce, and internet banking, are adopting 2FA Live as a standard sign-in security measure.
Moreover, some industries have adopted compliance rules for software applications that recommend 2FA as a security measure to protect user data. For example, the Health Insurance Portability and Accountability Act (HIPAA) for health-tech related applications.
Most applications rely on questionable rules to create supposedly "strong" passwords. However, those password policies are not secure enough. When users are forced to create complex and hard-to-remember passwords, they often write them down somewhere, which compromises security. Additionally, the practice of regularly changing passwords exacerbates the issue, as users are forced to create new complex passwords frequently. A possible solution on the user side is using a password manager app, but this responsibility lies entirely with the user, and your application will not be secure on its own. This is why the username and password combo alone is no longer sufficient to secure a user's online access, and increasing password complexity or changing frequency may actually weaken authentication security. Therefore, it is necessary to add a security step that is performed outside the login form itself, ideally where only the real users can confirm their identity. 2FA Live is likely one of the most reliable methods to achieve this.

"**Warning**

There are some suspicious websites claiming to be alternative 2FA Live methods, and they are catching some attention through the search engines. Do not trust supposed security tools developed by unknown authors that ask you to share secret keys or any sensitive data!

Use only reliable security tools made by well-known tech companies to protect your accounts, or the ones approved by your employer at your job. If you are a professional developing a system with a 2FA Live method, instruct your users to adopt only the industry standard security tools for 2FA."

What is 2FA Live?

Two-Factor Authentication (2FA) is an additional security layer used to ensure that individuals attempting to access an online account are indeed who they claim to be.
After entering their username and password, users are required to provide a second factor of security information. The most common approach used in web applications is the One-Time Password (OTP), which consists of a code generated for single-use only. There are some possible ways to implement this, but some of them are not recommended.

"Non-Live" 2FA methods

Sending the OTP code by email to the user is probably the easiest way to apply 2FA, but certainly not the most secure. This method can lead to issues such as spam blocking, email clients synchronization delay, or other issues related to email access and security.

Another option is to send the code via SMS to the user's mobile device. However, this method also has some limitations, including possible delivery delay and the requirement of a third-party provider to send the message, which adds costs to the project and requires sharing users' sensitive data (mobile phone number) with an external service.
Both of these methods are asynchronous, involving a message sent to the user through channels that may result in delivery delays. To accommodate this, OTP codes need a long expiration time to ensure the user can use them, which increases the risk of the codes being intercepted.

Additionally, these methods require:

  • 1.Storing the OTP code in a database for verification against user input.
  • 2.Managing the expiration time and providing invalidation methods.
  • 3.Updating the database whenever new OTP codes are created for security checks.

    All the cons above can weaken the application security and lead to bugs and poor user experience in any application, and that is why they are not recommended.

    A reliable 2FA Live method: authenticator app

There are a few methods to implement reliable and secure 2FA, but the easiest one for web applications is by using an authenticator app.

This method does not depend on an external service to deliver the OTP codes, as they are generated and checked by an algorithm using calculations with a secret key and the current time interval value at the login moment. The codes are valid for just a few seconds or a minute, so they work as an almost real-time check, bringing the "Live" concept to the security verification.

Users have the authenticator app installed and synchronized on their device, and no communication between the application login and the authenticator app is required.

Such a simple and robust identity verification greatly enhances the authentication security in web applications. Despite some resistance from most users to adopt an additional security step like an authenticator app, it is becoming an industry standard, and we are likely to see more web apps implementing 2FA Live.

How to implement 2FA live in a web app login

As a developer, you might think that implementing such a security feature in a web app login is challenging. However, it's actually quite straightforward, thanks to secure open-source libraries that handle most of the heavy lifting. All you need to do is integrate them into your application.

In the following simple tutorial, we will use open source libraries from the NPM registry to develop a 2FA Live system in a Node.js application, compatible with any reliable authenticator app.

We will focus on the back-end API implementation and won't cover the front-end aspects. However, it's essential to have a proper user interface flow for registration and authentication to include the 2FA Live security steps.

Requirements

To implement 2FA Live login security as described in this tutorial, you will need:

Tools:

  1. Node.js and NPM installed in your development environment.

    Skills:

  2. Proficiency in Node.js and Express (or a similar API framework).

    Step 1: Set up your Express app

If you don't have a running Express app already, create a new one with the basic structure and features of your choice. There are no special requirements regarding the app architecture beyond the NPM package we will use in the next steps.

Step 2: Install the necessary dependency

For this implementation, we need to install only one dependency package: @jsweb/utils.

It can be installed with any of the popular Node.js package managers:

npm i @jsweb/utils

pnpm i @jsweb/utils

yarn add @jsweb/utils


This is an open-source project that I develop, maintain, and distribute as an NPM package. It is a TypeScript/JavaScript library containing utilities for web development.

While writing this article, I developed and added a new module with easy-to-use methods for implementing a simple and secure 2FA Live system. We will use these methods in the next steps.

Step 3: Generate the activation secret key and QR Code

To activate the OTP synchronization with the authenticator app, we need to generate the user's secret key when or after they sign up.

Here we have a sample implementation code:

import express from 'express'
import { generateSecretKey } from '@jsweb/utils/modules/2fa'

const app = express()

// Sample registration endpoint
app.post('/sign-up', (req, res) => {
    // Register the users and securely store their data
    // Your sign-up logic goes here...

    // Sample: Identify your web app in the authenticator app
    const myWebApp = 'My Secure Web App'

    // Sample: Get the username for reference in the authenticator app
    const username = user.username

    // Generate the secret key
    const { qrcode, secret } = generateSecretKey(myWebApp, username)

    // Sample: The secret key must be securely stored along with user data
    user.secret = secret

    // Deliver the QR Code for the authenticator app activation
    res.json({ qrcode })
})

app.listen(3000, () => { console.log('Server running on port 3000'); })


  • The generateSecretKey method, from @jsweb/utils/modules/2fa , creates a random secret key using a secure crypt algorithm and generates a QR Code image that users can scan for authenticator app activation.

  • We need to securely store the secret key, on the web app database along with the user data, for further use on OTP validation.

  • The QR Code image is encoded as base64 string format for easy deliver through an API response and easy render on a front-end HTML image tag.

  • We need to provide our web app name and the username to be properly listed as references within the user's authenticator app, like this:

    authenticator


    Step 4: OTP verification

With the user registration response, we expect that the front-end display the QR Code to the user to scan and activate the authenticator app.

Then, we must check if the user is good to go with 2FA Live, so the user interface will also ask for the first OTP code check, and submit it to a verification API endpoint.

import express from 'express'
import { checkUserOTP } from '@jsweb/utils/modules/2fa'

const app = express()

// Middleware to parse JSON request bodies
app.use(express.json())

// Other endpoints...

// Sample 2FA Live OTP verification endpoint
app.post('/2fa-live-otp-verification', (req, res) => {
    // Get the submitted data
    const { username, otp } = req.body

    // Sample: Find the user on the data store
    const user = UserStore.find({ username })

    // Check if the submitted OTP is valid with the user secret key
    const valid = checkUserOTP(user.secret, otp)

    // Sample: A simple status response
    const status = valid ? 200 : 401
    res.sendStatus(status)
})


This sample endpoint code can be used not only for the initial OTP verification during 2FA Live activation but also for subsequent authentication attempts.
From now on, we can add that well-known OTP token verification screen at the front-end side after the login screen to secure the user authentication.

Is that all?


We are almost done!

From the API perspective, all the basics are set, but for a successful implementation, we need to consider a few additional steps:

Recommend reliable authenticator apps Suggest secure options to users, such as Google Authenticator or Microsoft Authenticator.

Provide setup instructions Offer clear instructions on how to set up and use the authenticator app, especially for users who are not yet familiar with this security practice.

Develop an account recovery system Implement a system for account recovery and/or provide backup access codes in case the user loses the device with the authenticator app.

Enhance user experience (UX) Ensure a friendly and attractive user experience throughout the authentication and verification process to avoid rejections due to poor UX.

Conclusion

In this article, we discussed the relevance of 2FA Live for securing user authentication in web applications and how this approach has become an industry standard in recent years.

Implementing 2FA Live is a crucial step in enhancing the security of your web application. By adding an extra layer of authentication using a reliable authenticator app, you can significantly reduce the risk of unauthorized access and protect your users' sensitive information.

The tutorial has shown that integrating 2FA Live using open-source libraries is straightforward and effective. With just a few lines of code within a back-end API, you can apply a simple and robust user OTP verification system.

However, remember to provide clear instructions for users and ensure a smooth user experience!

By adopting 2FA Live, you are not only following industry standards, but also prioritizing the security and trust of your users. Secure your applications today and stay ahead in the cybersecurity landscape.

References:

Secure Sign-in Trends Report | Okta
@jsweb/utils | npm