Blog - JWT.png

Introduction

What is JWT?

A JSON Web Token (JWT) is a secure way to exchange information between two or more parties using JSON format, often used for authentication.

To put it simply, when a user logs in to an application using his username and password, the server returns a JWT, and the user can hold on to the token. The next time the user wants to access something from the server, the token will be included in the header of his request, so that the server can know that they’re already a logged-in user.

JWT in React Native

The concept of authorization in a React Native application is simple. Once a user logs in using their username and password, the credentials are sent to the server in an HTTP request, and the server then returns a JWT.

As the user interacts with an application, a token is attached in the header of each request so the server knows this is a logged-in user without the user-provided credentials each time until the JWT expires.

This article will guide you through how our team at FABA implements JWT in React Native.

How to implement JWT authorization in React Native

The diagram shows the flow of how we implement JWT with the client (React Native)

JWT has 2 main concepts:

And they both have time to live (TTL) to determine the valid time of each token.

Plus, a legal JWT must be added to HTTP Header to protect our resources. When accessToken is used after its TTL, we will receive a 401 status code from the server, so we need to call refresh API to get new pair of accessToken and refreshToken. Here’s a diagram of the flow.

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/a393ad43-ba46-439a-b4ca-e22ceaadb712/JWT.png

The simple flow is:

if the response has the 401 status code, we will call API ‘/refresh-token’ to get new metadata. It will work if we don’t have more than one request that needs to verify header with the bearer token