【问题标题】:how to use google api library oauth2? I have id token and access token如何使用谷歌 api 库 oauth2?我有 id 令牌和访问令牌
【发布时间】:2020-12-05 09:40:58
【问题描述】:

如果我从前端对用户进行了身份验证,我如何授权访问后端(使用 go google 库)?前端认证,我有access_token或者id_token

  • 有没有办法将id_token 转换为access token
  • 有没有办法使用id_token 运行calendar.NewService
  • 有没有办法使用access_token 运行calendar.NewService

我的设置

在扩展中,我都做了:

  • 我可以从 GCP creds oauth2“chrome app”获取“访问令牌”。
  • 从 GCP creds oauth2“web app”,我可以得到“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()

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

【问题讨论】:

  • 您必须知道访问令牌通常会在 60 分钟后过期,请考虑设置 offline access。更一般地说,您的身份验证需要遵循 Google 授权的流程之一。首先估计哪个是您的scenario,然后阅读相应 Auth 协议的文档,例如OAuth 2.0 for Client-side Web Applications.
  • 感谢您的提示。但这不是我要找的。我想使用 go api 库。给定访问令牌,我无法弄清楚如何使用它。
  • thisnode.js 实现与您的案例相关?
  • 如果您有一个有效的访问令牌,是什么阻止您将它与standard procedure 一起使用?
  • 我尝试的原始方法只给了我访问令牌。使用 chrome 标识。只有访问令牌是不够的。完整的令牌(访问、刷新、到期和类型)。所以我找到了另一种获取身份验证代码的方法,而不是后来才意识到“代码”是身份验证代码。他们的文档很烂。希望我们可以编辑和改进它。

标签: go google-api google-oauth gmail-api google-signin


【解决方案1】:

抱歉,文档没有示例。是的,我尝试了各种变体,终于搞定了。

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

【讨论】:

    猜你喜欢
    • 2014-10-17
    • 2013-07-20
    • 2021-01-29
    • 2012-08-13
    • 2017-04-12
    • 2014-01-11
    • 2021-08-12
    • 2013-03-23
    • 2012-05-24
    相关资源
    最近更新 更多