如何将 JWT 的到期日期解析为 Go 中的 time.Time()?

How to parse the expiration date of a JWT to a time.Time() in Go?

我想从 JSON Web 令牌 (JWT) 中解析到期日期 (exp) 而不验证它。我尝试了以下脚本(试图遵循 How to parse unix timestamp to time.Time):

package main

import (
    "fmt"
    "log"
    "strconv"
    "time"

    jwt "github.com/dgrijalva/jwt-go"
)

func main() {
    tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"

    token, _, err := new(jwt.Parser).ParseUnverified(tokenString, jwt.MapClaims{})
    if err != nil {
        log.Fatal(err)
    }

    if claims, ok := token.Claims.(jwt.MapClaims); ok {
        fmt.Println(claims["exp"])
        i, err := strconv.ParseInt(claims["exp"].(string), 10, 64)
        if err != nil {
            log.Fatal(err)
        }

        tm := time.Unix(i, 0)
        fmt.Println(tm)
    }
}

但是,我得到这个错误:

> go run main.go
<nil>
panic: interface conversion: interface {} is nil, not string

goroutine 1 [running]:
main.main()
    /Users/kurt/go/src/github.com/khpeek/mygoproject/jwt_validation/main.go:23 +0x34a
exit status 2

有没有办法从 jwt 库中获取 exp 的字符串?我怎样才能让这个给我 JWT 的到期日期(或 iat)?

我最终直接在 claims["exp"] 上调用 int64,而不是首先尝试将其转换为字符串:

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "time"

    jwt "github.com/dgrijalva/jwt-go"
)

func main() {
    tokenString := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"

    token, _, err := new(jwt.Parser).ParseUnverified(tokenString, jwt.MapClaims{})
    if err != nil {
        log.Fatal(err)
    }

    claims, ok := token.Claims.(jwt.MapClaims)
    if !ok {
        log.Fatalf("Can't convert token's claims to standard claims")
    }

    var tm time.Time
    switch iat := claims["iat"].(type) {
    case float64:
        tm = time.Unix(int64(iat), 0)
    case json.Number:
        v, _ := iat.Int64()
        tm = time.Unix(v, 0)
    }

    fmt.Println(tm)
}

打印

> go run main.go
2018-01-17 17:30:22 -0800 PST

请注意,我已将 exp 替换为 iat,因为简化示例(从 jwt.io 获得)没有 exp 声明,但它确实有一个 iat 个。