如何使用JavaScript解码JWT的有效负载?没有图书馆。令牌只返回一个有效负载对象,前端应用可以使用它。

示例令牌:xxxxxxxxx.XXXXXXXX.xxxxxxxx

结果就是有效载荷:

{exp: 10012016 name: john doe, scope:['admin']}

当前回答

@Peheje将工作,但你将有问题的unicode。 为了解决这个问题,我使用https://stackoverflow.com/a/30106551/5277071上的代码;

let b64DecodeUnicode = str => decodeURIComponent( Array.prototype.map.call(atob(str), c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2) ).join('')) let parseJwt = token => JSON.parse( b64DecodeUnicode( token.split('.')[1].replace('-', '+').replace('_', '/') ) ) let form = document.getElementById("form") form.addEventListener("submit", (e) => { form.out.value = JSON.stringify( parseJwt(form.jwt.value) ) e.preventDefault(); }) textarea{width:300px; height:60px; display:block} <form id="form" action="parse"> <textarea name="jwt">eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkrDtGhuIETDs8OoIiwiYWRtaW4iOnRydWV9.469tBeJmYLERjlKi9u6gylb-2NsjHLC_6kZNdtoOGsA</textarea> <textarea name="out"></textarea> <input type="submit" value="parse" /> </form>

其他回答

我在jwt找到了这个代码。IO,它工作得很好。

//this is used to parse base64
function url_base64_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!';
  }
  var result = window.atob(output); //polifyll https://github.com/davidchambers/Base64.js
  try{
    return decodeURIComponent(escape(result));
  } catch (err) {
    return result;
  }
}

在某些情况下(某些开发平台), 最好的答案(目前)面临一个base64长度无效的问题。 所以,我需要一种更稳定的方法。

我希望这对你有所帮助。

@Peheje将工作,但你将有问题的unicode。 为了解决这个问题,我使用https://stackoverflow.com/a/30106551/5277071上的代码;

let b64DecodeUnicode = str => decodeURIComponent( Array.prototype.map.call(atob(str), c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2) ).join('')) let parseJwt = token => JSON.parse( b64DecodeUnicode( token.split('.')[1].replace('-', '+').replace('_', '/') ) ) let form = document.getElementById("form") form.addEventListener("submit", (e) => { form.out.value = JSON.stringify( parseJwt(form.jwt.value) ) e.preventDefault(); }) textarea{width:300px; height:60px; display:block} <form id="form" action="parse"> <textarea name="jwt">eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkrDtGhuIETDs8OoIiwiYWRtaW4iOnRydWV9.469tBeJmYLERjlKi9u6gylb-2NsjHLC_6kZNdtoOGsA</textarea> <textarea name="out"></textarea> <input type="submit" value="parse" /> </form>

在Node.js (TypeScript)中:

import { TextDecoder } from 'util';

function decode(jwt: string) {
    const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.');

    if (length !== 3) {
        throw new TypeError('Invalid JWT');
    }

    const decode = (input: string): JSON => { return JSON.parse(new TextDecoder().decode(new Uint8Array(Buffer.from(input, 'base64')))); };

    return { header: decode(encodedHeader), payload: decode(encodedPayload), signature: signature };
}

与jose在GitHub上的panva,你可以使用最小的导入{解码为base64Decode}从'jose/util/base64url'和替换新的Uint8Array(Buffer.from(输入,'base64'))与base64Decode(输入)。这样代码就可以在浏览器和Node.js中正常工作。

你可以定义并使用这个函数:

jwtDecode = b => JSON.parse(Buffer.from(b.split('.')[1], 'base64').toString('binary'));

你可以使用纯javascript atob()函数将token解码为字符串:

atob(token.split('.')[1]);

或者直接解析成json对象:

JSON.parse(atob(token.split('.')[1]));

阅读关于atob()和btoa()内置javascript函数Base64编码和解码- Web api | MDN。