-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
85 lines (76 loc) · 1.73 KB
/
parser.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"encoding/json"
"fmt"
"regexp"
"strings"
"github.com/golang-jwt/jwt/v5"
)
const (
jsonOutIndent = " "
regexTemplate = `(?m)^( +"%s": )\d+,$`
replaceTemplate = `${1}"%+v",`
)
var (
expRe *regexp.Regexp = regexp.MustCompile(fmt.Sprintf(regexTemplate, "exp"))
iatRe *regexp.Regexp = regexp.MustCompile(fmt.Sprintf(regexTemplate, "iat"))
)
func parseAndFormat(jwtS string) (string, error) {
p := jwt.NewParser()
token, _, err := p.ParseUnverified(
jwtS,
jwt.MapClaims{},
)
if err != nil {
return EmptyString, err
}
headerFormatted, err := json.MarshalIndent(token.Header, "", jsonOutIndent)
if err != nil {
return EmptyString, err
}
bs, err := json.MarshalIndent(token.Claims, "", jsonOutIndent)
if err != nil {
return EmptyString, err
}
claimsFormated := string(bs)
exp, err := token.Claims.GetExpirationTime()
if err != nil {
return EmptyString, err
}
if exp != nil {
tmpClaims := expRe.ReplaceAllString(
claimsFormated,
fmt.Sprintf(replaceTemplate, exp),
)
claimsFormated = tmpClaims
}
iat, err := token.Claims.GetIssuedAt()
if err != nil {
return EmptyString, err
}
if iat != nil {
tmpClaims := iatRe.ReplaceAllString(
claimsFormated,
fmt.Sprintf(replaceTemplate, iat),
)
claimsFormated = tmpClaims
}
alg := fmt.Sprintf("%s", token.Header["alg"])
algFS := strings.Replace(alg, "HS", "HMACSHA", -1)
signatureFormated := strings.Join(
[]string{
fmt.Sprintf(`%s(`, algFS),
` base64UrlEncode(header) + "." + base64UrlEncode(payload),`,
` your-256-bit-secret`,
`)`,
},
"\n",
)
out := fmt.Sprintf(
"===\nHeader →\n%s\nClaims →\n%s\nSignature →\n%s\n===\n",
headerFormatted,
claimsFormated,
signatureFormated,
)
return out, nil
}