24
votes

I am currently working on a Golang application.I receive a JWT token from the client side and, in Go I need to decode that token and get the information: user, name, etc. I was checking the libraries that are available to handle JWT tokens and I came down to https://github.com/dgrijalva/jwt-go, but I don't see how to simply make what I need.

I have the token and I need to decode the info into a map or at least a json. Where can I find a guide of how to do it? Thank you!

5
@zerkms I already saw it, but in that example I should have the struct with of the data that I will going to receive, in this case MyCustomClaims, but that can easily change from the other side and I don't want to be reestructuring that anytime that something is added or deleted - Sredny M Casanova
Possible duplicate of Go Language and Verify JWT - Tim Cooper

5 Answers

37
votes

Function jwt.ParseWithClaims accept an interface of jwt.Claims as the second argument. Besides struct-based custom claims, the package also provides map-based claims, i.e. jwt.MapClaims. So, you can simply decode the token into a MapClaims, e.g.

tokenString := "<YOUR TOKEN STRING>"    
claims := jwt.MapClaims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
    return []byte("<YOUR VERIFICATION KEY>"), nil
})
// ... error handling

// do something with decoded claims
for key, val := range claims {
    fmt.Printf("Key: %v, value: %v\n", key, val)
}
17
votes

Disclaimer: I am not affiliated to the library. I'm just a user, find it useful and would like to share.

It's 2019. I would like to suggest an alternate library that does pretty good job on JWT using JWS and/or JWE.

Here is the few examples on how to use the library:

import (
    "gopkg.in/square/go-jose.v2/jwt"
    "gopkg.in/square/go-jose.v2"
)
...

var claims map[string]interface{} // generic map to store parsed token

// decode JWT token without verifying the signature
token, _ := jwt.ParseSigned(tokenString)
_ = token.UnsafeClaimsWithoutVerification(&claims)

// decode JWT token and verify signature using JSON Web Keyset
token, _ := jwt.ParseSigned(tokenString)
jwks := &jose.JSONWebKeySet { // normally you can obtain this from an endpoint exposed by authorization server
            Keys: []jose.JSONWebKey { // just an example
                {
                    Key: publicKey, 
                    Algorithm: jose.RS256, // should be the same as in the JWT token header
                    KeyID: "kid", // should be the same as in the JWT token header
                },
            },
        }
_ = jwt.Claims(jwks, &claims)

Noted that, claims can be a struct that contains default JWT fields and also customized fields that are inside the token E.g.:

import (
    "github.com/mitchellh/mapstructure"
    "gopkg.in/square/go-jose.v2/jwt"
)
...
type CustomClaims struct {
    *jwt.Claims
    // additional claims apart from standard claims
    extra map[string]interface{}
}

func (cc *CustomClaims) UnmarshalJSON(b []byte) error {
    var rawClaims map[string]interface{}
    if err := json.Unmarshal(b, &rawClaims); err != nil {
        return nil
    }
    var claims jwt.Claims
    var decoderResult mapstructure.Metadata
    decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
        Result:   &claims,
        Metadata: &decoderResult,
        TagName:  "json",
    })
    if err != nil {
        return err
    }
    if err := decoder.Decode(rawClaims); err != nil {
        return err
    }
    cc.Claims = &claims
    cc.extra = make(map[string]interface{})
    for _, k := range decoderResult.Unused {
        cc.extra[k] = rawClaims[k]
    }
    return nil
}

I also built a command line tool that uses the library to perform various encoding/decoding activities. It might be a useful reference on the usage of the library too.

5
votes

If you want to get claims from jwt token without validation

import "github.com/dgrijalva/jwt-go"
...
    token, err := jwt.Parse(tokenStr, nil)
    if token == nil {
        return nil, err
    }
    claims, _ := token.Claims.(jwt.MapClaims)
    // claims are actually a map[string]interface{}

3
votes

Use github.com/dgrijalva/jwt-go go liabary for the implementation. we can extract JWT token information from the api request according to the following way.

When post the JWT token from the using post request. you must extract JWT information in routing section.

  func RequireTokenAuthentication(inner http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            token, err := jwt.ParseFromRequest(
                r,
                func(token *jwt.Token) (interface{}, error) {
                    return VERIFICATION.PublicKey, nil
                })
            if err != nil || !token.Valid) {
                log.Debug("Authentication failed " + err.Error())
                w.WriteHeader(http.StatusForbidden)
                return
            } else {
                r.Header.Set("username", token.Claims["username"].(string))
                r.Header.Set("userid", strconv.FormatFloat((token.Claims["userid"]).(float64), 'f', 0, 64))
            }
            inner.ServeHTTP(w, r)
        })
    }

VERIFICATION.PublicKey : The key for verification(get public key from public.key file in your system)

Any Issue happen.Please let me know. I can give you help.

0
votes

Since both the question and answers mention the JWT library github.com/dgrijalva/jwt-go, please note that this library has been unmaintained for a long time now.

As of June 2021 there is a community fork golang-jwt/jwt, officially blessed by Dave Grijalva, the original author.

This also means that the library import path has changed. Note that the current major version v3 is not on Go modules, therefore you will still see v3.x.x+incompatible in your go.mod.

The fork fixes an important security issue with the original library. Before the fix, the library didn't properly handle multiple aud in the JWT claims, making it actually not compliant with the JWT spec.

Apart from that, the main API is still the same. For example to parse a JWT with HMAC verification:

    tokenString := /* raw JWT string*/

    token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
        if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
            return nil, errors.New("unexpected signing method")
        }
        return []byte(/* your JWT secret*/), nil
    })
    if err != nil {
        // handle err
    }

    // validate the essential claims
    if !token.Valid {
        // handle invalid tokebn
    }

To parse a JWT with custom claims, you can define your own struct type and embed jwt.StandardClaims into it:

    type MyClaims struct {
        jwt.StandardClaims
        MyField string `json:"my_field"`
    }

    tokenString := /* raw JWT string*/

    // pass your custom claims to the parser function
    token, err := jwt.ParseWithClaims(tokenString, &MyClaims{}, func(token *jwt.Token) (interface{}, error) {
        if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
            return nil, errors.New("unexpected signing method")
        }
        return []byte(/* your JWT secret*/), nil
    })

    // type-assert `Claims` into a variable of the appropriate type
    myClaims := token.Claims.(*MyClaims)

A valid alternative to this library is lestrrat-go/jwx. The API is slightly different, but also very easy to use:

    tokenString := /* raw JWT string*/

    // parse and verify signature
    tok, err := jwt.Parse(tokenString, jwt.WithVerify(jwa.HS256, []byte(/* your JWT secret */)))
    if err != nil {
        // handle err
    }

    // validate the essential claims
    if err := jwt.Validate(tok); err != nil {
        // handle err
    }