Reputation: 8836
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.
Upvotes: 4
Views: 10957
Reputation: 22555
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 .
Upvotes: 0