Biometric Authentication in React-Native Applications
If you're looking to improve security in your React-Native applications, you're in the right place — learn to integrate biometric authentication practices.
Join the DZone community and get the full member experience.
Join For FreeMobile application biometric authentication is an effective approach to multi-factor authentication (MFA) for the verification of individuals’ identity that utilizes the possession of mobile devices as a first factor and then verifies the unique biometric identifier by using the application as a second factor.
Passwords are not as reliable and secure as they were previously. A number of hackers are progressing in parallel to technological advancements. Due to this evolution, cybersecurity is becoming a hot topic as data breaches are continuously occurring. Keeping in view the enormous rate of identity theft, mobile applications should utilize new methods to secure data. The most efficient, effective, and reliable method is mobile biometric authentication.
The Retail Banking Biometrics Confidence Report concludes that customers not only believe in biometric technologies as a much more secure method to combat identity theft, but they demand more biometric options for mobile banking. The statistics below depict the shares of mobile biometric device owners from 2016 to 2022 that download biometric applications globally. It is evaluated that by the year 2022, 96.8% of biometric verification device users are supposed to download biometric applications.
Why You Should Choose Expo
ReactJS is a trustworthy javascript library that enhances the speed of JavaScript and utilizes innovative ways to render highly dynamic, yet responsive web pages. Virtual DOM in React enhances user experience and React Templates help developers to work efficiently and effectively. In addition to that, React Native is a native application development framework for Android and iOS that permits the re-utilization of 95% of the code, leaving the rest to designing platform-specific interfaces.
Expo is the best choice if you are trying to develop a mobile application and if you are not sure where to start and what to do. The open-source platform, Expo, is utilized to develop universal native apps for iOS, Android, and the web with React and JavaScript. Expo is an extension to ReactNative, which offers a wide range of libraries and components to facilitate the development process of mobile applications with the help of React Native. Moreover, it gives access to additional APIs to perform common tasks such as signing in with Facebook, accessing the phone gyroscope, reading contacts from the phone, and more.
Below is a list of steps to integrate fingerprint authentication to Expo Application with the help of the expo-local-authentication library to have an insight into the advantages of biometric authentication and how simple is the process of implementation. This implementation also goes for facial authentication.
Let’s get started.
Installation
Thankfully installation is a very manageable process with the expo-local-authentication library.
Run the code below in case you are using yarn:
xxxxxxxxxx
yarn add expo-local-authentication
Run the code below in case you are using npm.
xxxxxxxxxx
npm i —save expo-local-authentication
Assurance of Device Compatibility
It is mandatory to ensure that the user’s device is compatible enough to utilize fingerprint authentication.
You have to import LocalAuthentication from expo-local-authentication.
xxxxxxxxxx
import * as LocalAuthentication from ‘expo-local-authentication’;
Device compatibility can be easily ensured by calling LocalAuthentication.hasHardwareAsync()
in our componentDidMount()
This function returns a boolean which depicts if the present device possesses the essential hardware or not. If the function returns false, you’ll want to ensure that you have a fall-back option for user authentication.
xxxxxxxxxx
componentDidMount(){checkDeviceForHardware = async ()
this.checkDeviceForHardware();=> {
let compatible = await LocalAuthentication.hasHardwareAsync();
if (compatible) {
alert('Compatible Device!');
}
else alert('Current device does not have the necessary hardware!')
};
}
Checking For Biometric Records
After ensuring that the user’s device is compatible with the process of biometric authentication, we need to make sure that user biometrics are recorded in their operating system.
This can be once again achieved by calling the following method: LocalAuthentication.isEnrolledAsync(
This method also returns a boolean, which indicates whether user biometric records are found or not.
xxxxxxxxxx
checkForBiometrics = async () => {
let biometricRecords = await LocalAuthentication.isEnrolledAsync();
if (!biometricRecords) {
alert('No Biometrics Found')
} else {
alert('Biometrics Found')
}
};
Biometric Scanning
After the assurance of device compatibility and user biometric record set, we can now proceed further to biometric scanning.
Biometric scanning is done by calling the following method:
LocalAuthentication.authenticateAsync()
This method will return an object possessing a success key along with a boolean value which depicts if the authentication was successful or not. An error key contains the error code when the authentication fails. It is important to note that Android OS doesn’t give a User Interface (UI) prompt to scan. You’ll have to give your own. In contrast, iOS has a User Interface (UI) prompt and you don’t have to make additional efforts.
xxxxxxxxxx
handleAuthentication= async() //handleLogin() is your function for Login=> {
handleLogin = async () => {
this.props.navigation.navigate("HOME")
}
let result = await LocalAuthentication.authenticateAsync();
if (result.success) {
this.setState({scanned:true});
this.handleLogin();
}
else alert ('Authentication Failed')
}
Putting It All Together
The following code depicts Login components as the cleaned-up version of our authentication by utilizing the expo-local-authentication library.
The main focus is on the handleauthentication()
function besides all the functions of components we have mentioned previously.
The USER variable in AsyncStorage is your username after the scanning process of your biometrics which you send in a POST request to log in to your application. You have to enter your data in the input field if biometrics are not scanned and this procedure is typical for the login process.
import React, { Component } from "react";
import { Button } from "../components";
import { Input } from "../components";
import axios from "axios";
import { AsyncStorage } from "react-native";
import { _storeToken, _clearToken, _storeUser } from "../helpers/asyncStorage";
import * as LocalAuthentication from 'expo-local-authentication';const AUTH_KEY = "@AUTH_TOKEN_KEY";
const USER = "@USER";export default class Login extends Component { constructor(props) {
super(props);
this.state = {
username: "",
password: "",
incorrect: false,
sccaned:false};
}
componentDidMount() {
this.checkDeviceForHardware();
this.checkForBiometrics();
if(!this.state.scanned)
this.handleLoginPress();}checkDeviceForHardware = async () => {
let compatible = await LocalAuthentication.hasHardwareAsync();
if (compatible) {
alert('Compatible Device!');}
else alert('Current device does not have the necessary hardware!')
};checkForBiometrics = async () => {
let biometricRecords = await.LocalAuthentication.isEnrolledAsync();
if (!biometricRecords) {
alert('No Biometrics Found')
}
else {
alert('Biometrics Found')
}
};handleLoginPress =async () => {
this.handleAuthentication();
};handleAuthentication= async() => {
let result = await LocalAuthentication.authenticateAsync();
if (result.success) {
this.setState({sccaned:true})
const data = {
username:"username", //login data for your account
password:"password"} const headers = {
"Content-Type": "application/json",}; var temp= this; axios.post("https://mywebsite.com/login", data, {headers:headers}).then(function (result) {
if (result && result.data) {
const AUTH_TOKEN = result.data.token;
const AUTH_USER = result.data.username;
_storeUser(AUTH_USER);
_storeToken(AUTH_TOKEN);
if (AUTH_TOKEN){
temp.props.navigation.navigate("HOME");}
else {
temp.setState({ incorrect: true });}}}).catch(function (error) {
temp.setState({ incorrect: true });
console.log(error);});} else {
alert('Error! Enter your username and password!');}};_login = async () => {
const { name, password } = this.state;
const data = {name, password};
const headers = {"Content-Type": "application/json"};
var temp= this;
axios.post("https://mywebsite.com/login", data, {headers:headers}).then(function (result) {
if (result && result.data) {
const AUTH_TOKEN = result.data.token;
const AUTH_USER = result.data.username;
_storeUser(AUTH_USER);
_storeToken(AUTH_TOKEN);
if (AUTH_TOKEN){
temp.props.navigation.navigate("HOME");
}
else {temp.setState({ incorrect: true });}}})
.catch(function (error) {
temp.setState({ incorrect: true });
console.log(error);});
};render() {return ( <View style={styles.container}> <Input placeholder="Username" autoCompleteType="username" onChangeText={(text) => this.setState({ username: text })}></Input> <Input placeholder="Password" autoCompleteType="password" secureTextEntry={true} onChangeText={(text) => this.setState({ password: text })}></Input> {this.state.incorrect ? <Text>Inccorect username or password</Text> : null} <Button onPress={this._login}>Login</Button></View>
);}}const styles = {
container: {
flex: 1,
backgroundColor: "white",
justifyContent: "flex-start",
alignItems: "center",
padding: 10}
}
Conclusion
Congratulations! You have now successfully integrated a biometric authentication system in your Expo application.
You will become familiar with various advantages for biometric authentication after running this application.
- User friendly
- Easy to use
- Privacy protection
- No more stolen passwords
Biometric authentication for mobile applications is fast, accurate, reliable, and secure as compared to other authentication methods. With no fear of identity theft and no fear of evolving hackers, you would have no fear that someone might access your information.
Opinions expressed by DZone contributors are their own.
Comments