This repository has been archived by the owner on Sep 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
jwt.go
59 lines (51 loc) · 1.42 KB
/
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
package internal
import (
"encoding/json"
"fmt"
"time"
jwt "github.com/golang-jwt/jwt/v5"
)
type JWT struct {
Header string
Claims string
Expires *time.Time
}
func DecodeJWT(jwtToken string) (JWT, error) {
token, _, err := new(jwt.Parser).ParseUnverified(jwtToken, jwt.MapClaims{})
if err != nil {
return JWT{}, err
}
headersJSON, _ := json.MarshalIndent(token.Header, "", " ")
claims := token.Claims.(jwt.MapClaims)
var expires *time.Time
expireTime, err := token.Claims.GetExpirationTime()
if err != nil || expireTime == nil {
expires = nil
} else {
expires = &expireTime.Time
}
claimsJSON, _ := json.MarshalIndent(claims, "", " ")
return JWT{Header: string(headersJSON), Claims: string(claimsJSON), Expires: expires}, nil
}
func EncodeJWT(headers map[string]interface{}, claims map[string]interface{}, signature string) (string, error) {
algorithms := jwt.GetAlgorithms()
algorithmExists := false
if _, ok := headers["alg"]; !ok {
headers["alg"] = "HS256"
}
algorithm := headers["alg"].(string)
for _, a := range algorithms {
if a == headers["alg"] {
algorithm = a
algorithmExists = true
break
}
}
if !algorithmExists {
return "", fmt.Errorf("algorithm %s is not supported", algorithm)
}
token := jwt.NewWithClaims(jwt.GetSigningMethod(algorithm), jwt.MapClaims(claims))
token.Header = headers
signedString, err := token.SignedString([]byte(signature))
return signedString, err
}