Preserve original expiry when refreshing token (#4580)

To avoid shortening the token expiration time during
refreshing cause client reconnect failed after network
down for a long time (>5min).
This commit is contained in:
cnderrauber
2026-06-10 14:51:10 +08:00
committed by GitHub
parent 8d2b827f44
commit 7dc6877738
10 changed files with 125 additions and 9 deletions
+22 -5
View File
@@ -19,6 +19,7 @@ import (
"errors"
"net/http"
"strings"
"time"
"github.com/twitchtv/twirp"
@@ -35,8 +36,9 @@ const (
type grantsKey struct{}
type grantsValue struct {
claims *auth.ClaimGrants
apiKey string
claims *auth.ClaimGrants
apiKey string
expiresAt time.Time
}
var (
@@ -90,17 +92,23 @@ func (m *APIKeyAuthMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request,
return
}
_, grants, err := v.Verify(secret)
claims, grants, err := v.Verify(secret)
if err != nil {
HandleError(w, r, http.StatusUnauthorized, errors.New("invalid token: "+authToken+", error: "+err.Error()))
return
}
var expiresAt time.Time
if claims != nil && claims.ExpiresAt != nil {
expiresAt = claims.ExpiresAt.Time
}
// set grants in context
ctx := r.Context()
r = r.WithContext(context.WithValue(ctx, grantsKey{}, &grantsValue{
claims: grants,
apiKey: v.APIKey(),
claims: grants,
apiKey: v.APIKey(),
expiresAt: expiresAt,
}))
}
@@ -123,6 +131,15 @@ func GetGrants(ctx context.Context) *auth.ClaimGrants {
return v.claims
}
func GetTokenExpiresAt(ctx context.Context) time.Time {
val := ctx.Value(grantsKey{})
v, ok := val.(*grantsValue)
if !ok {
return time.Time{}
}
return v.expiresAt
}
func GetAPIKey(ctx context.Context) string {
val := ctx.Value(grantsKey{})
v, ok := val.(*grantsValue)