在Go中解析JSON Web令牌声明

I am trying to do some authentication with JSON Web Tokens and I've managed to generate the token with the correct claims, but I'm having trouble parsing the claims my subsequent requests.

My token looks something like this

{
    "Raw": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...",
    "Method": {
        "Name": "RS256",
        "Hash": 5
    },
    "Header": {
        "alg": "RS256",
        "typ": "JWT"
    },
    "Claims": {
        "foo": "bar"
    },
    "Signature": "",
    "Valid": false
}

and my goal is to parse the foo value from the claims. I'm using this package for working with web tokens.

I'm able to successfully extract the token from the Authorization header, but when I try this

token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
    return apiKeyPair.PublicKey, nil
})

if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
    return claims, nil
} else {
    return nil, err
}

I'm not getting an error here, but when I try to access foo from the claims like this

claims, err := GetWebTokenClaims(r)
if err != nil {
    return
}

foo := claims["foo"]

I get nil. I've tried a number of little tweaks to this structure–like using custom claims with the ParseWithClaims() method–but for the life of me I can't get this simple thing working.

Not sure where to go from here or what other info might be relevant, any help is appreciated!

Define a type that describes the claims and that includes the jwt.StandardClaims:

type myClaims struct {
    Foo    string   `json:"foo"`
    jwt.StandardClaims
}

If you have a JWT with this data

{
  "foo": "bar"
}

you can access the claims like this:

parsedToken, err := jwt.Parse(signed, keyfunc)
if err != nil {
    fmt.Println("token is invalid: ", err)
} else {
    claims := parsedToken.Claims.(jwt.MapClaims)
    fmt.Println(claims["foo"])
}