AUTH-2235 GetTokenIfExists now parses JWT payload for json expiry field to detect if the cached access token is expired

This commit is contained in:
Elvin Tan 2020-02-24 10:48:06 +08:00 committed by Austin Cherry
parent 1c6ea36e73
commit 6d63f84a75
1 changed files with 29 additions and 1 deletions

View File

@ -2,12 +2,14 @@ package token
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/url"
"os"
"os/signal"
"syscall"
"time"
"github.com/cloudflare/cloudflared/cmd/cloudflared/config"
"github.com/cloudflare/cloudflared/cmd/cloudflared/path"
@ -34,6 +36,21 @@ type signalHandler struct {
signals []os.Signal
}
type jwtPayload struct {
Aud []string `json:"aud"`
Email string `json:"email"`
Exp int `json:"exp"`
Iat int `json:"iat"`
Nbf int `json:"nbf"`
Iss string `json:"iss"`
Type string `json:"type"`
Subt string `json:"sub"`
}
func (p jwtPayload) isExpired() bool {
return int(time.Now().Unix()) > p.Exp
}
func (s *signalHandler) register(handler func()) {
s.sigChannel = make(chan os.Signal, 1)
signal.Notify(s.sigChannel, s.signals...)
@ -147,7 +164,7 @@ func FetchToken(appURL *url.URL) (string, error) {
return string(token), nil
}
// GetTokenIfExists will return the token from local storage if it exists
// GetTokenIfExists will return the token from local storage if it exists and not expired
func GetTokenIfExists(url *url.URL) (string, error) {
path, err := path.GenerateFilePathFromURL(url, keyName)
if err != nil {
@ -162,6 +179,17 @@ func GetTokenIfExists(url *url.URL) (string, error) {
return "", err
}
var payload jwtPayload
err = json.Unmarshal(token.Payload, &payload)
if err != nil {
return "", err
}
if payload.isExpired() {
err := os.Remove(path)
return "", err
}
return token.Encode(), nil
}