DEV Community

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

Posted on • Edited on

2 1

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!!!

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series