简体   繁体   中英

How to decode a JWT token in Go?

I am currently working on a Go application. I receive a JWT token from the client side and I need to decode that token and obtain the relevant information: user, name, etc.

I was checking the libraries that are available to handle JWT tokens and I came down to dgrijalva/jwt-go , but I don't see how to accomplish my goal in a simple way.

I have the token and I need to decode the info into a map or at least a json. How can I do it?

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!

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!

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 .


Edit: since August 2021 version v4 of golang-jwt/jwt is available. This finally supports Go modules . The new version is backward-compatible with previous versions, so in order to migrate simply replace the old import path with:

github.com/golang-jwt/jwt/v4

then update your modules as needed — see also the migration guide for details.


The fork most notably 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
    }

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!

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!

I had a kind of very similar use case where I wanted to verify an access token and extract fields(such as: iss , sub , aud , exp , iat , jti , etc..) from it after decoding. For my use case, I have used jwx and jwt-go libs.

Please find the detailed code snippet here which worked for me.

Code snippet

go.mod
module my-go-module

go 1.16

require (
    github.com/dgrijalva/jwt-go v3.2.0+incompatible
    github.com/lestrrat-go/jwx v1.0.4
)
main package
package main

import (
    "errors"
    "fmt"

    "github.com/dgrijalva/jwt-go"
    "github.com/lestrrat-go/jwx/jwa"
    "github.com/lestrrat-go/jwx/jwk"
)

func main() {
    jwksURL := "https://your-tenant.auth0.com/.well-known/jwks.json"

    keySet, _ := jwk.Fetch(jwksURL)
    var accessToken = "eyJhbGciOiJSUzI1NiIsImtpZCI6Ind5TXdLNEE2Q0w5UXcxMXVvZlZleVExMTlYeVgteHlreW1ra1h5Z1o1T00ifQ.eyJzdWIiOiIwMHUxOGVlaHUzNDlhUzJ5WDFkOCIsIm5hbWUiOiJva3RhcHJveHkgb2t0YXByb3h5IiwidmVyIjoxLCJpc3MiOiJodHRwczovL2NvbXBhbnl4Lm9rdGEuY29tIiwiYXVkIjoidlpWNkNwOHJuNWx4ck45YVo2ODgiLCJpYXQiOjE0ODEzODg0NTMsImV4cCI6MTQ4MTM5MjA1MywianRpIjoiSUQuWm9QdVdIR3IxNkR6a3RUbEdXMFI4b1lRaUhnVWg0aUotTHo3Z3BGcGItUSIsImFtciI6WyJwd2QiXSwiaWRwIjoiMDBveTc0YzBnd0hOWE1SSkJGUkkiLCJub25jZSI6Im4tMFM2X1d6QTJNaiIsInByZWZlcnJlZF91c2VybmFtZSI6Im9rdGFwcm94eUBva3RhLmNvbSIsImF1dGhfdGltZSI6MTQ4MTM4ODQ0MywiYXRfaGFzaCI6Im1YWlQtZjJJczhOQklIcV9CeE1ISFEifQ.OtVyCK0sE6Cuclg9VMD2AwLhqEyq2nv3a1bfxlzeS-bdu9KtYxcPSxJ6vxMcSSbMIIq9eEz9JFMU80zqgDPHBCjlOsC5SIPz7mm1Z3gCwq4zsFJ-2NIzYxA3p161ZRsPv_3bUyg9B_DPFyBoihgwWm6yrvrb4rmHXrDkjxpxCLPp3OeIpc_kb2t8r5HEQ5UBZPrsiScvuoVW13YwWpze59qBl_84n9xdmQ5pS7DklzkAVgqJT_NWBlb5uo6eW26HtJwHzss7xOIdQtcOtC1Gj3O82a55VJSQnsEEBeqG1ESb5Haq_hJgxYQnBssKydPCIxdZiye-0Ll9L8wWwpzwig"
    token, err := verify(accessToken, keySet)
    if err != nil {
        fmt.Printf("Gor an error while verifiying access token: %v\n", err)
    }

    // Check if the token is valid.
    if !token.Valid {
        fmt.Println("The token is not valid.")
    }

    // Extract key value from the token and print them on console
    claims := token.Claims.(jwt.MapClaims)
    for key, value := range claims {
        fmt.Printf("%s\t%v\n", key, value)
    }
}

func verify(tokenString string, keySet *jwk.Set) (*jwt.Token, error) {
    tkn, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
        if token.Method.Alg() != jwa.RS256.String() { 
            return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
        }
        kid, ok := token.Header["kid"].(string)
        if !ok {
            return nil, errors.New("kid header not found")
        }
        keys := keySet.LookupKeyID(kid)
        if len(keys) == 0 {
            return nil, fmt.Errorf("key %v not found", kid)
        }
        var raw interface{}
        return raw, keys[0].Raw(&raw)
    })
    return tkn, err
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM