-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtokens.go
204 lines (170 loc) · 5.53 KB
/
tokens.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package awstokens
import (
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cognitoidentityprovider"
"github.com/dgrijalva/jwt-go"
"github.com/pkg/errors"
)
const defaultExpiryMargin time.Duration = 5 * time.Second
// AuthInitiator is an interface that represents the cognitoidentityprovider
// library client, which allows you to refresh tokens.
type AuthInitiator interface {
InitiateAuth(input *cognitoidentityprovider.InitiateAuthInput) (*cognitoidentityprovider.InitiateAuthOutput, error)
}
// Config contains the initial settings for the Auth.
type Config struct {
// Actual tokens
AccessToken, IDToken, RefreshToken string
// Info required to refresh the tokens
ClientID, Region string
// By default use the access token for auth, but if this is true then use ID
// token instead
ShouldUseIDToken bool
// ExpiryMargin is the margin in which a token is considered to be expired.
// If it is left empty (i.e. 0) then we will use the default value of 5
// seconds.
ExpiryMargin time.Duration
}
// Auth contains the AWS tokens and some extra info for refreshing them.
type Auth struct {
mu sync.RWMutex
authInitiator AuthInitiator
// Actual tokens
accessToken, idToken, refreshToken string
// Info required to refresh the tokens
clientID string
// Extra settings
useIDToken bool
expiryMargin time.Duration
}
// NewAuth returns a pointer to an Auth using the provided Config.
func NewAuth(config Config) (*Auth, error) {
// Put in fake creds because we need to provide some creds or else
// NewSession will return an error. We don't need valid creds to refresh
// tokens.
creds := credentials.NewStaticCredentials("access_id", "access_secret_key", "")
sess, err := session.NewSession(&aws.Config{
Region: aws.String(config.Region),
Credentials: creds,
})
if err != nil {
return nil, errors.Wrap(err, "session.NewSession")
}
cognitoIDP := cognitoidentityprovider.New(sess)
return NewAuthWithAuthInitiator(cognitoIDP, config), nil
}
// NewAuthWithAuthInitiator returns a pointer to an Auth using the provided config and AuthInitiator.
func NewAuthWithAuthInitiator(authInitiator AuthInitiator, config Config) *Auth {
expiryMargin := defaultExpiryMargin
if config.ExpiryMargin > 0 {
expiryMargin = config.ExpiryMargin
}
return &Auth{
authInitiator: authInitiator,
accessToken: config.AccessToken,
idToken: config.IDToken,
refreshToken: config.RefreshToken,
clientID: config.ClientID,
useIDToken: config.ShouldUseIDToken,
expiryMargin: expiryMargin,
}
}
// GetAuthToken returns the Access token by default, but if ShouldUseIDToken has
// been set to true it returns the ID token. If the token it is going to return
// has expired then it attempts to refresh the token before returning it.
func (t *Auth) GetAuthToken() (string, error) {
token := t.getAuthTokenNoCheck()
if !tokenIsExpired(token, t.getExpiryMargin()) {
return token, nil
}
if err := t.refreshTokens(); err != nil {
return "", errors.Wrap(err, "refresh failed")
}
return t.getAuthTokenNoCheck(), nil
}
func (t *Auth) getAuthTokenNoCheck() string {
if t.shouldUseIDToken() {
return t.getIDToken()
}
return t.getAccessToken()
}
func (t *Auth) getIDToken() string {
t.mu.RLock()
defer t.mu.RUnlock()
return t.idToken
}
func (t *Auth) getAccessToken() string {
t.mu.RLock()
defer t.mu.RUnlock()
return t.accessToken
}
func (t *Auth) shouldUseIDToken() bool {
t.mu.RLock()
defer t.mu.RUnlock()
return t.useIDToken
}
func (t *Auth) getExpiryMargin() time.Duration {
t.mu.RLock()
defer t.mu.RUnlock()
return t.expiryMargin
}
func (t *Auth) getRefreshToken() string {
t.mu.RLock()
defer t.mu.RUnlock()
return t.refreshToken
}
func (t *Auth) getClientID() string {
t.mu.RLock()
defer t.mu.RUnlock()
return t.clientID
}
func (t *Auth) setIDToken(token string) {
t.mu.Lock()
defer t.mu.Unlock()
t.idToken = token
}
func (t *Auth) setAccessToken(token string) {
t.mu.Lock()
defer t.mu.Unlock()
t.accessToken = token
}
func (t *Auth) refreshTokens() error {
res, err := t.authInitiator.InitiateAuth(&cognitoidentityprovider.InitiateAuthInput{
AuthFlow: aws.String(cognitoidentityprovider.AuthFlowTypeRefreshTokenAuth),
AuthParameters: map[string]*string{
cognitoidentityprovider.AuthFlowTypeRefreshToken: aws.String(t.getRefreshToken()),
},
ClientId: aws.String(t.getClientID()),
})
if err != nil {
return errors.Wrap(err, "cognitoidentityprovider.New.InitiateAuth")
}
if res.AuthenticationResult == nil {
return errors.New("cognitoidentityprovider.New.InitiateAuth response has no AuthenticationResult")
}
if res.AuthenticationResult.AccessToken == nil {
return errors.New("cognitoidentityprovider.New.InitiateAuth response has no AccessToken")
}
if res.AuthenticationResult.IdToken == nil {
return errors.New("cognitoidentityprovider.New.InitiateAuth response has no IdToken")
}
t.setAccessToken(*res.AuthenticationResult.AccessToken)
t.setIDToken(*res.AuthenticationResult.IdToken)
return nil
}
// tokenIsExpired checks if the provided token has expired, or is shortly due
// to expire.
func tokenIsExpired(token string, expiryMargin time.Duration) bool {
adjustedExpiryTime := getTokenExpiryTime(token) - int64(expiryMargin/time.Second)
return time.Now().UTC().Unix() > adjustedExpiryTime
}
func getTokenExpiryTime(token string) int64 {
// Parse the token without validating it.
claims := jwt.StandardClaims{}
_, _ = jwt.ParseWithClaims(token, &claims, nil)
return claims.ExpiresAt
}