DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • In-App Browsers in Mobile Apps: Benefits, Challenges, Solutions
  • Development of a Truck Tracker and Delivery Services Software
  • Building a Receipt Scanner App With OCR, OpenAI, and PostgreSQL

Trending

  • Apache Doris vs Elasticsearch: An In-Depth Comparative Analysis
  • Solid Testing Strategies for Salesforce Releases
  • Contextual AI Integration for Agile Product Teams
  • Simplify Authorization in Ruby on Rails With the Power of Pundit Gem
  1. DZone
  2. Coding
  3. Frameworks
  4. Biometric Authentication in React-Native Applications

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.

By 
Liam Smith user avatar
Liam Smith
·
Mar. 17, 21 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
5.8K Views

Join the DZone community and get the full member experience.

Join For Free

Mobile 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: 

Java
 




xxxxxxxxxx
1


 
1
yarn add expo-local-authentication



Run the code below in case you are using npm. 

Java
 




xxxxxxxxxx
1


 
1
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.  

Java
 




xxxxxxxxxx
1


 
1
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. 

Java
 




xxxxxxxxxx
1


 
1
componentDidMount(){checkDeviceForHardware = async ()
2
 this.checkDeviceForHardware();=> {
3
 let compatible = await LocalAuthentication.hasHardwareAsync();
4
 if (compatible) {
5
 alert('Compatible Device!');
6
 }
7
 else alert('Current device does not have the necessary hardware!')
8
}; 
9
}



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.

Java
 




xxxxxxxxxx
1


 
1
checkForBiometrics = async () => {
2
 let biometricRecords = await LocalAuthentication.isEnrolledAsync();
3
 if (!biometricRecords) {
4
 alert('No Biometrics Found')
5
 } else {
6
 alert('Biometrics Found')
7
 }
8
 };



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. 

Java
 




xxxxxxxxxx
1
11


 
1
handleAuthentication= async() //handleLogin() is your function for Login=> {
2
handleLogin = async () => {
3
 this.props.navigation.navigate("HOME")
4
} 
5
 let result = await LocalAuthentication.authenticateAsync();
6
 if (result.success) {
7
 this.setState({scanned:true});
8
 this.handleLogin();
9
 }
10
 else alert ('Authentication Failed')
11
}



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. 

Java
 




x
80


 
1
import React, { Component } from "react";
2
import { Button } from "../components";
3
import { Input } from "../components";
4
import axios from "axios";
5
import { AsyncStorage } from "react-native";
6
import { _storeToken, _clearToken, _storeUser } from "../helpers/asyncStorage";
7
import * as LocalAuthentication from 'expo-local-authentication';const AUTH_KEY = "@AUTH_TOKEN_KEY";
8
const USER = "@USER";export default class Login extends Component { constructor(props) {
9
        super(props);
10
        this.state = {
11
           username: "",
12
           password: "",  
13
           incorrect: false,
14
           sccaned:false};
15
    }
16
componentDidMount() {
17
       this.checkDeviceForHardware();
18
       this.checkForBiometrics();     
19
       if(!this.state.scanned)
20
       this.handleLoginPress();}checkDeviceForHardware = async () => {
21
    let compatible = await LocalAuthentication.hasHardwareAsync();
22
    if (compatible) {
23
    alert('Compatible Device!');}
24
    else alert('Current device does not have the necessary hardware!')
25
};checkForBiometrics = async () => {
26
    let biometricRecords = await.LocalAuthentication.isEnrolledAsync();
27
    if (!biometricRecords) {
28
    alert('No Biometrics Found')
29
    } 
30
    else {
31
    alert('Biometrics Found')
32
    }
33
};handleLoginPress =async () => {
34
    this.handleAuthentication();
35
};handleAuthentication= async() => {
36
    let result = await LocalAuthentication.authenticateAsync();
37
    if (result.success) {
38
    this.setState({sccaned:true})
39
    const data = {
40
    username:"username", //login data for your account
41
    password:"password"}    const headers = { 
42
         "Content-Type": "application/json",};    var temp= this;    axios.post("https://mywebsite.com/login", data,                      {headers:headers}).then(function (result) {
43
     if (result && result.data) {
44
     const AUTH_TOKEN = result.data.token; 
45
     const AUTH_USER = result.data.username;
46
     _storeUser(AUTH_USER);
47
     _storeToken(AUTH_TOKEN);
48
     if (AUTH_TOKEN){
49
        temp.props.navigation.navigate("HOME");}
50
     else {
51
        temp.setState({ incorrect: true });}}}).catch(function (error) {
52
    temp.setState({ incorrect: true });
53
    console.log(error);});}    else {
54
       alert('Error! Enter your username and password!');}};_login = async () => {
55
     const { name, password } = this.state;
56
     const data = {name, password}; 
57
     const headers = {"Content-Type": "application/json"};
58
     var temp= this;
59
     axios.post("https://mywebsite.com/login", data,                 {headers:headers}).then(function (result) {
60
     if (result && result.data) {
61
     const AUTH_TOKEN = result.data.token;
62
     const AUTH_USER = result.data.username;
63
     _storeUser(AUTH_USER);
64
     _storeToken(AUTH_TOKEN); 
65
     if (AUTH_TOKEN){
66
        temp.props.navigation.navigate("HOME");
67
     }
68
    else {temp.setState({ incorrect: true });}}})
69
    .catch(function (error) {
70
    temp.setState({ incorrect: true });
71
    console.log(error);});
72
};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>
73
);}}const styles = {
74
    container: {
75
       flex: 1, 
76
       backgroundColor: "white",
77
       justifyContent: "flex-start",
78
       alignItems: "center",
79
       padding: 10}
80
}



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.

mobile app authentication React Native

Opinions expressed by DZone contributors are their own.

Related

  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • In-App Browsers in Mobile Apps: Benefits, Challenges, Solutions
  • Development of a Truck Tracker and Delivery Services Software
  • Building a Receipt Scanner App With OCR, OpenAI, and PostgreSQL

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!