Javascript 解析 JWT 的 payload 部分, 提取自 auth0/jwt-decode.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
let payload_decode = utf8_token => {
    // validation
    if (typeof utf8_token !== 'string') throw 'Invalid token specified'
    let arr = utf8_token.split('.')
    if(arr.length != 3) throw 'Illegal JWT token.'
    let payload = arr[1]

    // decode
    var decoded = payload.replace(/-/g, "+").replace(/_/g, "/")
    switch (decoded.length % 4) {
        case 0:
            break
        case 2:
            decoded += "=="
            break
        case 3:
            decoded += "="
            break
        default:
            throw "Illegal base64url string!"
    }

    // atob
    let result = (input => {
        let str = String(input).replace(/=+$/, '')
        if (str.length % 4 == 1) throw "The string to be decoded is not correctly encoded."
        let chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
        for (
            var bc = 0, bs, buffer, idx = 0, output = '';
            buffer = str.charAt(idx++);
            ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
                bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
        ) {
            buffer = chars.indexOf(buffer)
        }
        return output
    })(decoded).replace(/(.)/g, (_, p) => {
        let code = p.charCodeAt(0).toString(16).toUpperCase()
        return '%' + (code.length < 2 ? '0' + code : code)
    })

    return JSON.parse(decodeURIComponent(result))
};