Skip to content

Instantly share code, notes, and snippets.

@ddieppa
Last active August 24, 2022 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ddieppa/b7b3423d57e79237f0fa9be64668e5a2 to your computer and use it in GitHub Desktop.
Save ddieppa/b7b3423d57e79237f0fa9be64668e5a2 to your computer and use it in GitHub Desktop.
Postman auto-refresh auth token
published: true

How to auto-refresh auth token in Postman

This is very common scenario when testing APIs in postman, we have a collection of request and those requests needs to be authenticated first. Most of the time we have to run the auth request first, grab the token from the response and then go request per request and add the token or simple create a variable in Postman and add the token, still saving the token in a variable requires to run the auth request again once the token expires.

Here is a code snippet that can help with that.

📓 Of course there is no code to rule them all, so adjust the code base on your environment variables and data used for authentication.

// Get environment variables
const username = pm.environment.get("username");
const password = pm.environment.get("password")
const enableAutoRefresh = pm.environment.get("enableAutoRefresh");
const tokenUrl = pm.environment.get("tokenUrl");
const baseUrl = pm.environment.get("baseUrl");
const authUrl = baseUrl+tokenUrl;

// Determine if accessTokenExpiry exists in the environment
const expiresAt = pm.environment.get("accessTokenExpiry");
if (!expiresAt) {
  console.log(
    "accessTokenExpiry does not exist, creating a new environment variable and setting it to an old expired date time"
  );
  pm.environment.set("accessTokenExpiry", Number(14400));
}
// Determine if the Access Token has expired
const expired = Date.now() > Number(expiresAt);
// Determine if the user has auto-refresh enabled
if (!enableAutoRefresh) {
  console.log(
    "enableAuoRefresh does not exist, creating a new environment variable and setting it to false"
  );
  pm.environment.set("enableAutoRefresh", false);
}


const autoRefresh = String(enableAutoRefresh) === "true";
// Determine if we have all the client credentials needed in the environment
const hasUsername = String(username).length > 0;
const hasPassword = String(password).length > 0;
const hasAllCredentials = hasUsername && hasPassword;

// Determine if autoRefresh is enabled and only continue if it is.
if (!autoRefresh) {
  console.log("Enable auto refresh is disabled");
}
// If the access token expired and auto refresh has been set, use the refresh
// token to create a new access token
else if (expired && autoRefresh && hasAllCredentials) {
  console.log(
    "All prerequisites are met so getting new access and refresh tokens"
  );
  // Send a new API request to refresh the access token
  pm.sendRequest(
    {
      url: authUrl,
      method: "POST",
      headers: {
        "Content-Type": "Content-Type: application/x-www-form-urlencoded",
      },
      body: {
        mode: "urlencoded",
        urlencoded: [
          {
            key: "username",
            value: username
          },
          { 
              key: 'password',
              value: password,
          },
          { 
              key: "grant_type",
              value: "password"
          }
        ],
      },
    },
    function (error, response) {
      if (error || response.json().error) {
        // If an error occurred, log the error and raise a message to the user.
        console.log("Could not refresh the access token");
        console.log(error);
        console.log(response.json());
        throw new Error(
          "Could not refresh the access token. Check the console for more details."
        );
      } else {
        // Otherwise, fetch the new access token and store it
        const data = response.json();

        // Determine when this token is set to expire at
        const newAccessTokenExpiresAt = Date.now() + data.expires_in * 1000;
        // Store the new variables in the environment
        pm.environment.set("accessToken", data.access_token);
        pm.environment.set("refreshToken", data.refresh_token);
        pm.environment.set("accessTokenExpiry", newAccessTokenExpiresAt);
        console.log("New access and refresh tokens stored successfully");
      }
    }
  );
} else if (expired) {
  // Otherwise, throw a message to the user if the access token expired.
  throw new Error(
    "Refresh token expired. Please generate a new refresh token via the authentications section at the top of the collection and save it into the environment and try again."
  );
}

This code snippet could be placed where fits better for our use case based on the Postman hierarchy of execution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment