gpt4 book ai didi

go - 如何使用 google api 库 oauth2?我有 id token 和访问 token

转载 作者:行者123 更新时间:2023-12-01 20:22:05 25 4
gpt4 key购买 nike

鉴于我从前端对用户进行了身份验证,我如何授权对后端的访问(使用 go google libary)?前端认证,我有access_tokenid_token .

  • 有没有办法转换id_tokenaccess token ?
  • 有没有办法使用id_token运行 calendar.NewService ?
  • 有没有办法使用access_token运行 calendar.NewService ?

  • 我的设置
    在扩展中,我做了两个:
  • 从 GCP creds oauth2“chrome app”我可以获得“访问 token ”。
  • 从 GCP creds oauth2“网络应用程序”,我可以获得“id token ”。

  • 在后端,使用 go google api library for calendar
    config := &oauth2.Config{...}
    // ...
    token, err := config.Exchange(ctx, ...)
    calendarService, err := calendar.NewService(ctx, option.WithTokenSource(config.TokenSource(ctx, token)))
    res, err := calService.Events.List("myemail@gmail.com").Do()
    我不知道如何使用我的 id_tokenaccess_token使用这个库。到目前为止,我可以使用 access_token 执行 curl 请求,但不使用此库。这个谷歌图书馆有办法吗?
    尝试
  • 我读过 cross identity ,只要您指向同一个项目中的同一个客户端 ID,就可以了。但我不断收到,token expired or not found
  • 我听说 id_token 只是 jwt。所以我试过了,但我不能得到正确的类型,所以甚至不能运行它。

  • jwt, err := google.JWTConfigFromJSON(g.key, gmail.GmailReadonlyScope)     
    jwt.Subject = "myname@gmail.com" //impersonate user
    service, err := calendar.NewService(ctx, option.WithHTTPClient(jwt.Client(ctx)))

  • 尝试使用 oauth2 key.json

  • serviceAccountKey, err := ioutil.ReadFile("oauth2_webapp.json")  
    conf, err := google.ConfigFromJSON(serviceAccountKey, calendar.CalendarReadonlyScope)
    token, err := conf.Exchange(ctx,"code") // code seems like another method
    calendarService, err := calendar.NewService(ctx,
    option.WithTokenSource(config.TokenSource(ctx, token)))
    res, err := calService.Events.List("myemail@gmail.com").Do()

    “代码”应该无关紧要,因为我不想通过浏览器链接对用户进行身份验证。此时用户应该假设已经从前端进行了身份验证。但这也不起作用。

    最佳答案

    抱歉,文档没有示例。是的,我尝试了变体,终于得到了它。
    id_token 没用。
    在访问 token 之前,我有一个 authCode。我希望在他们的文档中,他们说的是 authcode 而不是代码。我只是将身份验证代码从前端传递到后端。因为我是新手,请删除任何 html 编码。即(%2f =>/)。这也是我无法得到它的原因之一。
    下面的作品:

    authCode := "4/3AGEkPVEN9O**70ish char***G0uOPYtQWkUSc" 
    // authcode was html encoded which the conf.Exchange needed a decoded version.
    saKey, err := ioutil.ReadFile("oauth2_webapp.json")
    conf, err := google.ConfigFromJSON(saKey, calendar.CalendarReadonlyScope)
    token, err := conf.Exchange(ctx,authCode)

    关于go - 如何使用 google api 库 oauth2?我有 id token 和访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63430755/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com