0
const response = await axios.post(`${config.END_POINT}/users`, formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })

        await Keychain.setGenericPassword('token', response.token)

/* App.js */

useEffect(() => {
        async function getToken() {
            try {
                const token = await Keychain.getGenericPassword()
                dispatch({
                    type: 'auth/setToken',
                    payload: token
                })
            }
            catch (error) {
                console.error(error.message)
            }
        }
        getToken()
    }, [dispatch])

I'm building my first react native app with expressJS and MongoDB and using jwt for authentication.

When I was working on ReactJS project, I used to store token in localstorage. But I don't have any idea about storing in React Native. I did research and found about asyncStorage and react-native-keychain. However, I got to know that asyncStorage is not secure.

So, I used react-native-keychain but it's having and error on both setGenericPassword and getGenericPassword :

Cannot read property 'getGenericPasswordForOptions', 'setGenericPasswordForOptions' of null //Respectively
Yash Sharma
  • 232
  • 2
  • 12

1 Answers1

0

I recommend you to use CryptoJS to encrypt your token. And use MMKV to save it locally, apparently MMKV is 30x faster than AsyncStorage. Code example below:

    import CryptoJS from 'crypto-js';
    import { MMKV } from 'react-native-mmkv';

    const storage = new MMKV();
    const secret = 'FAKE_SECRET';

    const encryptedToken = CryptoJS.AES.encrypt('FAKE_TOKEN', 
    secret).toString();

    storage.set('userToken', encryptedToken);

It's not recommended to store the secretKey like this, maybe it's better to use env vars.

To get and decrypt your token do this:

    const encryptedToken = storage.getString('userToken');
    const decryptedBytes = CryptoJS.AES.decrypt(encryptedToken, 
    secret);
    const userToken = decryptedBytes.toString(CryptoJS.enc.Utf8);
Tchiteu Abloh
  • 424
  • 1
  • 6
  • 15