Gmail API令牌过期如何获得新令牌?

人气:424 发布:2022-10-16 标签: google-api google-oauth gmail-api go

问题描述

我刚刚实现了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 
")
    }

 }

推荐答案

首先查找本地令牌

在快速入门文档中:

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

有关刷新令牌如何过期的详细信息,例如,它可能是:

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

309