More on JWT (for React Native)

Using JWT on a React Native project is slightly different from a web project, but offers the same benefits plus some.

Stateless, easy to scale: Server does not need to store user sessions, as JWT contains the authorization of the user, including the expiry date.

Reusability: We can have multiple servers on different platforms and domains, reusing the same token.

Performance: No lookup cost.

Sidestep mobile cookies: Most mobile web browsers accept first party-cookies, but different mobile browsers behave differently when it comes to accepting third-party cookies.

Screen Shot 2016-05-15 at 1.46.31 PM

On the backend, I have already set up my routes, and I will need to link it up with my react native app:

  1. A method for _register, which will POST request to the endpoint /users, providing a username and a password. If the user doesn’t already exist, it will be created, and a JWT will be returned for the current session.
  2. We will also need a method for _login, which will POST request to /sessions/create with a username and password. This uses bcrypt compare to compare the hashed password with the stored hashed in the server. If successful, this will return a JWT for the session.
  3. Lastly, we’ll need a method for protected content, eg: _getProtectedContent, which will GET request the endpoint, including the session’s stored JWT. The response serves up the content, if successful.

 

In the _register method, after getting the response, we will need to store the token securely.

In Expo, this can be done easily by importing

import {SecureStore} from 'expo';

and then storing it in SecureStore (which encrypts the token) and navigating to the app:

await SecureStore.setItemAsync("Bearer", responseJson.token);

this.props.navigation.navigate("App");

To get the token before login subsequently:

const userToken = await SecureStore.getItemAsync("Bearer");
To send token to protected route:
async _getProtectedContent() {
    var TOKEN = await SecureStore.getItem("Bearer");
    fetch("http://localhost:3001/api/protected/content", {
        method: "GET",
        headers: {
            'Authorization': 'Bearer ' + TOKEN
        }
    })
    .then((response) => //do something with the response)
    .done();
},

Resources:
https://logrocket.com/blog/jwt-authentication-best-practices/
https://gellerj496howto.wordpress.com/
https://stackoverflow.com/questions/50404239/how-to-store-tokens-in-react-native

Leave a comment

Design a site like this with WordPress.com
Get started