-
Notifications
You must be signed in to change notification settings - Fork 40
/
token.go
47 lines (37 loc) · 1.22 KB
/
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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package auth
import (
"golang.org/x/oauth2"
"time"
"github.com/hashicorp/go-azure-sdk/sdk/claims"
)
const tokenExpiryDelta = 20 * time.Minute
// tokenExpiresSoon returns true if the token expires within 10 minutes, or if more than 50% of its validity period has elapsed (if this can be determined), whichever is later
func tokenDueForRenewal(token *oauth2.Token) bool {
if token == nil {
return true
}
// Some tokens may never expire
if token.Expiry.IsZero() {
return false
}
expiry := token.Expiry.Round(0)
delta := tokenExpiryDelta
now := time.Now()
expiresWithinTenMinutes := expiry.Add(-delta).Before(now)
// Try to parse the token claims to retrieve the issuedAt time
if claims, err := claims.ParseClaims(token); err == nil {
if claims.IssuedAt > 0 {
issued := time.Unix(claims.IssuedAt, 0)
validity := expiry.Sub(issued)
// If the validity period is less than double the expiry delta, then instead
// determine whether >50% of the validity period has elapsed
if validity < delta*2 {
halfValidityHasElapsed := issued.Add(validity / 2).Before(now)
return halfValidityHasElapsed
}
}
}
return expiresWithinTenMinutes
}