user2212726
user2212726

Reputation: 1285

How to extract the claims from JWT token

I'm using the dgrijalva/jwt-go/ package.

I would like to extract the payload from the token, and I couldn't find a way to do it.


Example (taken from : https://jwt.io/):

for encoded:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ

I would like to extract the payload:

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}

I will be grateful for an example (using golang).

Upvotes: 21

Views: 36272

Answers (2)

0xTanvir
0xTanvir

Reputation: 125

If you want to extract the claims without secret, you can use the ParseUnverified

func extractUnverifiedClaims(tokenString string) (string, error) {
    var name string
    token, _, err := new(jwt.Parser).ParseUnverified(tokenString, jwt.MapClaims{})
    if err != nil {
        return "", err
    }

    if claims, ok := token.Claims.(jwt.MapClaims); ok {
        name = fmt.Sprint(claims["name"])
    }

    if name == "" {
        return "", fmt.Errorf("invalid token payload")
    }
    return name, nil
}

Full code: https://go.dev/play/p/a7CdBNL8LzW

Upvotes: 5

Ankit Deshpande
Ankit Deshpande

Reputation: 3604

Sample Code:

    func extractClaims(tokenStr string) (jwt.MapClaims, bool) {
        hmacSecretString := // Value
        hmacSecret := []byte(hmacSecretString)
        token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
             // check token signing method etc
             return hmacSecret, nil
        })

        if err != nil {
            return nil, false
        }

        if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
            return claims, true
        } else {
            log.Printf("Invalid JWT Token")
            return nil, false
        }
    }

Upvotes: 27

Related Questions