Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save MuhammadSawalhy/d6e4ba473c59e166d8e8c84ffac89ae7 to your computer and use it in GitHub Desktop.

Select an option

Save MuhammadSawalhy/d6e4ba473c59e166d8e8c84ffac89ae7 to your computer and use it in GitHub Desktop.

Revisions

  1. MuhammadSawalhy revised this gist May 3, 2024. No changes.
  2. MuhammadSawalhy revised this gist Feb 24, 2022. 1 changed file with 62 additions and 64 deletions.
    126 changes: 62 additions & 64 deletions postman-pre-request-refresh-acces-token.js
    Original file line number Diff line number Diff line change
    @@ -1,73 +1,70 @@
    const backendURL = pm.collectionVariables.get("back_url");
    const tokens = getTokens(); // from the collection variables
    setAccessToken(); // to the collection variables
    updateAccessIfNeeded(); // and set to the collection variables

    // --------------------------------------------------
    // check and (create or refresh)
    // --------------------------------------------------

    function setAccessToken() {
    checkRefreshToken();
    updateAccessIfNeeded();
    }

    function checkRefreshToken() {
    const decodedToken = tokens.decoded.refresh;
    if (isTokenExpired(decodedToken)) {
    throw new Error("refresh token has expired");
    }
    function updateAccessIfNeeded() {
    if (!isTokenExpired(tokens.decoded.access)) return;
    if (!isTokenExpired(tokens.decoded.refresh)) refresh();
    else login();
    }

    function updateAccessIfNeeded() {
    const decodedAccess = tokens.decoded.access;
    const backendURL = pm.collectionVariables.get("back_url");
    if (decodedAccess && isTokenExpired(decodedAccess)) {
    console.log("refreshing the access token from:", backendURL);
    pm.sendRequest(
    {
    url: `${backendURL}/auth/jwt/refresh`,
    method: "POST",
    header: { "Content-Type": "application/json" },
    body: {
    mode: "raw",
    raw: JSON.stringify({ refresh: tokens.refresh }),
    },
    function refresh() {
    console.log("refreshing the access token from:", backendURL);
    pm.sendRequest(
    {
    url: `${backendURL}/auth/jwt/refresh`,
    method: "POST",
    header: { "Content-Type": "application/json" },
    body: {
    mode: "raw",
    raw: JSON.stringify({ refresh: tokens.refresh }),
    },
    function (err, response) {
    if (err) throw err;
    const data = response.json();
    pm.collectionVariables.set("refresh_token", data.refresh);
    pm.collectionVariables.set("access_token", data.access);
    console.log("access token is refreshed, alhamdulillah ❤");
    },
    function (err, response) {
    if (err) {
    login();
    return;
    }
    );
    } else if (!decodedAccess) {
    console.log("fetching the authentication tokens from:", backendURL);
    pm.sendRequest(
    {
    url: `${backendURL}/auth/jwt/create`,
    method: "POST",
    header: { "Content-Type": "application/json" },
    body: {
    mode: "raw",
    raw: JSON.stringify({
    email: pm.collectionVariables.get("user_email"),
    password: pm.collectionVariables.get("user_password"),
    }),
    },

    const data = response.json();
    pm.collectionVariables.set("refresh_token", data.refresh);
    pm.collectionVariables.set("access_token", data.access);
    console.log("access token is refreshed, alhamdulillah ❤");
    }
    );
    }

    function login() {
    console.log("loging into:", backendURL);
    pm.sendRequest(
    {
    url: `${backendURL}/auth/jwt/create`,
    method: "POST",
    header: { "Content-Type": "application/json" },
    body: {
    mode: "raw",
    raw: JSON.stringify({
    email: pm.collectionVariables.get("user_email"),
    password: pm.collectionVariables.get("user_password"),
    }),
    },
    function (err, response) {
    if (err) throw err;
    const data = response.json();
    pm.collectionVariables.set("refresh_token", data.refresh);
    pm.collectionVariables.set("access_token", data.access);
    console.log("authentication tokens are fetched, alhamdulillah ❤");
    }
    );
    }
    },
    function (err, response) {
    if (err) throw err;
    const data = response.json();
    pm.collectionVariables.set("refresh_token", data.refresh);
    pm.collectionVariables.set("access_token", data.access);
    console.log("loged in successfully, alhamdulillah ❤");
    }
    );
    }

    function isTokenExpired(decodedToken) {
    return decodedToken.exp * 1000 - new Date() <= 0;
    return !decodedToken || decodedToken.exp * 1000 - new Date() <= 0;
    }

    // --------------------------------------------------
    @@ -79,18 +76,19 @@ function getTokens() {
    const tokens = {
    refresh: pm.collectionVariables.get("refresh_token"),
    access: pm.collectionVariables.get("access_token"),
    decoded: {}
    };

    if (!tokens.refresh) {
    if (!tokens.refresh)
    throw new Error("You have to set refresh token global variable");
    }

    Object.assign(tokens, {
    decoded: {
    refresh: jwtDecode(tokens.refresh),
    access: tokens.access && jwtDecode(tokens.access),
    },
    });
    try {
    tokens.decoded.refresh = tokens.refresh && jwtDecode(tokens.refresh);
    } catch {}

    try {
    tokens.decoded.access = tokens.access && jwtDecode(tokens.access);
    } catch {}

    return tokens;
    }
  3. MuhammadSawalhy revised this gist Feb 24, 2022. No changes.
  4. MuhammadSawalhy revised this gist Feb 24, 2022. No changes.
  5. MuhammadSawalhy revised this gist Feb 24, 2022. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions postman-pre-request-refresh-acces-token.js
    Original file line number Diff line number Diff line change
    @@ -37,7 +37,7 @@ function updateAccessIfNeeded() {
    const data = response.json();
    pm.collectionVariables.set("refresh_token", data.refresh);
    pm.collectionVariables.set("access_token", data.access);
    console.log("access token is refreshed, alhadulilah ❤");
    console.log("access token is refreshed, alhamdulillah ❤");
    }
    );
    } else if (!decodedAccess) {
    @@ -60,7 +60,7 @@ function updateAccessIfNeeded() {
    const data = response.json();
    pm.collectionVariables.set("refresh_token", data.refresh);
    pm.collectionVariables.set("access_token", data.access);
    console.log("authentication tokens are fetched, alhadulilah ❤");
    console.log("authentication tokens are fetched, alhamdulillah ❤");
    }
    );
    }
  6. MuhammadSawalhy revised this gist Feb 24, 2022. 1 changed file with 4 additions and 4 deletions.
    8 changes: 4 additions & 4 deletions postman-pre-request-refresh-acces-token.js
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,5 @@
    const tokens = getTokens();
    setAccessToken(); // to collection variables
    const tokens = getTokens(); // from the collection variables
    setAccessToken(); // to the collection variables

    // --------------------------------------------------
    // check and (create or refresh)
    @@ -37,11 +37,11 @@ function updateAccessIfNeeded() {
    const data = response.json();
    pm.collectionVariables.set("refresh_token", data.refresh);
    pm.collectionVariables.set("access_token", data.access);
    console.log("access token is refreshed");
    console.log("access token is refreshed, alhadulilah ❤");
    }
    );
    } else if (!decodedAccess) {
    console.log("creating the authentication tokens from:", backendURL);
    console.log("fetching the authentication tokens from:", backendURL);
    pm.sendRequest(
    {
    url: `${backendURL}/auth/jwt/create`,
  7. MuhammadSawalhy created this gist Feb 24, 2022.
    136 changes: 136 additions & 0 deletions postman-pre-request-refresh-acces-token.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,136 @@
    const tokens = getTokens();
    setAccessToken(); // to collection variables

    // --------------------------------------------------
    // check and (create or refresh)
    // --------------------------------------------------

    function setAccessToken() {
    checkRefreshToken();
    updateAccessIfNeeded();
    }

    function checkRefreshToken() {
    const decodedToken = tokens.decoded.refresh;
    if (isTokenExpired(decodedToken)) {
    throw new Error("refresh token has expired");
    }
    }

    function updateAccessIfNeeded() {
    const decodedAccess = tokens.decoded.access;
    const backendURL = pm.collectionVariables.get("back_url");
    if (decodedAccess && isTokenExpired(decodedAccess)) {
    console.log("refreshing the access token from:", backendURL);
    pm.sendRequest(
    {
    url: `${backendURL}/auth/jwt/refresh`,
    method: "POST",
    header: { "Content-Type": "application/json" },
    body: {
    mode: "raw",
    raw: JSON.stringify({ refresh: tokens.refresh }),
    },
    },
    function (err, response) {
    if (err) throw err;
    const data = response.json();
    pm.collectionVariables.set("refresh_token", data.refresh);
    pm.collectionVariables.set("access_token", data.access);
    console.log("access token is refreshed");
    }
    );
    } else if (!decodedAccess) {
    console.log("creating the authentication tokens from:", backendURL);
    pm.sendRequest(
    {
    url: `${backendURL}/auth/jwt/create`,
    method: "POST",
    header: { "Content-Type": "application/json" },
    body: {
    mode: "raw",
    raw: JSON.stringify({
    email: pm.collectionVariables.get("user_email"),
    password: pm.collectionVariables.get("user_password"),
    }),
    },
    },
    function (err, response) {
    if (err) throw err;
    const data = response.json();
    pm.collectionVariables.set("refresh_token", data.refresh);
    pm.collectionVariables.set("access_token", data.access);
    console.log("authentication tokens are fetched, alhadulilah ❤");
    }
    );
    }
    }

    function isTokenExpired(decodedToken) {
    return decodedToken.exp * 1000 - new Date() <= 0;
    }

    // --------------------------------------------------
    // get the tokens and decode
    // --------------------------------------------------
    // source: https://github.com/auth0/jwt-decode/

    function getTokens() {
    const tokens = {
    refresh: pm.collectionVariables.get("refresh_token"),
    access: pm.collectionVariables.get("access_token"),
    };

    if (!tokens.refresh) {
    throw new Error("You have to set refresh token global variable");
    }

    Object.assign(tokens, {
    decoded: {
    refresh: jwtDecode(tokens.refresh),
    access: tokens.access && jwtDecode(tokens.access),
    },
    });

    return tokens;
    }

    function jwtDecode(token, options) {
    options = options || {};
    var pos = options.header === true ? 0 : 1;
    return JSON.parse(base64_url_decode(token.split(".")[pos]));
    }

    function base64_url_decode(str) {
    var output = str.replace(/-/g, "+").replace(/_/g, "/");
    switch (output.length % 4) {
    case 0:
    break;
    case 2:
    output += "==";
    break;
    case 3:
    output += "=";
    break;
    default:
    throw "Illegal base64url string!";
    }

    try {
    return b64DecodeUnicode(output);
    } catch (err) {
    return atob(output);
    }
    }

    function b64DecodeUnicode(str) {
    return decodeURIComponent(
    atob(str).replace(/(.)/g, function (m, p) {
    var code = p.charCodeAt(0).toString(16).toUpperCase();
    if (code.length < 2) {
    code = "0" + code;
    }
    return "%" + code;
    })
    );
    }