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?
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?
Share Improve this question edited Feb 20, 2023 at 5:28 Carson 8,2462 gold badges57 silver badges58 bronze badges asked Sep 20, 2020 at 2:30 Jack ColeJack Cole 1,8042 gold badges25 silver badges45 bronze badges 1- 1 Does this answer your question? Obtain an id token in the Gmail add-on for a backend service authentication – user555121 Commented Sep 20, 2020 at 9:46
1 Answer
Reset to default 8I found out how to decode a JWT from https://developers.google./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);
};