亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

訪問令牌在 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條經驗 獲得超13個贊

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

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

在那里傳遞你的舊令牌,updatedToken 將反映更新的訪問令牌和到期



查看完整回答
反對 回復 2023-04-24
  • 1 回答
  • 0 關注
  • 124 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號