forked from oracle/oci-go-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
69 lines (58 loc) · 1.83 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
60
61
62
63
64
65
66
67
68
69
// Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
package auth
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/oracle/oci-go-sdk/common"
"strings"
"time"
)
type jwtToken struct {
raw string
header map[string]interface{}
payload map[string]interface{}
}
const bufferTimeBeforeTokenExpiration = 5 * time.Minute
func (t *jwtToken) expired() bool {
exp := int64(t.payload["exp"].(float64))
expTime := time.Unix(exp, 0)
expired := exp <= time.Now().Unix()+int64(bufferTimeBeforeTokenExpiration.Seconds())
if expired {
common.Debugf("Token expires at: %v, currently expired due to bufferTime: %v", expTime.Format("15:04:05.000"), expired)
}
return expired
}
func parseJwt(tokenString string) (*jwtToken, error) {
parts := strings.Split(tokenString, ".")
if len(parts) != 3 {
return nil, fmt.Errorf("the given token string contains an invalid number of parts")
}
token := &jwtToken{raw: tokenString}
var err error
// Parse Header part
var headerBytes []byte
if headerBytes, err = decodePart(parts[0]); err != nil {
return nil, fmt.Errorf("failed to decode the header bytes: %s", err.Error())
}
if err = json.Unmarshal(headerBytes, &token.header); err != nil {
return nil, err
}
// Parse Payload part
var payloadBytes []byte
if payloadBytes, err = decodePart(parts[1]); err != nil {
return nil, fmt.Errorf("failed to decode the payload bytes: %s", err.Error())
}
decoder := json.NewDecoder(bytes.NewBuffer(payloadBytes))
if err = decoder.Decode(&token.payload); err != nil {
return nil, fmt.Errorf("failed to decode the payload json: %s", err.Error())
}
return token, nil
}
func decodePart(partString string) ([]byte, error) {
if l := len(partString) % 4; 0 < l {
partString += strings.Repeat("=", 4-l)
}
return base64.URLEncoding.DecodeString(partString)
}