class="nav-up">

Store sensitive data using KeyChain

16

Apr. 21

3.02 K

VIEWS

There is always some sensitive data that our App holds for instance, Passwords, Touch Id, Certificates, Tokens or Biometric information. In general, React Native does not come bundled with any way of storing sensitive data. However, there are pre-existing solutions for Android and iOS platforms.

In Native platform like Android/iOS they provide something like this:

[ Android ] – Secure Shared Preferences:

Shared Preferences is the Android equivalent for a persistent key-value data store. Data in Shared Preferences is not encrypted by default, but Encrypted Shared Preferences wraps the Shared Preferences class for Android, and automatically encrypts keys and values.

[ iOS ] – Keychain Services:

Keychain Services allows you to securely store small chunks of sensitive info for the user. This is an ideal place to store certificates, tokens, passwords, and any other sensitive information that doesn’t belong in Async Storage.

In order to use iOS Keychain services or Android Secure Shared Preferences, you can either write a bridge yourself or use a library that wraps them for you and provides a unified API at your own risk. There is a library to consider:

=>  react-native-keychain 

Lets see how we can implement this feature in our React native app:


Installation:

Installation is quite simple with the react-native-keychain library.

Run the following command in your terminal:

yarn add react-native-keychain


OR

npm i react-native-keychain
Make sure to link your library:

react-native link react-native-keychain 

If you are developing iOS, Run pod install in ios/ directory to install iOS dependencies. Finally, rebuild the application.

To check whether it’s successfully linked or not you can go through the  MainApplication.java.

Now run the app using react-native run-android or react-native run-ios depending on your target device. All set for the coding 🙂 .

Using the library in practice for the login feature of our App:

In this example we will store, retrieve, and use credentials for re-login to an app.

Step 01 — Save credentials on first time login.

We can use the setGenericPassword function to store user credentials (username and password) in the Keychain. (Note: By default, strings can be stored using their function. When storing objects, it is recommended to use JSON.stringify).

 

import * as Keychain from 'react-native-keychain';

const LoginPage = props => {

  

  const username = LetsNurture;

  const password = 'LNs@1234';

  

  await Keychain.setGenericPassword(username, password);

}

Step 02 — Retrieve Credentials

Use the function getGenericPassword to get the saved user credentials from the Keychain. (Note: By default, the function returns String. So when retrieving objects, it is recommended to use JSON.parse).

import * as Keychain from 'react-native-keychain';

const LoginPage = props => {

  const checkUserStatus = async () => {

    try {

      const credentials = await Keychain.getGenericPassword();

      }

    } catch (error) {

      console.log('Keychain couldn\'t be accessed!', error);

    }

  }

 }

Step 03 — Using in a real-world

In the following code snippet, the first checkUserStatus() function will be called within the use effect hook during the component mount and set user credentials by retrieving them by the Keystore.

Then login() the function will be invoked to log in to the user using obtained credentials.

import React, { useState } from 'react';

import * as Keychain from 'react-native-keychain';

const LoginScreen = props => {

  const [email, setEmail] = useState('');

  const [password, setPassword] = useState('');

  const [preLogTest, setPreLogTest] = useState(false);

  useEffect(() => {

    checkUserStatus();

  }, []);

  useEffect(() => {

    if (preLogTest) {

      login();

    }

  }, [password, email])

  const checkUserStatus = async () => {

    try {

      const credentials = await Keychain.getGenericPassword();

      if (credentials) {

        setPreLogTest(true);

        setEmail(credentials.username);

        setPassword(credentials.password);

      } else {

      setLoading(false);

      }

    } catch (error) {

      console.log('Keychain couldn\'t be accessed!', error);

      setLoading(false);

    }

  }

  const login = async () => {

    try {

      const response = await fetch('yoururl' + 'signin', {

        method: 'POST',

        headers: {

          Accept: 'application/json',

          'Content-Type': 'application/json',

        },

        body: JSON.stringify({

          email,

          password,

        }),

      });

      const responseJson = await response.json();

      var message = responseJson.msg;

      if (responseJson.success === true) {

          await Keychain.setGenericPassword(email, password);

        }

      }

    } catch (error) {

      console.error(error);

    }

  };

 }

Step 04 — Remove credentials

The function resetGenericPassword can remove all Keychain credentials in a scenario where users are logging out from the app.

import * as Keychain from 'react-native-keychain';

const LoginScreen = props => {

  const removeCredentials = async () => {

    try {

      const credentials = await Keychain.resetGenericPassword();

      }

    } catch (error) {

      console.log('Keychain couldn\'t be accessed!', error);

    }

  }

 }

Conclusion

I believe using a react-native-keychain is the best option to store Sensitive data in React-Native mobile apps. As I can see, the main advantage is the usage of the existing iOS Keychain and Android shared preferences under the hood. I hope you find this insightful. Happy coding!  🙂

If you want to share your own ideas regarding “Store sensitive data using KeyChain”, you can directly contact our expert team of android / iOS / react-native developers.

Author

Lets Nurture
Posted by Lets Nurture

Blog A directory of wonderful things

6 Business Models That Online Marketplaces Use to Earn Money

As the ongoing pandemic continues to push consumers to shop online and get delivery directly to their homes in a bid to stay safe from the spread of Covid-19, online …

How to Tackle & Manage SKUs as an Ecommerce Business in 2021

If you are just starting to build up your eCommerce business, you may have started thinking about the size of your inventory but not necessarily, how you are going to …

How to setup Contact form 7 plugin In WordPress

Contact Form 7 is the most popular and oldest WordPress contact form plugin. It is easy to integrate and equally easy to deploy. For setup contact form 7 follow the …

Setting up a multi-platform SwiftUI project

What is SwiftUI? Before SwiftUI, we were designing iOS applications User Interface into storyboards. Storyboards are an imperative user interface. From June 2020, Apple released SwiftUI for design applications in …

Steps to Create Apple Enterprise Developer Account

The Apple Developer Enterprise Program allows large organizations to develop and deploy proprietary, internal-use apps to their employees. This program is for specific use cases that require private distribution directly …

React Native: First Demo

Let us start to build our first React Native application on Windows as a development operating system and Android as a target operating system. If you are looking to set …

AdMob Mediation in Android

We all know about Admob Ads very well. Here, I would like to explain what mediation features and how it will be useful for developers. Let’s take a simple one …

Laundry On-Demand services: A Successful App Service You Should Consider

With our hectic lifestyles and the need to physically distance due to the ongoing pandemic, on-demand app services are rising in popularity. One such category for this niche is on-demand …

How to Setup Twilio Package for SMS in Laravel

In your application workflow, you may need to pass important information to your users. Most services require your users to have an internet connection and unfortunately, this isn’t always the …

Firebase Dynamic Links

Deep links are a powerful and essential part of a market’s toolkit. They are connecting users to campaigns, streamlining user experience and exposing users to the right marking. Many developers …

Kotlin Coroutines in Android

Multithreading is a well known programming concept which all developers might have come across. The concept of multithreading is a vast subject and includes complex mechanisms in it, but in …

Google in app purchase in android app

Before we start with app purchase, Let’s get a basic idea of what type of digital content we are selling to users. Google’s Billing system gives us mainly two types …

COVID lockdown has brought the digital future forward

The Novel Coronavirus epidemic that has spread its tentacles worldwide almost brought business and the economy to its knees. With no way of attending office, how are employees supposed to …

The Impact of COVID 19 on Restaurant & Hospitality Industry

Coronavirus has literally crippled the economies of different countries catastrophically and has forced many industries to put down their shutters for long. Some have closed down temporarily abiding by the …

AI for Pneumonia Detection

The risk of pneumonia is enormous for many, especially in the nations where billions face energy poverty and rely on polluting forms of energy. “The WHO estimates that over 4 …

How Outsourcing & Subcontracting help companies with Disaster Management

According to recent google reports, 114 countries have reported that 1,18,000 have contracted Covid-19, the disease caused by the virus, known as SARS-CoV2. Nearly 4,300 people have died. Introduction Where …

10 most extensively used Python libraries

Python, being one of the most sought after programming languages, has a huge collection of libraries. In fact, this expansive set of libraries can be considered as one of the …

AI for Food Detection

“Four simple ways to fight diabetes/Obesity: Go for regular medical check-ups; Exercise more; Watch your diet, and Cut down on soft drinks.” – Singapore PM Lee Hsien Loong (Nvidia Research …

Django vs Laravel vs Node js

Web Frameworks are basically software packages that ease the complexity of web development. They come with many inbuilt features that are common in web development, thus minimizing the development time, …

8 Chatbot Development Frameworks: Building a Better Bot for Your Business

There has been an explosion in the use of chatbots across both business websites and messaging applications, mainly because businesses want to cater to their customers and customers have a …

We use cookies to give you tailored experiences on our website.
Okay