为了账号安全,请及时绑定邮箱和手机立即绑定

访问令牌在 GO 中过期时如何使用谷歌刷新令牌?

访问令牌在 GO 中过期时如何使用谷歌刷新令牌?

Go
芜湖不芜 2023-04-24 16:14:35
我刚开始使用 Google 服务,目前正在尝试从 gmail API 读取电子邮件。但是,当访问令牌过期时,我陷入了这种情况。我有第一次身份验证的刷新令牌,但是,一些线程说访问令牌在过期时会自动刷新。但是我的没有。我不知道我哪里错了。这是我目前的代码。// get saved token from database / anywhere elsefunc getCachedToken() *oauth2.Token {    token := new(oauth2.Token)    token.AccessToken = "xxxxxxxx"    token.RefreshToken = "xxxxxx"    token.TokenType = "Bearer"    return token}func refreshToken(config *oauth2.Config, token *oauth2.Token) *http.Client {    return config.Client(context.Background(), token)}// Retrieve a token, saves the token, then returns the generated client.func getClient(config *oauth2.Config) *http.Client {    tok := getTokenFromWeb(config)    fmt.Println(tok.RefreshToken)    fmt.Println(tok.AccessToken)    fmt.Println(tok.Expiry)    fmt.Println(tok.TokenType)    return config.Client(context.Background(), tok)}func main() (string, error) {    b, err := ioutil.ReadFile("credentials.json")    if err != nil {        log.Fatalf("Unable to read client secret file: %v", err)    }    // If modifying these scopes, delete your previously saved token.json.    config, err := google.ConfigFromJSON(b, gmail.GmailReadonlyScope, gmail.GmailSendScope, gauth.UserinfoEmailScope, gauth.UserinfoProfileScope)    if err != nil {        log.Fatalf("Unable to parse client secret file to config: %v", err)    }    token := getCachedToken()    accessToken := token.AccessToken    client := refreshToken(config, token)    if err != nil {        log.Fatalf("Unable to retrieve oauth client: %v", err)    }    if accessToken != token.AccessToken {        fmt.Println(token.RefreshToken)        fmt.Println(token.AccessToken)        fmt.Println(token.Expiry)        fmt.Println(token.TokenType)    } //THE TOKEN IS NOT CHANGED HERE WHEN THE ACCESS TOKEN EXPIRED    srv, err := gmail.New(client)    if err != nil {        log.Fatalf("Unable to retrieve Gmail client: %v", err)    }
查看完整描述

1 回答

?
萧十郎

TA贡献1815条经验 获得超12个赞

oauth2.Config有一个可以自动刷新令牌的功能。

updatedToken, err := config.TokenSource(context.TODO(), token).Token()

在那里传递你的旧令牌,updatedToken 将反映更新的访问令牌和到期



查看完整回答
反对 回复 2023-04-24
  • 1 回答
  • 0 关注
  • 81 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信