Home > database >  How to iterate over the decoded claims of a Jwt token in Go?
How to iterate over the decoded claims of a Jwt token in Go?

Time:07-28

I am referring to this post (claim values of Jwt token

Now I want to iterate over these values using loop.

for _, v := range claims["scope"]{
      fmt.Println(v)
}

However, when I try to loop over this claims ["scope"], I got an error message saying that:

"cannot range over claims["scope"] (type interface {})".

How to iterate over these claims["scope"] values? Also, is it possible to convert it to other forms, like string array or json, to iterate over it?

Thanks.

CodePudding user response:

There are a few ways you can handle this; the simplest is probably to let the library decode things for you (playground)

type MyCustomClaims struct {
    Scope []string `json:"scope"`
    jwt.StandardClaims
}

claims := MyCustomClaims{}
_, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) {
    return []byte(sharedKey), nil
})
if err != nil {
    panic(err)
}

for _, s := range claims.Scope {
    fmt.Printf("%s\n", s)
}

If you want to stick with the approach used in your question then you will need to use type assertions (playground - see the json docs for more info on this):

var claims jwt.MapClaims
_, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) {
    return []byte(sharedKey), nil
})
if err != nil {
    panic(err)
}

scope := claims["scope"]
if scope == nil {
    panic("no scope")
}
scopeSlc, ok := scope.([]any)
if !ok {
    panic("scope not a slice")
}

for _, s := range scopeSlc {
    sStr, ok := s.(string)
    if !ok {
        panic("slice member not a string")
    }
    fmt.Println(sStr)
}
  • Related