小程序端的jwt-decode

1,708 阅读1分钟

简介

小程序端由于没有window和global变量,所以使用npm上面的jwt-decode会出问题。下面是一个利用jwt-decode的核心代码封装的一个小程序端的jwt-decode。

使用

创建文件

创建一个名为mini-jwt-decode.js的文件


var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';

function InvalidCharacterError(message) {
    this.message = message;
}

InvalidCharacterError.prototype = new Error();
InvalidCharacterError.prototype.name = 'InvalidCharacterError';

function atob (input) {
    input = input.replace(/-/g, "+").replace(/_/g, "/");
    switch (input.length % 4) {
    case 0:
        break;
    case 2:
        output += "==";
        break;
    case 3:
        output += "=";
        break;
    default:
        throw "Illegal base64url string!";
    }
    var str = String(input).replace(/=+$/, '');
    if (str.length % 4 == 1) {
        throw new InvalidCharacterError("'atob' failed: The string to be decoded is not correctly encoded.");
    }
    for (
    // initialize result and counters
        var bc = 0, bs, buffer, idx = 0, output = '';
    // get next character
        buffer = str.charAt(idx++);
    // character found in table? initialize bit storage and add its ascii value;
        ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
        // and if not first of each 4 characters,
        // convert the first 8 bits to one ascii character
        bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
    ) {
    // try to find character in table (0-63, not found => -1)
        buffer = chars.indexOf(buffer);
    }
    return output;
}

function b64DecodeUnicode(str) {
    return decodeURIComponent(atob(str).replace(/(.)/g, function (m, p) {
        var code = p.charCodeAt(0).toString(16).toUpperCase();
        if (code.length < 2) {
            code = '0' + code;
        }
        return '%' + code;
    }));
}

export default function (token,options) {
    if (typeof token !== 'string') {
        throw new InvalidCharacterError('Invalid token specified');
    }

    options = options || {};
    var pos = options.header === true ? 0 : 1;
    try {
        return JSON.parse(b64DecodeUnicode(token.split('.')[pos]));
    } catch (e) {
        throw new InvalidCharacterError('Invalid token specified: ' + e.message);
    }
}

引入文件

import jwtDecode from './mini-jwt-decode';

使用

const decodeData = jwtDecode(jwt);