登录
首页 >  Golang >  Go问答

使用 Golang 解析来自 Google OAuth 2.0 的 JWT 令牌的方法

来源:stackoverflow

时间:2024-02-16 18:27:23 297浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《使用 Golang 解析来自 Google OAuth 2.0 的 JWT 令牌的方法》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

我正在取回有效的:

https://developers.google.com/identity/gsi/web/reference/js-reference#credentialresponse

按照以下步骤操作后:

https://developers.google.com/identity/gsi/web/guides/migration

即这一切都正常:


    

我使用有效的 credentialresponse base64 编码 jwt 调用 handlecredentialresponse

144712​​361111

我可以在 go 的后端执行此操作:

tokens := strings.split(token, ".")
  base64url := tokens[1]
  decoded, _ := base64.stdencoding.decodestring(base64url)
  jsonstring := string(decoded) + "}"

我会得到一些不错的 json,其中包含用户名和电子邮件,但 json 缺少最后一个结束 }

当我尝试使用时:

func parseJwt(tokenString string) {
  secret := os.Getenv("GOOGLE_SECRET")

  token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
    if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
      return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
    }
    return []byte(secret), nil
  })

  if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
    fmt.Println(claims["email"], claims)
  } else {
    fmt.Println(err)
  }
}

它总是因无效的 jwt 错误而出现恐慌。我尝试过在 strings.split(".")[1] 逻辑之前和之后、base64 之前和之后使用令牌调用 parsejwt ,但似乎没有任何东西可以解析它。

我上面的代码在生产中添加了结尾 } 并且它正在“工作”,但它并没有真正检查秘密以确保 jwt 有效。我该如何解决这个问题?


正确答案


好的,找到答案了!它与您所做的oauth cred secret 无关。您使用公共 google 密钥进行验证:

https://www.googleapis.com/oauth2/v3/certs

来自:

the id token is properly signed by google. use googles
public keys (available in jwk or pem format) to verify
the tokens signature. these keys are regularly rotated;
examine the cache-control header in the response to
determine when you should retrieve them again.

上面是 jwk 格式,您应该点击该 url 并将 json 缓存一段时间,该时间段在 cache-control 标头中定义。

下面是使用这些密钥验证 jwt 的工作示例:

https://github.com/MicahParks/keyfunc/blob/master/examples/json/main.go

import (
  "encoding/json"
  "log"
  "github.com/golang-jwt/jwt/v5"
  "github.com/micahparks/keyfunc/v2"
)

jwksjson := json.rawmessage(thatjson)
jwks, _ := keyfunc.newjson(jwksjson)
token, _ := jwt.parse(yourjwtfromgoogle, jwks.keyfunc)
if token.valid {
  claims := token.claims.(jwt.mapclaims)
  //claims["email"]  
  //claims["given_name"]
  //claims["family_name"]
}

以下是将该 json 缓存 24 小时的逻辑:

func writeGoogleFile(file string) string {
  // https://developers.google.com/identity/gsi/web/guides/verify-google-id-token
  // cache-control: public, max-age=18702, must-revalidate, no-transform
  jsonString, code := network.GetTo("https://www.googleapis.com/oauth2/v3/certs", "")
  if code == 200 {
    ioutil.WriteFile(file, []byte(jsonString), 0644)
    return jsonString
  }
  return ""
}
func getGoogleCerts() string {
  file := "/certs/google_jwt_oauth.json"
  fileInfo, err := os.Stat(file)
  if err != nil {
    return writeGoogleFile(file)
  }
  lastModified := fileInfo.ModTime().Unix()
  if time.Now().Unix()-lastModified > 86400 {
    return writeGoogleFile(file)
  }
  b, _ := ioutil.ReadFile(file)
  return string(b)
}

以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>