5

I am trying to decode a JSON Web Token using this function:

function parseJwt(token) {
    var base64Url = token.split('.')[1];
    var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    var jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));

    return JSON.parse(jsonPayload);
};

This works fine in my Google Chrome console, but when I try to use it in Google Scripts it says "atob is not defined". I looked up what atob does, which is decode a 64-bit encoded string. But when I use base64Decode(String) it produces an array instead of a string. How can I reproduce atob's behavior? Or is there another way to decode a JWT?

Carson
  • 6,105
  • 2
  • 37
  • 45
Jack Cole
  • 1,528
  • 2
  • 19
  • 41
  • 1
    Does this answer your question? [Obtain an id token in the Gmail add-on for a backend service authentication](https://stackoverflow.com/questions/52387866/obtain-an-id-token-in-the-gmail-add-on-for-a-backend-service-authentication) – Kos Sep 20 '20 at 09:46

1 Answers1

6

I found out how to decode a JWT from https://developers.google.com/apps-script/reference/script/script-app#getidentitytoken

function parseJwt(token) {
    let body = token.split('.')[1];
    let decoded = Utilities.newBlob(Utilities.base64Decode(body)).getDataAsString();
    return JSON.parse(decoded);
};
Jack Cole
  • 1,528
  • 2
  • 19
  • 41
  • I tried to use this solution, but I don't have those "Utilities". – Gustavo Jan 28 '22 at 18:22
  • 1
    This is for Google Apps Script. The Utilities are documented [here](https://developers.google.com/apps-script/reference/utilities/utilities). – Jack Cole Jan 28 '22 at 23:01