Home  >  Article  >  Backend Development  >  How to get expiration date from jwt token in go?

How to get expiration date from jwt token in go?

PHPz
PHPzforward
2024-02-14 12:20:09963browse

如何从 go 中的 jwt 令牌获取过期日期?

In the Go language, JWT tokens are a common authentication mechanism. To get the expiration date from the JWT token, we can use the third-party library "github.com/dgrijalva/jwt-go" to parse the token's payload. First, we need to parse the token string into a jwt.Token object, and then we can get the expiration date by accessing the Token.Claims["exp"] field. The value of this field is a Unix timestamp, which can be converted to a time type using the time.Unix function. In this way, we can easily get the expiration date of the JWT token.

Question content

I have a jwt token and I can see the decoded token on the https://jwt.io/ website. It doesn't require me to set any secrets or claims. So I'm looking for a way to decode the token to get the expiration date without providing any secret.

I am using the library ngopkg.in/square/go-jose.v2/jwt and below is my code:

token, err := jwt.ParseSigned(jwtToken)

Return value token There is a header field which includes keyid, algorithm but it doesn't give me the expiration date.

I searched this topic and people said to use github.com/auth0/go-jwt-middleware/v2/validator library, but it requires setting the key/secret. Parse whether a secret is required for the token's expiration date. Website https://jwt.io/How to know the expiration date?

Workaround

Using the example jwt token from jwt.io, This code parses and retrieves claims with unverified signatures:

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

    t, err := jwt.ParseSigned(raw)
    if err != nil {
        panic(err)
    }

    var claims map[string]any
    if err := t.UnsafeClaimsWithoutVerification(&claims); err != nil {
        panic(err)
    }

    fmt.Println(claims)
}

In this example, the expiration time should appear as one of the fields in the claims mapping. To retrieve it, use exp, ok := claims["expire"] (depending on the exact name).

The above is the detailed content of How to get expiration date from jwt token in go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete