HowTo: JSON Web Token from iOS and Android with React Native

Adding Features

JWT Token Storage

Code development and description of workflow here is contributed by @Phat_Ca , computer science major, University of Hawaii at Manoa.

Note from @Phat_Ca :

The majority of the implementation and features are currently in App.tsx, which is not best practice for React Native as it’s recommended to break down functionality into separate components. I plan to refactor each feature into its own component for better readability and adherence to best practices. This restructuring will enhance the code organization and maintainability.

JWT Token Storage

To securely manage user sessions, we implemented JWT token storage within the app. This setup allows the app to persist user authentication between sessions by storing tokens on the device, providing a seamless experience while maintaining security. Below are the steps we used to implement this feature:

  1. Code Snippet for Token Storage:

App.tsx:

if (data.access) {
  await AsyncStorage.setItem('accessToken', data.access);
  await AsyncStorage.setItem('refreshToken', data.refresh);
  console.log('Access token saved successfully:', data.access);

  // Navigate to the Home screen
  navigation.navigate('Home');
} else {
  setErrorMessage('No access token found');
}
  1. Access and Refresh Token Management:
  • Upon receiving tokens, the app stores both accessToken and refreshToken in AsyncStorage.
  • Storing tokens locally allows the app to access them quickly when making subsequent requests, avoiding unnecessary reauthentication.
  1. Security Consideration:
  • By using AsyncStorage for token storage, we ensure that sensitive information is retained securely and can be accessed when the app needs to verify user sessions.
  • In addition by storing tokens rather than sensitive credentials (like the username and password) in AsyncStorage, the app reduces security risks. In the event of a malicious attack or unauthorized access, users’ actual credentials remain safe, as only the tokens are stored.