The Tao of Managing JWT Tokens

The Tao of Managing JWT Tokens


Posted 11 September 2017
Over recent years, single page websites and web applications have become more and more popular. Thanks to the rise of popular frontend frameworks such as VueJS and Angular, it’s getting easier to build single page applications. Here we discuss how you handle user authentication within a single page application.

Over recent years, single page websites and web applications have become more and more popular. Thanks to the rise of popular frontend frameworks such as VueJS and Angular, it’s getting easier to build single page applications. What could be considered a trade off (but is also a benefit) of single page applications is the fact the application becomes stateless. This means that data (such as the current authenticated users details) are not stored in the session, because there is no session. Instead, you have a frontend client which makes API requests to your backend server. This is especially great if you plan on building a mobile application for example. This is because all you have to do is build the front end for the app and just integrate it with the API you have already built; saving heaps of time!

Because single page applications are stateless, authentication becomes slightly trickier… we can no longer grab a token from the session to find the current authenticated user. Say hello to JSON Web Tokens (JWT)! A JWT Token is made up of three key parts, the header, the payload and the signature. If you want to learn more about JWT Tokens, checkout out jwt.io!

The general idea is that you make a request to authenticate the user and you receive a token back which will need to be stored somewhere such as in a Cookie or in Local Storage. You can then use this token to make authenticated requests to your API. You can configure how long the tokens last before expiring, but generally they last around 60 minutes - afterwhich you need to refresh. However, it might be a good idea to refresh the token when it is close to expiring so if your application attempts to make an API request, it doesn’t fail and confuse the user.

As you can tell, there is quite a lot here. We need to be able to store the token somewhere, retrieve it whenever we want to make requests, know when the token is going to expire soon so we can refresh it. I also found this quite a lot to deal with, so I created a package to make it as simple as possible, welcome JWT Manager… (I know I’m not the best at naming packages).

JWT Manager

Installation

You can install the package by running the following command: npm install --save jwt-manager or yarn add jwt-manager. Once you have installed the package you need to import the library.

import JWTManager from 'jwt-manager';

window.JWTManager = new JWTManager();

Storing The Token

The first thing you are going to need to do is store the JWT Token you have received from your server. By default the package will store the token in a cookie, but you can change this to local storage by running the following command:

window.JWTManager.useLocalStorage();

You can then set a token using the following method:

window.JWTManager.setToken('jwt-token');

Retrieving The Token

Once you have stored the token, you are generally going to need it to make requests to your API. You can retrieve the token from the store easily by calling the getToken() method. Here is an example:

window.JWTManager.getToken();

You can then add this to the Authorization header on the request, or append it to the url as a get parameter - it just depends on how you’ve setup your API.

Refreshing The Token

A JWT token will only last for a certain amount of time, after which it will need to be refreshed. As I mentioned earlier, it is generally a good rule of thumb to refresh the token in the background before it is due to expire, that way it prevents the issue of making an API call while the token is invalid. To solve this you can call the monitor method:

window.JWTManager.monitor((token) => {
// Make request to refresh token here
// Then call the JWTManager.refresh() method and pass in your new token
});

In the background this will monitor the JWT Token and run the callback when the token is due to expire within the next 60 seconds. In the callback you would then make a request to refresh the token from your API. You can then call the window.JWTManager.refresh(‘new-jwt-token’) method to update the current stored JWT Token.

There are many other methods available with the JWTManager package, feel free to check out the GitHub repository for more information on each available method.