5

我想exp从 JSON Web 令牌 (JWT) 解析到期日期 (),而不进行验证。我尝试了以下脚本(试图遵循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

有没有办法expjwt图书馆里得到一个字符串?我怎样才能让这给我iatJWT 的到期日期(或 )?

4

1 回答 1

3

我最终直接调用int64claims["exp"]不是首先尝试将其转换为字符串:

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

于 2019-10-17T23:27:07.847 回答