问题描述
鉴于ive从前端对用户进行了身份验证,我如何授权访问后端(带有go google libary)?前端身份验证,我有access_token
或id_token
。
- 是否可以将
id_token
转换为access token
? - 是否可以使用
id_token
来运行calendar.NewService
? - 是否可以使用
access_token
来运行calendar.NewService
?
我的设置
在扩展程序中,我同时做到了:
- 从GCP认证oauth2“ chrome应用程序”中,我可以获得“访问令牌”。
- 从GCP认证oauth2“网络应用”中,我可以获取“ id令牌”。
在后端,将Go Google api库用于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_token
或access_token
来使用此库。到目前为止,我可以使用access_token进行curl请求,但是不使用该库。这个Google图书馆有办法吗?
尝试
- 我已经读过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,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,token))) res,err := calService.Events.List("myemail@gmail.com").Do()
“代码”不重要,因为我不想通过浏览器链接对用户进行身份验证。此时,用户应假定已经从前端进行了身份验证。但这也不起作用。
解决方法
很抱歉,文档没有示例。是的,我尝试了各种变化,最后得到了它。
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)