golang-jwt / jwt

Go implementation of JSON Web Tokens (JWT).
https://golang-jwt.github.io/jwt/
MIT License
6.98k stars 335 forks source link

Customize the unit of timestamp/exp in payload #367

Closed icbd closed 9 months ago

icbd commented 9 months ago

https://github.com/golang-jwt/jwt/blob/8ab6606c2f0cf68ed0a532a150d13497daacf2cf/types.go#L71-L71

func (date NumericDate) MarshalJSON() (b []byte, err error) {
    var prec int
    if TimePrecision < time.Second {
        prec = int(math.Log10(float64(time.Second) / float64(TimePrecision)))
    }
    truncatedDate := date.Truncate(TimePrecision)

    seconds := strconv.FormatInt(truncatedDate.Unix(), 10)
    nanosecondsOffset := strconv.FormatFloat(float64(truncatedDate.Nanosecond())/float64(time.Second), 'f', prec, 64)

    output := append([]byte(seconds), []byte(nanosecondsOffset)[1:]...)

    return output, nil
}

Only support seconds here.

How can we measure in milliseconds (*1000)?


If I change TimePrecision to time.Millisecond, will get the float number in seconds.

oxisto commented 9 months ago

You can't. The unit of exp is fixed to seconds. The type of the field is a NumericDate, which is defined in https://datatracker.ietf.org/doc/html/rfc7519#section-2 as:

NumericDate
      A JSON numeric value representing the number of seconds from
      1970-01-01T00:00:00Z UTC until the specified UTC date/time,
      ignoring leap seconds.  This is equivalent to the IEEE Std 1003.1,
      2013 Edition [[POSIX.1](https://datatracker.ietf.org/doc/html/rfc7519#ref-POSIX.1)] definition "Seconds Since the Epoch", in
      which each day is accounted for by exactly 86400 seconds, other
      than that non-integer values can be represented.  See [RFC 3339](https://datatracker.ietf.org/doc/html/rfc3339)
      [[RFC3339](https://datatracker.ietf.org/doc/html/rfc3339)] for details regarding date/times in general and UTC in
      particular.