-
Notifications
You must be signed in to change notification settings - Fork 52
/
iam_token.go
104 lines (89 loc) · 2.5 KB
/
iam_token.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package core_config
import (
"encoding/base64"
"encoding/json"
"strings"
"time"
"github.com/IBM-Cloud/ibm-cloud-cli-sdk/common/types"
)
const (
SubjectTypeServiceID = "ServiceId"
SubjectTypeTrustedProfile = "Profile"
)
const expiryDelta = 10 * time.Second
type IAMTokenInfo struct {
IAMID string `json:"iam_id"`
ID string `json:"id"`
RealmID string `json:"realmid"`
SessionID string `json:"session_id"`
Identifier string `json:"identifier"`
Firstname string `json:"given_name"`
Lastname string `json:"family_name"`
Fullname string `json:"name"`
UserEmail string `json:"email"`
Accounts AccountsInfo `json:"account"`
Subject string `json:"sub"`
SubjectType string `json:"sub_type"`
Issuer string `json:"iss"`
GrantType string `json:"grant_type"`
Scope string `json:"scope"`
Authn Authn `json:"authn"`
Expiry time.Time
IssueAt time.Time
}
type AccountsInfo struct {
AccountID string `json:"bss"`
IMSAccountID string `json:"ims"`
Valid bool `json:"valid"`
}
type Authn struct {
Subject string `json:"sub"`
IAMID string `json:"iam_id"`
Name string `json:"name"`
Firstname string `json:"given_name"`
Lastname string `json:"family_name"`
Email string `json:"email"`
}
func NewIAMTokenInfo(token string) IAMTokenInfo {
tokenJSON, err := DecodeAccessToken(token)
if err != nil {
return IAMTokenInfo{}
}
var t struct {
IAMTokenInfo
Expiry types.UnixTime `json:"exp"`
IssueAt types.UnixTime `json:"iat"`
}
err = json.Unmarshal(tokenJSON, &t)
if err != nil {
return IAMTokenInfo{}
}
ret := t.IAMTokenInfo
ret.Expiry = t.Expiry.Time()
ret.IssueAt = t.IssueAt.Time()
return ret
}
// DecodeAccessToken will decode an access token string into a raw JSON.
// The encoded string is expected to be in three parts separated by a period.
// This method does not validate the contents of the parts
func DecodeAccessToken(token string) (tokenJSON []byte, err error) {
encodedParts := strings.Split(token, ".")
if len(encodedParts) < 3 {
return
}
encodedTokenJSON := encodedParts[1]
return base64.RawURLEncoding.DecodeString(encodedTokenJSON)
}
func (t IAMTokenInfo) exists() bool {
// token without an ID is invalid
return t.ID != ""
}
func (t IAMTokenInfo) hasExpired() bool {
if !t.exists() {
return true
}
if t.Expiry.IsZero() {
return false
}
return t.Expiry.Before(time.Now().Add(expiryDelta))
}