-
Notifications
You must be signed in to change notification settings - Fork 121
/
decode_jwt.go
62 lines (53 loc) · 1.26 KB
/
decode_jwt.go
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package peirates
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"strings"
)
// JWT structure to hold decoded JWT parts
type JWT struct {
Header string
Payload string
Signature string
RawHeader string
RawPayload string
RawSignature string
}
// decodeJWT decodes a JWT token into its parts
func decodeJWT(token string) JWT {
parts := strings.Split(token, ".")
if len(parts) != 3 {
panic("Invalid JWT format")
}
header := decodeBase64(parts[0])
payload := decodeBase64(parts[1])
signature := parts[2]
jwt := JWT{
Header: header,
Payload: payload,
Signature: signature,
RawHeader: parts[0],
RawPayload: parts[1],
RawSignature: parts[2],
}
return jwt
}
// decodeBase64 decodes a base64url-encoded string
func decodeBase64(str string) string {
decoded, err := base64.RawURLEncoding.DecodeString(str)
if err != nil {
panic(fmt.Sprintf("Error decoding base64url: %s", err.Error()))
}
return string(decoded)
}
// PrettyPrintPayload pretty prints the decoded JWT payload
func (jwt *JWT) PrettyPrintPayload() string {
var prettyJSON bytes.Buffer
err := json.Indent(&prettyJSON, []byte(jwt.Payload), "", " ")
if err != nil {
return "Error pretty printing JSON"
}
return string(prettyJSON.Bytes())
}