Google Calendar API invalid_grant 获取 token (Golang)

标签 go google-calendar-api google-oauth access-token bad-request

我正在尝试检索访问 token ,以便使用 Oauth2 对用户进行身份验证。我主要使用在谷歌的 HOW-TO 页面上找到的代码,用于将 Calendar API 与 golang 结合使用。问题是每当我尝试获取 token 时,谷歌都会发回:

Response: {
 "error" : "invalid_grant"
}

出现错误 oauth2: cannot fetch token: 400 Bad Request

正如我所说,我正在使用从 google 的 howto 中获取的一些代码,只是稍作修改以满足我的需要。

//Somewhere...
authURL = config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)

//Somewhere else...
func getClient(ctx context.Context, config *oauth2.Config, code string) *http.Client {
    cacheFile := tokenCacheFile()

    tok, err := tokenFromFile(cacheFile)
    if err != nil {
        log.Printf("Google auth code not cached. Obtaining from the web...")
        tok, err = getTokenFromWeb(code) //This returns an error
        if err == nil {
            log.Printf("Got token!")
            saveToken("calendar-go-quickstart.json", tok)
        } else { //Prevent saving token when error
            log.Printf("Couldn't get OAUTH2 token! %s", err)
        }
    }
    return config.Client(ctx, tok)
}

错误发生在“getTokenFromWeb(code)”(如果我理解正确,code 必须是一些随机字符串,无论其值如何,它只需要是整个过程都一样)。 这是有问题的代码:

func getTokenFromWeb(code string) (*oauth2.Token, error) {
    tok, err := config.Exchange(context.Background(), code)
    return tok, err
}

执行后,我看到的是那个错误。我什至在尝试复制粘贴谷歌自己的示例代码时遇到了完全相同的错误!
任何的想法?网上实在是找不到解决方法。

额外细节:使用 IRIS 网络框架;使用最新版本的 google calendar api;使用最新版本的 Golang;我在 Google Cloud Console 上为 OAuth2 创建了一个客户端 ID;该网站已获得受信任的 SSL 证书;它监听端口 80 (HTTP) 和 4433 (HTTPS);

最佳答案

这是谷歌的例子:

// getTokenFromWeb uses Config to request a Token.
// It returns the retrieved Token.
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
  authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
  fmt.Printf("Go to the following link in your browser then type the "+
"authorization code: \n%v\n", authURL)

  var code string
  if _, err := fmt.Scan(&code); err != nil {
    log.Fatalf("Unable to read authorization code %v", err)
  }
  ...
}

code 是访问显示链接后给予用户的授权码。 fmt.Scan() 将扫描用户的输入。

如果您要代表不同的用户,则必须执行与此示例类似的操作。 如果您只是以您自己的身份行事,那么您应该能够在没有代码的情况下以您自己的身份进行身份验证。

无论哪种方式,code 都不能是随机字符串。

关于Google Calendar API invalid_grant 获取 token (Golang),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45493523/

相关文章:

php - Google Oauth 2.0 检查我的刷新访问 token 是否过期

windows - Go 和 COM/ActiveX

go - 如何从 URL 检索域?

Golang 相当于 Java 的 SHA256withRSA

Javascript 解析器 Google 日历 JSON Feed 与重复事件

plone - 在 Plone 站点中显示 Google 日历

oauth - 谷歌 API 休息 : Exchange authorization code for refresh and access tokens - error 404

file - 在 Go 中读取/写入文件的正确方法

google-app-engine - Google 日历与 Google App Engine 的集成

youtube - 使用JavaScript将视频上传到youtube,而无需登录google