Biometric Authentication in React Native App with AsyncStorage
August 09, 2021
Biometric Authentication in React Native App with AsyncStorage
React-native-biometrics (https://www.npmjs.com/package/react-native-biometrics)
AsyncStorage (https://react-native-async-storage.github.io/async-storage/)
React native biometrics is a simple bridge to native iOS and Android keystore management. It allows you to create public private key pairs that are stored in native keystores and protected by biometric authentication. Those keys can then be retrieved later, after proper authentication, and used to create a cryptographic signature.
Just follow the docs of React-native-biometrics and AsyncStorage for installation and permission and you can also use redux presist
Step 1 First Check the biomatric is enable or not at the start of your app .
Case 1 : If user login status is ok and biomatric is also enable and you just want to confirm the identity then have to reditect the user into login screen then popup of biomatric will be shown on login page
For Example App.js
let BiomatircEnable = await AsyncStorage.getItem("PopUPEnable");
let isLogged; //here is user login or not status
if(BiomatircEnable){
BiomatircEnable=JSON.parse(BiomatircEnable);
}
console.info(BiomatircEnable);
if(BiomatircEnable===true&&isLogged){
//GO TO LOGIN PAGE TO SHOW BIOMATRIC POPUP
}else{
if(isLogged){
//REDIRECT TO HOME PAGE DIRECT BECAUSE USE ALREADY CANCEL THE
// BIOMATRIC FEATURE OR DEVICE IS NOT SUPPORTED
}else{
//GO TO LOGIN PAGE FOR NORMAL LOGIN
}
}
//USER WILL REDIRECT ACCORDING TO SCREENS ON THE BASIS OF
//LOGIN AND BIOMARIC STATUS
Step 2 Login.js
const CallBio=async()=>{
let isLogged; //here is user login or not status
let BiomatircEnable = await AsyncStorage.getItem("PopUPEnable");
if(BiomatircEnable){
BiomatircEnable=JSON.parse(BiomatircEnable);
}
console.info(BiomatircEnable)
if(isLogged&&BiomatircEnable===true){
let sign= await CallAuthBiomatirc();
console.info(sign)
if(sign===true){
//REDIRECT TO HOME PAGE AFTER VERIFICATION OF BIOMATRIC
// CallAuthBiomatirc() is services that is create for
// handle the verficaiton
}
}
}
useEffect(() => {
CallBio();
}, [])
Step 3 src/services/auth/Biomatric/index.js
import { BackHandler} from 'react-native'
import ReactNativeBiometrics from 'react-native-biometrics'
const CallCheckBiomatric=async()=>{
const { available } = await ReactNativeBiometrics.isSensorAvailable();
return available;
}
const CallAuthBiomatirc=async()=>{
try {
const { success } = await ReactNativeBiometrics.simplePrompt({promptMessage: 'Authentication required'})
if (success) {
return true;
} else {
return false;
}
} catch (error) {
console.log('biometrics failed',error)
return false;
}
}
const CreateBioAuthKey=async()=>{
try {
console.info('enter for Sign')
let epochTimeSeconds = Math.round((new Date()).getTime() / 1000).toString()
let payload = epochTimeSeconds + 'some message';
const {success, signature}=await ReactNativeBiometrics.createSignature({
promptMessage: 'Authentication required',
payload: payload
})
if(success){
return signature;
}else{
return null;
}
} catch (error) {
console.log('biometrics failed',error)
}
}
export {
CallCheckBiomatric,
CreateBioAuthKey,
CallAuthBiomatirc
};
Step 4 For enable the biomatric featrue you can add a popup on the home screen with two options that are canceled or enable
ModalBiomatripopup.js
import React from 'react'
import { View, Text,Modal,TouchableOpacity } from 'react-native'
const BiomatricModal = ({open,CallBack}) => {
return (
<Modal
animationType="slide"
transparent={true}
visible={open}
>
<View style={{flex:1,alignItems:'center',justifyContent:'center',backgroundColor: 'rgba(0,0,0,0.5)'}}>
<View style={{flexDirection:'column',backgroundColor:'white',margin:20,padding:20,alignItems: "center"
,borderRadius:20}}>
<Text style={{padding:25,fontSize:16,textAlign:'center'}}>Do you want to allow Fusion App to use biometrci authentication ?</Text>
<TouchableOpacity
style={{padding:10}}
onPress={()=>CallBack(true)}
>
<Text style={{fontWeight:'bold',fontSize:16}}>Enable</Text>
</TouchableOpacity>
<TouchableOpacity
style={{padding:10}}
onPress={()=>CallBack(false)}
>
<Text style={{fontWeight:'bold',fontSize:16}}>Skip</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
)
}
export default BiomatricModal;
Steps 5 Home.js
import BiomatricModal from "@components/common/BiomatricModal";
import React, {useState, useEffect} from "react";
const Home = () => {
const [BioMatricModal, setBioMatricModal] = useState(false)
const OpneModal=async()=>{
let Biomatciaviable=await CallCheckBiomatric();
if(Biomatciaviable){
let PopUPEnable = await AsyncStorage.getItem("PopUPEnable");
if(PopUPEnable){
PopUPEnable=JSON.parse(PopUPEnable);
}
console.info(PopUPEnable)
if(PopUPEnable===null){
setBioMatricModal(true)
}
}
}
const CallBack=async(data)=>{
console.info(data)
setBioMatricModal(false)
if(data===true){
let sign= await CallAuthBiomatirc();
if(sign===true){
await AsyncStorage.setItem("PopUPEnable", JSON.stringify(sign));
}
}
if(data===false){
await AsyncStorage.setItem("PopUPEnable", JSON.stringify(data));
}
}
useEffect(() => {
(async () => await OpneModal());
}, []);
}