DEV Community

Cover image for Solving unauthorized tokens for testing
Visakh Vijayan
Visakh Vijayan

Posted on • Updated on

Solving unauthorized tokens for testing

A major part of building an API is testing. We use postman extensively for testing our APIs. The catch is our APIs are protected using JWT tokens. So while testing there is chance that your tokens might expire and you start receiving unauthorized exceptions thereafter.

Sure it is simple for developers we can easily get a token from the database (provided we save it). But what about the QA team or the mobile-app teams. The web team is smart enough to copy the token from the browser network request. Ha ha :D

That is when postman came to our rescue. Postman has something called pre/post request scripts. In simple terms these are functions that run before/after your API request. This felt like something we could use.

  1. We created an API in our project that would take a JWT token and return a new token for that particular user. Kind of like a refresh token logic. We kept it simple however.
  2. We then wrote this piece in our post request script (The Tests tab)
if (pm.response.code == 401 || pm.response.code == 403)
{
    console.log("Token refreshment needed!");

    // expired token from the environment variables
    const token = pm.environment.get('token');

    const baseUrl = pm.environment.get('url');
    const url = baseUrl + '<refresh-url>';

    const options = 
    {
        'method': 'GET',
        'url': url,
        'header': 'Authorization:Bearer ' + token
    };

    pm.sendRequest(options, function (error, response)
    {
        const resp = response.json();
        const newToken = resp["token"];

        pm.environment.set('token', newToken);
    });
}
Enter fullscreen mode Exit fullscreen mode

What the script basically does is. Whenever a token expires, the reponse returns an unauthorized exception. This is caught by pm.response.code section as it will have either 401 or 403 status code usually.

Once we get an unauthorized exception we are simply calling our refresh url to get a new token for this user. With pm.environment.set('token', newToken), we are basically assigning the newly generated token to the token environment variable.

With this, on the first click if a token expires, you can click again and the request will get you a response.

Hope it helps. Let us know your comments.

Happy programming!!!

Top comments (0)