Skip to content

Commit

Permalink
Add token refresh grace period (#54)
Browse files Browse the repository at this point in the history
* Add token within expiry grace period check

* Migrate WithinGracePeriod

* Deassociate

* Not

* Unexport

* Unexport var
  • Loading branch information
mjcmtb authored Sep 23, 2024
1 parent c982e42 commit 8c45328
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion tokencache/cache_token_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,15 @@ package tokencache
import (
"context"
"fmt"
"time"

"github.com/pardot/oidc"
)

const (
tokenExpirationGracePeriod = time.Duration(30 * time.Second)
)

type cachingTokenSource struct {
src oidc.TokenSource
cache CredentialCache
Expand Down Expand Up @@ -87,7 +92,7 @@ func (c *cachingTokenSource) Token(ctx context.Context) (*oidc.Token, error) {
}

var newToken *oidc.Token
if token != nil && token.Valid() {
if token != nil && token.Valid() && !tokenWithinGracePeriod(token) {
return token, nil
} else if token != nil && token.RefreshToken != "" {
// we have an expired token, try and refresh if we can.
Expand All @@ -114,3 +119,8 @@ func (c *cachingTokenSource) Token(ctx context.Context) (*oidc.Token, error) {

return newToken, nil
}

func tokenWithinGracePeriod(token *oidc.Token) bool {
gracePeriodStart := token.Claims.Expiry.Time().Add(-tokenExpirationGracePeriod)
return gracePeriodStart.Before(time.Now()) && token.Valid()
}

0 comments on commit 8c45328

Please sign in to comment.