最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Decoding JWT in Google Apps Script - Stack Overflow

programmeradmin1浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 8

I 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);
};
发布评论

评论列表(0)

  1. 暂无评论