如何在Go中迭代Jwt令牌的解码声明?

huangapple go评论111阅读模式
英文:

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

问题

我正在参考这篇帖子(https://stackoverflow.com/questions/45405626/how-to-decode-a-jwt-token-in-go)来获取Jwt令牌的声明字段。以下是我根据这篇帖子使用的代码:

  1. tokenString := "<YOUR TOKEN STRING>"
  2. claims := jwt.MapClaims{}
  3. token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
  4. return []byte("<YOUR VERIFICATION KEY>"), nil
  5. })
  6. // ... 错误处理
  7. // 处理解码后的声明
  8. for key, val := range claims {
  9. fmt.Printf("Key: %v, value: %v\n", key, val)
  10. }

我成功获取了这些声明及其值。然而,在这个Jwt令牌中,有一个称为'scope'的声明字段,它具有字符串数组值,如'['openId','username','email']。

现在我想使用循环遍历这些值。

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

然而,当我尝试循环遍历这个claims["scope"]时,我收到了一个错误消息:

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

如何遍历这些claims["scope"]的值?另外,是否可以将其转换为其他形式,比如字符串数组或JSON,以便进行遍历?

谢谢。

英文:

I am referring to this post (https://stackoverflow.com/questions/45405626/how-to-decode-a-jwt-token-in-go) to get the claim fields of a Jwt token. Here are the code that I used based on this post:

  1. tokenString := &quot;&lt;YOUR TOKEN STRING&gt;&quot;
  2. claims := jwt.MapClaims{}
  3. token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
  4. return []byte(&quot;&lt;YOUR VERIFICATION KEY&gt;&quot;), nil
  5. })
  6. // ... error handling
  7. // do something with decoded claims
  8. for key, val := range claims {
  9. fmt.Printf(&quot;Key: %v, value: %v\n&quot;, key, val)
  10. }

I managed to get those claims and its values. However, in this Jwt token, there is a claim field called 'scope', and it has a string array values, like '['openId','username','email'].

如何在Go中迭代Jwt令牌的解码声明?

Now I want to iterate over these values using loop.

  1. for _, v := range claims[&quot;scope&quot;]{
  2. fmt.Println(v)
  3. }

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.

答案1

得分: 2

有几种方法可以处理这个问题;最简单的方法可能是让库为您解码(playground

  1. type MyCustomClaims struct {
  2. Scope []string `json:"scope"`
  3. jwt.StandardClaims
  4. }
  5. claims := MyCustomClaims{}
  6. _, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) {
  7. return []byte(sharedKey), nil
  8. })
  9. if err != nil {
  10. panic(err)
  11. }
  12. for _, s := range claims.Scope {
  13. fmt.Printf("%s\n", s)
  14. }

如果您想坚持使用您问题中使用的方法,那么您需要使用类型断言(playground - 有关更多信息,请参阅json文档):

  1. var claims jwt.MapClaims
  2. _, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) {
  3. return []byte(sharedKey), nil
  4. })
  5. if err != nil {
  6. panic(err)
  7. }
  8. scope := claims["scope"]
  9. if scope == nil {
  10. panic("no scope")
  11. }
  12. scopeSlc, ok := scope.([]interface{})
  13. if !ok {
  14. panic("scope not a slice")
  15. }
  16. for _, s := range scopeSlc {
  17. sStr, ok := s.(string)
  18. if !ok {
  19. panic("slice member not a string")
  20. }
  21. fmt.Println(sStr)
  22. }
英文:

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

  1. type MyCustomClaims struct {
  2. Scope []string `json:&quot;scope&quot;`
  3. jwt.StandardClaims
  4. }
  5. claims := MyCustomClaims{}
  6. _, err := jwt.ParseWithClaims(tokenString, &amp;claims, func(token *jwt.Token) (interface{}, error) {
  7. return []byte(sharedKey), nil
  8. })
  9. if err != nil {
  10. panic(err)
  11. }
  12. for _, s := range claims.Scope {
  13. fmt.Printf(&quot;%s\n&quot;, s)
  14. }

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):

  1. var claims jwt.MapClaims
  2. _, err := jwt.ParseWithClaims(tokenString, &amp;claims, func(token *jwt.Token) (interface{}, error) {
  3. return []byte(sharedKey), nil
  4. })
  5. if err != nil {
  6. panic(err)
  7. }
  8. scope := claims[&quot;scope&quot;]
  9. if scope == nil {
  10. panic(&quot;no scope&quot;)
  11. }
  12. scopeSlc, ok := scope.([]any)
  13. if !ok {
  14. panic(&quot;scope not a slice&quot;)
  15. }
  16. for _, s := range scopeSlc {
  17. sStr, ok := s.(string)
  18. if !ok {
  19. panic(&quot;slice member not a string&quot;)
  20. }
  21. fmt.Println(sStr)
  22. }

huangapple
  • 本文由 发表于 2022年7月28日 09:46:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/73146348.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定