Ultimate Guide to FaceIO
Get started with FaceIO to implement facial authentication on a web application. This guide will enable developers to enable face authentication.
Join the DZone community and get the full member experience.
Join For FreeFacial recognition technology called FaceIO is employed for online user identification. For increased security during online transactions and access to sensitive information, it can be linked to websites and apps to verify a person's identity using their distinctive facial features. It can be used in addition to more established authentication techniques, such as passwords, for increased security. It's crucial to consider any potential drawbacks, such as bias, errors, and privacy issues.
Key Features of FaceIO
FaceIO may include the following features that could make it a viable tool for online authentication:
- Convenience: Users of FaceIO can authenticate themselves more quickly and efficiently than by entering a password or providing the answers to security questions by simply taking a picture of their face.
- Increased Security: FaceIO can add an extra degree of protection for online transactions and access to sensitive information by employing facial recognition technology.
- Multi-Factor Authentication: The authentication procedure can be made more secure by using it in conjunction with other authentication techniques like passwords and security questions.
- Liveness Detection: The ability of the technology to tell whether the camera's subject is a real person and not a photograph or video will prevent fraud.
- Mobile Compatibility: A broad spectrum of consumers can use the technology because it can be used on mobile devices with front-facing cameras.
- Remote Verification: For firms that must confirm the identification of clients who are not physically present, the technology can be utilized for remote verification.
FaceIO is more open and user-friendly because it doesn't require any special hardware or software on the user's device. Regardless of the server-side language or front-end framework, it can also be adapted to other websites and web-based apps. It still has drawbacks, though, like potential prejudice, errors, and privacy concerns, which should be taken into account before implementation.
Integrating FaceIO in Your Web Application or Website
To add FaceIO to your web app or website, you will need to integrate the technology into your existing codebase. In most cases, this entails adding a few lines of JavaScript code to your front-end code and creating an API in your server-side code.
The steps for including FaceIO in your website or web application are described in the following broad overview:
Step 1
Sign up for a FaceIO account. You will need to create an account with a FaceIO provider to access and use the technology on your web-based application or website.
Use your email address to log in to the FaceIO Console initially. Following a series of automated steps, the Application Wizard produces your first application after connecting to your website or web application. The following steps usually involve entering the program's name, choosing an engine for facial recognition, selecting a cloud storage area, looking over security settings, and adjusting the Widget layout.
Integrate the fio.js FaceIO Javascript library on your website after creating your application and initialize it with your app's Public ID. By doing this, your website can employ facial recognition technology to verify users. Consider the privacy and security issues, and test the technology frequently to ensure it is functioning as intended.
Integrate the FaceIO JavaScript library into your front-end code. This typically involves adding a few lines of code to your HTML and JavaScript files. The JavaScript library allows you to access facial recognition technology and capture images of the User's face.
Step 2
Put the following code in the HTML page(s) you intend to use to launch fio.js before the closing /body> element.
<div id="faceio-modal"></div>
<script src="https://cdn.faceio.net/fio.js"></script>
This code first constructs the "faceio-modal" div element and then adds the "fio.js" FaceIO JavaScript library from the FaceIO CDN (Content Delivery Network). The facial recognition widget or modal will be displayed on the page in the div element with the id "faceio-modal."
It's crucial to start the fio.js library with the app's public ID as well as any additional settings you wish to set, such as the language and other customization choices and the modal's design.
Step3
To initialize fio.js, you must create a new faceIO() object and pass in your app's Public ID as an argument. This allows the fio.js library to connect to your specific application and use its facial recognition capabilities. The code should look something like this:
<script type="text/javascript">
/* Instantiate fio.js with your application Public ID */
let faceio = new faceIO("your_application_public_id");
</script>
It's also important to remember that you may further personalize the facial recognition experience on your website by passing more options to the faceIO() objects, such as the modal's layout, language, and other customization choices.
The Public ID can be found in your application's dashboard in the settings or general section. This particular application-specific identification is necessary for the fio.js library to connect to your application and access its face recognition features.
Step 4
The enroll() and authenticate() methods are used to invoke the facial recognition widget and start the enrollment or authentication process, respectively. enroll() is used to register new users, capture their facial features, and save them in the cloud storage associated with your application. authenticate() is used to verify a user's identity by comparing their facial features with the ones previously enrolled in the system. To invoke the widget, you can call these methods on the instantiated FaceIO object like so:
<body>
<button onclick="enrollNewUser()">Enroll New User</button>
<button onclick="authenticateUser()">Authenticate User</button>
<div id="faceio-modal"></div>
<script data-fr-src="https://cdn.faceio.net/fio.js"></script>
<script type="text/javascript">
// Create a fio.js instance using your app's Public ID.
const faceio = new faceIO("your-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>
Understanding of Enroll() and Authenticate()
Enroll
To enroll a new user in your application using the faceIO object, you can call the enroll() method. This method will bring about the FaceIO Widget and ask for the User's consent to access the webcam, extract and index the User's facial features for future authentication. It then takes in optional parameters such as locale for the interaction language, permissionTimeout for the time to wait for camera access permission, and a payload of arbitrary data such as an email address, name, or ID.
The enroll() method returns a promise that, when fulfilled, returns a userInfo object with a Facial ID unique to the enrolled User. If the User denies camera access permission or rejects the terms of use, the promise will be rejected with an error code. Additionally, suppose you have set up a webhook handler. In that case, the enroll() method will make a POST request to the configured URL after each successful enrollment, allowing for real-time updates and synchronization with your application backend.
// Instantiate the faceIO object
const faceIO = new FaceIO("your_public_ID");
// Create a function to handle the enrollment process
const handleEnrollment = async (payload) => {
try {
// Call the enroll() method and pass in the payload data
const userData = await faceIO.enroll({ payload });
// Log the userData object for debugging purposes
console.log(userData);
// Save the userData object to your backend for future reference
saveUserDataToBackend(userData);
// Notify the User that the enrollment was successful
alert('Enrollment successful!')
} catch (err) {
// Handle any errors that may occur during the enrollment process
console.error(err);
alert('Enrollment failed. Please try again.');
}
}
// Call the handleEnrollment function when the User clicks the "Enroll" button
document.querySelector('#enroll-button').addEventListener('click', () => {
handleEnrollment({ name: 'John Doe', email: 'johndoe@example.com' });
});
In this example, we first instantiate the FaceIO object. Then we create a function handleEnrollment that will take care of the enrollment process. Inside this function, we call the enroll() method and pass in the payload data, which is an arbitrary object that can contain any information about the User. The enroll() method returns a promise that resolves with a userData object which contains the facial ID and the payload data that was passed in.
We log the userData object for debugging purposes and save the userData object to our backend. Finally, we notify the User that the enrollment was successful. We also handle any errors that may occur during the enrollment process. In this example, we call the handleEnrollment function when the User clicks the "Enroll" button.
Authenticate
The authenticate() method recognizes and authenticates previously enrolled users on an application. It requests access to the browser's webcam and starts the facial recognition process, which only requires one frame and takes less than 100 milliseconds. Depending on the app's security configuration, the User may need to confirm their PIN code for the authenticate() method to succeed. The method also takes optional parameters for camera access permission timeout and interaction language.
The authenticate() method returns a promise with a userData object upon successful identification, which includes the payload data linked to the User during enrollment and a Facial ID unique identifier. The promise is rejected with an error code if camera access is denied.
const faceIO = new FaceIO("your public_ID");
faceIO.authenticate()
.then((userData) => {
// User has been successfully authenticated
console.log(userData);
})
.catch((error) => {
// An error occurred during the authentication
console.error(error);
});
In this example, calling the authenticate() method will bring about the FaceIO widget, which will request access to the User's webcam or frontal camera. Once the User grants access, the facial recognition process will begin. If the User is successfully identified, the promise returned by authenticate() will be resolved with a userData object containing information about the User. The security will be rejected with an error code if an error occurs.
You can also pass optional parameters to the authenticate() method, such as a permissionTimeout to specify the number of seconds to wait for the User to grant camera access or a locale to set the language for the interaction.
General Boiler Plate
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FACEIO Integration Boilerplate</title>
<style>
.container {
text-align: center;
}
button {
padding: 10px 20px;
font-size: 18px;
}
</style>
</head>
<body>
<div class="container">
<h1>FACEIO Integration Boilerplate</h1><br>
<button onclick="enrollNewUser()" title="Enroll a new user on this FACEIO application">Enroll New User</button>
<button onclick="authenticateUser()" title="Authenticate a previously enrolled user on this application">Authenticate User</button>
</div>
<div id="faceio-modal"></div>
<script data-fr-src="https://cdn.faceio.net/fio.js"></script>
<script type="text/javascript">
// Initialize the library first with your application Public ID.
// Grab your public ID from the Application Manager on the FACEIO console at: https://console.faceio.net/
const faceio = new faceIO("app-public-id"); // Replace with your application Public ID
function enrollNewUser() {
// Start the facial enrollment process
faceio.enroll({
"locale": "auto", // Default user locale
"userConsent": false, // Set to true if you have already collected user consent
"payload": {
/* The payload we want to associate with this particular user
* which is forwarded back to us on each of his future authentication...
*/
"whoami": 123456, // Example of 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, redirect to dashboard...
}).catch(errCode => {
// handle enrollment failure. Visit:
// https://faceio.net/integration-guide#error-codes
// for the list of all possible error codes
handleError(errCode);
// If you want to restart the session again without refreshing the current TAB. Just call:
faceio.restartSession();
// restartSession() let you enroll the same user again (in case of failure)
// without refreshing the entire page.
// restartSession() is available starting from the PRO plan and up, so think of upgrading your app
// for user usability.
});
}
function authenticateUser() {
// Start the facial authentication process (Identify a previously enrolled user)
faceio.authenticate({
"locale": "auto" // Default user locale
}).then(userData => {
console.log("Success, user recognized")
// 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 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 the enroll() method takes.
console.log("Associated Payload: " + JSON.stringify(userData.payload))
// {"whoami": 123456, "email": "john.doe@example.com"} set via enroll()
}).catch(errCode => {
// handle authentication failure. Visit:
// https://faceio.net/integration-guide#error-codes
// for the list of all possible error codes
handleError(errCode);
// If you want to restart the session again without refreshing the current TAB. Just call:
faceio.restartSession();
// restartSession() let you authenticate the same user again (in case of failure)
// without refreshing the entire page.
// restartSession() is available starting from the PRO plan and up, so think of upgrading your app
// for user usability.
});
}
function handleError(errCode) {
// Log all possible error codes during user interaction..
// Refer to: https://faceio.net/integration-guide#error-codes
// for a detailed overview when these errors are triggered.
switch (errCode) {
case fioErrCode.PERMISSION_REFUSED:
console.log("Access to the Camera stream was denied by the end user");
break;
case fioErrCode.NO_FACES_DETECTED:
console.log("No faces were detected during the enroll or authentication process");
break;
case fioErrCode.UNRECOGNIZED_FACE:
console.log("Unrecognized face on this application's Facial Index");
break;
case fioErrCode.MANY_FACES:
console.log("Two or more faces were detected during the scan process");
break;
case fioErrCode.FACE_DUPLICATION:
console.log("User enrolled previously (facial features already recorded). Cannot enroll again!");
break;
case fioErrCode.PAD_ATTACK:
console.log("Presentation (Spoof) Attack (PAD) detected during the scan process");
break;
case fioErrCode.FACE_MISMATCH:
console.log("Calculated Facial Vectors of the user being enrolled do not matches");
break;
case fioErrCode.WRONG_PIN_CODE:
console.log("Wrong PIN code supplied by the user being authenticated");
break;
case fioErrCode.PROCESSING_ERR:
console.log("Server side error");
break;
case fioErrCode.UNAUTHORIZED:
console.log("Your application is not allowed to perform the requested operation (eg. Invalid ID, Blocked, Paused, etc.). Refer to the FACEIO Console for additional information");
break;
case fioErrCode.TERMS_NOT_ACCEPTED:
console.log("Terms & Conditions set out by FACEIO/host application rejected by the end user");
break;
case fioErrCode.UI_NOT_READY:
console.log("The FACEIO Widget could not be (or is being) injected onto the client DOM");
break;
case fioErrCode.SESSION_EXPIRED:
console.log("Client session expired. The first promise was already fulfilled but the host application failed to act accordingly");
break;
case fioErrCode.TIMEOUT:
console.log("Ongoing operation timed out (eg, Camera access permission, ToS accept delay, Face not yet detected, Server Reply, etc.)");
break;
case fioErrCode.TOO_MANY_REQUESTS:
console.log("Widget instantiation requests exceeded for freemium applications. Does not apply for upgraded applications");
break;
case fioErrCode.EMPTY_ORIGIN:
console.log("Origin or Referer HTTP request header is empty or missing");
break;
case fioErrCode.FORBIDDDEN_ORIGIN:
console.log("Domain origin is forbidden from instantiating fio.js");
break;
case fioErrCode.FORBIDDDEN_COUNTRY:
console.log("Country ISO-3166-1 Code is forbidden from instantiating fio.js");
break;
case fioErrCode.SESSION_IN_PROGRESS:
console.log("Another authentication or enrollment session is in progress");
break;
case fioErrCode.NETWORK_IO:
default:
console.log("Error while establishing network connection with the target FACEIO processing node");
break;
}
}
</script>
</body>
</html>
Two buttons are present on the page: "Enroll New User" and "Authenticate User," which, when clicked, respectively, invoke the corresponding JavaScript functions "enrollNewUser()" and "authenticateUser()."
Using the "faceio.enroll()" method, the "enrollNewUser()" function initiates facial enrollment by sending in an options object that includes various parameters like "locale" and "payload." The "payload" option is used to link arbitrary data with the User, such as their email address or a unique user ID, while the "locale" field is used to establish the User's preferred language. The function logs the User's unique face ID, enrollment date, gender, and approximate age to the console and displays an alert message to the User if the enrollment procedure is successful. The function invokes the "handleError()" method, which is not specified in this code sample if an error occurs during the enrolling process.
Using the "faceio.authenticate()" method, the "authenticateUser()" function initiates facial authentication by sending in an options object that contains the "locale" parameter. The function logs a message to the console informing the User that they have been recognized, along with the User's facial ID and any related payload data, if the authentication process is successful. The function executes the "handleError()" function if an error occurs during the authentication procedure.
It's crucial to remember that the "handleError()" function is not declared in the code snippet; as a result, it must be added for the code to work correctly. The actual app public id generated by the service should also be used in place of FaceIO ("app-public-id").
Reasons Why Fio.js Require a Running HTTP Server to Load
JavaScript is a client-side language, which means that it executes in the browser rather than on the server, making it one of the primary causes of this. The server requests the HTML, CSS, and JavaScript files required to render a web page whenever the browser loads a web page. The browser subsequently executes the JavaScript code, which can send more requests to the server. Fio.js must send queries to the FaceIO server to retrieve data or carry out operations using the FaceIO REST API.
JavaScript code cannot, however, make requests to servers other than the one that provided the initial page because of the security measures built into the browser. The "same-origin policy" refers to this practice. The requests made by fio.js must be proxied through a server on the same origin as the web page to get around this restriction.
Fio.js employs the XMLHttpRequest (XHR) API, a browser API for sending HTTP queries, which is another reason it needs an active HTTP server. The XHR API must be loaded from a web server since it can only be used when JavaScript code is running within the context of a web page.
Maintaining Your Application
You may administer your FaceIO application using the Application Manager, a web-based interface. It offers a user-friendly interface for setting up and controlling your application's resources, including users, groups, and permissions.
When utilizing the Application Manager to manage your FaceIO application, you should keep the following in mind:
- User Management: In your application, you may create, edit, and delete users, add them to various groups, and give them different permissions.
- Group Management: In your application, groups can be created, modified, and deleted, with users assigned and permissions set.
- Permission Management: Users and groups can be given permission to access, write, and execute various resources in your application.
- Resource Management: Resources in your application, such as database tables and files, can be created, edited, and deleted.
- Monitoring Analytics: The Application Manager offers monitoring and analytics features like real-time performance metrics and logs to understand how your application is used.
- Security: The Application Manager offers robust security features like multi-factor authentication and encryption to safeguard your application and its data.
- Integration: using the Application Manager, you can connect your app to other services, such as social media sites and outside databases,
- Scalability: You may quickly scale your application using the Application Manager as necessary to handle rising user counts and additional traffic.
Opinions expressed by DZone contributors are their own.
Comments