From a68fa4bfb977392e7294d771c30821b432400007 Mon Sep 17 00:00:00 2001 From: Dylan Ratcliffe Date: Mon, 13 Feb 2023 13:54:54 +0000 Subject: [PATCH] Fixed token refresh on expiry An expired token isn't actually considered an "Error" so I'm changing the logic to catch expiries as "blocking" errors --- auth.go | 2 +- nats_test.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/auth.go b/auth.go index 5db12f9..7e75264 100644 --- a/auth.go +++ b/auth.go @@ -224,7 +224,7 @@ func (o *OAuthTokenClient) GetJWT() (string, error) { claims.Validate(&vr) - if len(vr.Errors()) != 0 { + if vr.IsBlocking(true) { // Regenerate the token err := o.generateJWT(ctx) diff --git a/nats_test.go b/nats_test.go index 5820548..7704372 100644 --- a/nats_test.go +++ b/nats_test.go @@ -5,7 +5,9 @@ import ( "testing" "time" + "github.com/nats-io/jwt/v2" "github.com/nats-io/nats.go" + "github.com/nats-io/nkeys" "github.com/overmindtech/sdp-go" ) @@ -312,6 +314,49 @@ func TestNATSConnect(t *testing.T) { }) } +func TestTokenRefresh(t *testing.T) { + tk := GetTestOAuthTokenClient(t) + + // Get a token + token, err := tk.GetJWT() + + if err != nil { + t.Fatal(err) + } + + // Artificially set the expiry and replace the token + claims, err := jwt.DecodeUserClaims(token) + + if err != nil { + t.Fatal(err) + } + + pair, err := nkeys.CreateAccount() + + if err != nil { + t.Fatal(err) + } + + claims.Expires = time.Now().Add(-10 * time.Second).Unix() + tk.jwt, err = claims.Encode(pair) + expiredToken := tk.jwt + + if err != nil { + t.Error(err) + } + + // Get the token again + newToken, err := tk.GetJWT() + + if err != nil { + t.Error(err) + } + + if expiredToken == newToken { + t.Error("token is unchanged") + } +} + func ValidateNATSConnection(t *testing.T, ec sdp.EncodedConnection) { t.Helper() done := make(chan struct{})