Secure your Web Applications with Facial Authentication
Tags: webdev, security, faceauthentication, javascript
Published: 2023-11-11 15:40:41


![face authentication](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i5mk47rvm0odwnb69uut.jpg)
For the last three decades, web technology has remained relevant due to its versatile nature and wide range of applications in building solutions. The web runs virtually everything, from simple blog sites to complex and scalable web-based ERP systems in B2B, gaming, and fintech, as well as other industries.
In order to personalize the user experience in web applications, we need to authenticate them. Over the years, user authentication has evolved from 4-digit personal identification numbers (PINs) to multi-factor authentication. The latter requires users to provide additional data such as OTP codes, usually sent to their mobile number or emails in addition to a username and password.
However, these authentication techniques are not sufficient to counter popular web attacks such as brute force, credential snuffing, dictionary attacks, or even phishing. This requires advanced authentication tools such as biometrics. With biometric authentication, organizations and users can eliminate impersonation frauds, prevent unauthorized access as well as prevent identity theft without necessarily remembering passwords and other security puzzles. In this article, we are going to show how to authenticate users in web applications using facial recognition tool known as Faceio.

Authenticating users in web applications using facial recognition
Typically, implementing this technology would be costly in terms of hardware components required and training in-house AI models to identify users by facial recognition.
However, PixLab has developed a tool known as Faceio that enables developers to authenticate users in web applications via a seamless REST API. With Faceio, you can simply implement passwordless authentication with a few lines of code.


![faceio console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/loocuaky8nbnq2iqfut6.png)
**Faceio API**
The [FACEIO API](https://faceio.net/) provides a simple and elegant widget that provides a secure face authentication experience to your users through simple calls to the register() & authenticate() methods. This utility is powered by the fio.js JavaScript library, which is simple enough to integrate in minutes and flexible enough to support highly custom configurations. Once deployed on your website or web application, you will be able to authenticate your existing users and register new users securely, with the utmost convenience on your favorite browser.

**Step 1: Import fio.js**
To instatiate fio.js, you need to load it from the Faceio content delivery network. Paste the following code snippet within the <body> tag on your html page.

```
<div id="faceio-modal"></div>
<script src="https://cdn.faceio.net/fio.js"></script>
```
This code will load fio.js asynchronously without affecting page load speed. 
This code will load fio.js asynchronously without affecting page load speed.
Step 2: Instantiate a new faceio object
Instantiate a new faceio() object and pass your application Public ID as follows. You can also insert this snippet just below the import code shown in Step 1.

```
<script type="text/javascript">
   /* Instantiate fio.js with your application Public ID */
    const faceio = new faceIO("app-public-id");
</script>
```

Retrieve your application Public ID is located at the Application Manager on the [FACEIO Console](https://console.faceio.net/).
Step 3: Invoke the Widget
To start the face recognition process, simply call register() or authentication(), the only two methods exported from the faceIO() class that you instantiated. register() is used to onboard new users (register) while authenticate() is used to authenticate previously registered users.
A typical implementation of this should be as shown in the code snippet below:

```
<html>
  <head>
    <title>Sign-In or Enroll via Face Recognition</title>
  </head>
  <body>
    <button onclick="enrollNewUser()">Enroll New User</button>
    <button onclick="authenticateUser()">Authenticate User</button>
    <div id="faceio-modal"></div>
    <script src="https://cdn.faceio.net/fio.js"></script>
    <script type="text/javascript">
        // Instantiate fio.js with your application's Public ID
        const faceio = new faceIO("app-public-id");
        function enrollNewUser(){
           // call to faceio.enroll() here will automatically trigger the on-boarding process
        }
        function authenticateUser(){
           // call to faceio.authenticate() here will automatically trigger the facial authentication process
        }
        function handleError(errCode){
            // Handle error here
        }
    </script>
  </body>
</html>
```

**Enroll method**
The register() method allows you to register new user transactions on your application. A better process is called integration. This is the equivalent implementation of the standard check-in/signup functionality in a traditional password-managed authentication system. An effective register() call, will trigger the FACEIO Utility, prompt the user for consent (if not already granted), request access (if not already granted) to the browser's webcam/front-camera stream, and finally extract and index the registered user's facial features for future authentication purposes.

The method takes some optional parameters such as locale for the interactive language, permissionTimeout is the number of seconds to wait for the user to grant access to the camera, but more importantly, register() accepts the payload, which is simply a tuple of arbitrary data that you can associate with that particular user, such as an email address, name, ID, etc. This payload will be returned to you upon future successful authentication of that particular user.
Usage
A typical invocation of the enroll method should look like this:

```
// Instantiate a new faceIO object with your application's Public ID
const faceio = new faceIO("app-public-id");
function enrollNewUser(){
  faceio.enroll({
    "locale": "auto", // Default user locale
    "payload": {
        /* The payload we want to associate with this particular user which is forwarded back to us upon future authentication of this user.*/
        "whoami": 123456, // Dummy ID linked to this particular user
        "email": "john.doe@example.com"
        }
    }).then(userInfo => {
        // User Successfully Enrolled! 
        alert(
            `User Successfully Enrolled! Details:
           Unique Facial ID: ${userInfo.facialId}
           Enrollment Date: ${userInfo.timestamp}
           Gender: ${userInfo.details.gender}
           Age Approximation: ${userInfo.details.age}`
        );
       console.log(userInfo);
       // handle success, save the facial ID (userInfo.facialId), redirect to the dashboard...
    }).catch(errCode => {
       // Something went wrong during enrollment, log the failure
       handleError(errCode);
    })
}

```

**Authenticate Method**
The authenticate() method allows you to validate existing registered users on your application. It is an equivalent implementation of the standard login/login functionality in a traditional password-managed authentication system. An effective authenticate() call, will trigger the FACEIO utility, request access (if not already granted) to the browser's webcam/front camera stream, and finally initiate the facial recognition process. authentication() only requires a single image to run, takes less than 100 milliseconds on average to run, and is extremely bandwidth efficient, making it suitable for use in slow networks. Depending on your application's security configuration, after the basic facial recognition engine has successfully identified the target user, they must confirm their PIN (freely chosen during the sign-in process). sign) for method validation() to succeed and thus the Promise will be resolved.

```
promise = faceio.authenticate({parameters})
promise
.then(userData => {
  /* User successfully authenticated/identified */
})
.catch(errCode => {
  /* handle the error */
})
```

Usage
Below is a simple implementation of how you can authenticate registered users with Faceio using facial recognition

```
const faceio = new faceIO("app-public-id"); // Initialize with your application's Public ID
function authenticateUser(){
    faceio.authenticate({
        "locale": "auto" // Default user locale
    }).then(userData => {
        console.log("Success, user identified")
        // Grab the facial ID linked to this particular user which will be same
        // for each of his successful future authentication. FACEIO recommend 
        // that your rely on this Facial ID if you plan to uniquely identify 
        // all enrolled users on your backend for example.
        console.log("Linked facial Id: " + userData.facialId)
        // Grab the arbitrary data you have already linked (if any) to this particular user
        // during his enrollment via the payload parameter of the enroll() method.
        console.log("Payload: " + JSON.stringify(userData.payload)) // {"whoami": 123456, "email": "john.doe@example.com"} from the enroll() example above
    }).catch(errCode => {
        handleError(errCode)
    })
}
```

Authentication() returns a Promise whose implementation handler receives a userData object when the user has been successfully identified. The most important include payload, which is the arbitrary data you bound (if any) to that particular user when they registered via the payload parameter that the register() method takes, and the face ID, which is the unique identifier generic identity assigned to that particular user upon registration.
This face ID along with the payload data can act as a search key on your backend to retrieve data related to this particular user on each successful authentication, for example. The details of the userInfo object are documented in the Return Values section below. If the user denies the camera permission example, the promise will be rejected with the corresponding error code, such as fioErrCode.PERMISSION_REFUSED or fioErrCode.TERMS_NOT_ACCEPTED. Refer to the [Error Codes section](https://faceio.net/integration-guide#error-codes) for a complete list of all possible error codes.

In summary, Faceio represents a significant leap in web application security. This facial recognition tool by PixLab simplifies user authentication with its seamless REST API, eliminating the need for expensive hardware and AI model training. With just a few lines of code, developers can implement passwordless authentication, enhancing both security and user experience.[ Faceio's](https://faceio.net/) biometric authentication empowers organizations and users to combat impersonation fraud, unauthorized access, and identity theft without the hassle of password management. By streamlining the onboarding of new users and validating existing ones, Faceio sets a new standard for web application security, offering robust protection against evolving cyber threats with a user-friendly approach.