提问者:小点点

如何在javascript中解码jwt令牌而不使用库?


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

示例令牌:xxxxxxxxxx.xxxxxxxxx

结果是有效载荷:

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

共3个答案

匿名用户

工作的unicode文本JWT解析器函数:

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);
};

匿名用户

带有try-catch的简单函数

const parseJwt = (token) => {
  try {
    return JSON.parse(atob(token.split('.')[1]));
  } catch (e) {
    return null;
  }
};

谢啦!

匿名用户

您可以使用jwt-decode,因此可以编写:

import jwt_decode from 'jwt-decode';

var token = 'eyJ0eXAiO.../// jwt token';

var decoded = jwt_decode(token);
console.log(decoded);
/*{exp: 10012016 name: john doe, scope:['admin']}*/