Google日历API无效\u授权获取令牌(Golang)

Google日历API无效\u授权获取令牌(Golang),go,google-calendar-api,google-oauth,access-token,bad-request,Go,Google Calendar Api,Google Oauth,Access Token,Bad Request,我试图检索一个访问令牌,以便使用Oauth2对用户进行身份验证。我使用的大部分代码都是在google的操作页面上找到的,用于在golang中使用日历API。问题是,每当我试图获得代币时,谷歌都会发回以下信息: Response: { "error" : "invalid_grant" } 错误为oauth2:无法获取令牌:400错误请求 正如我所说,我使用的一些代码来自google的howto,只是稍微修改一下以满足我的需要 //Somewhere... authURL = config.A

我试图检索一个访问令牌,以便使用Oauth2对用户进行身份验证。我使用的大部分代码都是在google的操作页面上找到的,用于在golang中使用日历API。问题是,每当我试图获得代币时,谷歌都会发回以下信息:

Response: {
 "error" : "invalid_grant"
}
错误为
oauth2:无法获取令牌:400错误请求

正如我所说,我使用的一些代码来自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)”(如果我理解正确,代码必须是某个随机字符串,无论其值如何,它只需要在整个过程中保持相同)。 这是有问题的代码:

func getTokenFromWeb(code string) (*oauth2.Token, error) {
    tok, err := config.Exchange(context.Background(), code)
    return tok, err
}
执行之后,我看到的是错误。我甚至在尝试复制粘贴google自己的示例代码时也遇到了完全相同的错误
有什么想法吗?我真的无法在网上找到解决方案


额外细节:使用IRIS web框架;使用最新版本的谷歌日历api;使用最新版本的Golang;我已经在谷歌云控制台上为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
都不能是随机字符串。

Ah,因此它被发送到客户端。。但是我如何找回它呢?我猜它是通过GET请求作为URL参数发送到web服务器的,所以我只需要在用户请求重定向回?后从用户请求中读取它?。我会尽快检查,我没有诚实地检查参数。谢谢,再试一次后,我看到代码作为查询参数发送。现在我有另一个问题。(立即编辑问题)在编辑之前,代码保留在url栏中并在每次单击时刷新,但url保留在
https://myside.com?state=state-令牌和代码=c/odethatchchangeseverytime