【问题标题】:gmail api token expired how to get new one?gmail api令牌过期如何获得新的?
【发布时间】:2021-04-21 17:08:34
【问题描述】:

我刚刚实现了 Gmail OAuth 服务,并且可以发送电子邮件,但是过了一段时间它应该过期了,我只是想知道如何自动更新它?

这里。是我的代码:

func OAuthGmailService() {
    config := oauth2.Config{
       ClientID:     "XXXXXX",
       ClientSecret: "XXXXXX",
       Endpoint:     google.Endpoint,
       RedirectURL:  "http://127.0.0.1",
    }
 
    token := oauth2.Token{
       AccessToken:  "XXXXXX",
       RefreshToken: "XXXXXX",
       TokenType:    "Bearer",
       Expiry: time.Now(),
    }
    

    var tokenSource = config.TokenSource(context.Background(), &token)
 
    srv, err := gmail.NewService(context.Background(), option.WithTokenSource(tokenSource))
    if err != nil {
       log.Printf("Unable to retrieve Gmail client: %v", err)
    }
 
    GmailService = srv
    if GmailService != nil {
       fmt.Println("Email service is initialized \n")
    }

 }

【问题讨论】:

  • 我投票结束这个问题,因为它是一个与客户服务相关的问题。直接联系供应商寻求帮助。对于有关您在该网站上的特定帐户的问题,我们无法提供帮助。
  • 重新投票,因为它与客户服务无关。然而,它确实与如何将 Google Oauth 与 Go 编程语言一起使用以及了解 Oauth2 如何与刷新令牌一起工作有关。访问令牌在一小时后过期,您应该在需要时使用刷新令牌来请求新的访问令牌。一。我无法帮助您执行此操作,但这可能会有所帮助daimto.com/google-3-legged-oauth2-flow
  • 您可以尝试在Google apis go client library 中寻找帮助您了解如何在 go 中执行此操作的文档。

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


【解决方案1】:

首先寻找本地令牌

在快速入门文档中:

https://developers.google.com/gmail/api/quickstart/go

getClient 函数中:

func getClient(config *oauth2.Config) *http.Client {
        // The file token.json stores the user's access and refresh tokens, and is
        // created automatically when the authorization flow completes for the first
        // time.
        tokFile := "token.json"
        tok, err := tokenFromFile(tokFile) // First seeking local token
        if err != nil {
                tok = getTokenFromWeb(config)
                saveToken(tokFile, tok)
        }
        return config.Client(context.Background(), tok)
}

这应该足以使用刷新令牌并注意需要后续登录。

我无法通过您的代码判断此逻辑是否在您的程序中。

如果没有,请查看:

https://developers.google.com/identity/protocols/oauth2#expiration

有关您的刷新令牌如何过期的更多信息,例如:

用户帐户已超过授予(实时)刷新令牌的最大数量。

【讨论】:

    【解决方案2】:

    可能有点老了,但由于我也在搜索类似的问题,所以我也在这里回答。

    你需要在Gmail API的快速入门基础上添加自动创建Access Token的功能,就像上面@iansedano的回答一样。

    之后,使用选项 option.WithHTTPClient(client) 而不是 WithTokenSource

    你可以在这里查看我的研究:Gmail API with Go and gmail.NewService invalid memory address or nil pointer dereference

    【讨论】:

      猜你喜欢
      • 2016-08-28
      • 2021-02-05
      • 2018-07-29
      • 2019-08-05
      • 2016-11-30
      • 2021-03-07
      • 2014-10-09
      • 1970-01-01
      • 2016-07-12
      相关资源
      最近更新 更多