4

I am setting the the expiration of JWT token claims using

claims["exp"] = time.Now().Add(time.Hour * time.Duration(settings.Get().JWTExpiration)).Unix()

where settings.Get().JWTExpiration gives me the settings I have made in my application settings file.

I have written a function which should ideally give me the remaining time the token is valid for.

func getTokenRemainingValidity(timestamp interface{}) int {
    if validity, ok := timestamp.(float64); ok {
        tm := time.Unix(int64(validity), 0)
        remainder := tm.Sub(time.Now())
        if remainder > 0 {
            return int(remainder.Seconds() + expireOffset)
        }
    }
    return expireOffset
}

and I invoke this function like:

x := getTokenRemainingValidity(claims["exp"])
fmt.Println(x)

where claims["exp"] is the claims I have got after parsing a jwt token. But this always gives me same output. i.e. 3600. How can I check for the remaining validity of my token. I am using golang.

Grokify
  • 15,092
  • 6
  • 60
  • 81
codec
  • 7,978
  • 26
  • 71
  • 127
  • 3
    Just ask, why don't you just use a golang jwt package.... – John Zeng Aug 24 '16 at 10:02
  • Your code doesn't compile. `expireOffset` must be an int (because of the return), but `remainder.Seconds()` is a float64, so you can't add an int to it. What is the value of expireOffset? Also check that timestamp is indeed float64 and not Number: https://golang.org/pkg/encoding/json/#Number – user1431317 Aug 24 '16 at 11:57

1 Answers1

0

You always get 3600 (which seems to be the expireOffset) because the type assertion timestamp.(float64) fails, as the actual value of timestamp is int64.

func getTokenRemainingValidity(timestamp interface{}) int {
    var expireOffset = 3600
    if validity, ok := timestamp.(int64); ok {
        tm := time.Unix(int64(validity), 0)
        remainder := tm.Sub(time.Now())

        if remainder > 0 {
            return int(remainder.Seconds() + float64(expireOffset))
        }
    }
    return expireOffset
}

To make it work, I added the expireOffset and set it to 3600. In the first return statement, expireOffset has to be convertet to float64, and then the result back to int. This way it works, though I'm not sure for what you add or return the offset.

A full working example can be seen and tested here on the Go Playground .

jps
  • 20,041
  • 15
  • 75
  • 79