登录
首页 >  Golang >  Go问答

无法获取 Oauth2 TokenSource 来刷新从存储中检索到的令牌

来源:stackoverflow

时间:2024-04-25 08:00:36 363浏览 收藏

对于一个Golang开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《无法获取 Oauth2 TokenSource 来刷新从存储中检索到的令牌》,主要介绍了,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!

问题内容

用户授权 google 日历后,nodejs 服务会将代码、accesstoken 和 refreshtoken 保存到存储中。

尝试使用相同的令牌来使用用 go 编写的不同后端服务来访问用户的日历。 当 accesstoken 有效时,数据是可以访问的,但是当 accesstoken 过期时,在尝试访问事件时,无法获取 config.exchange() 或 config.tokensource() 来提供有效的新令牌,即使令牌有效,得到错误:

错误 401:凭据无效,autherror 退出状态 1

tok, err := config.tokensource(ctx, token).token() // token is previous valid token
 if err != nil {
    log.fatalf("unable to retrieve token from web: %v", err)
 }

还尝试用代码交换新令牌,但没有帮助

400 错误请求 回复: { “错误”:“无效的授权”, "error_description": "授权代码格式错误。" }

tok, err := config.exchange(context.todo(), in)
if err != nil {
    log.fatalf("unable to retrieve token from web: %v", err)
}

尝试使用calendar.newservice进行访问

srv, _ := calendar.newservice(ctx, option.withtokensource(config.tokensource(ctx, tok)))

如何获取可以离线访问而无需其他服务的用户干预的令牌?

更新:将令牌存储到 redis - redisjson,但仍然无法获得新的 accesstoken。这是我传递有效令牌的完整函数。它仅在 accesstoken 到期之前有效。

func GetGoogleCalendarEvents(token *oauth2.Token, userid string) *calendar.Events {
tok := &oauth2.Token{}
var config *oauth2.Config
ctx := context.Background()

b, err := ioutil.ReadFile("credentials.json")
if err != nil {
    log.Fatalf("Unable to read client secret file: %v", err)
}

config, err = google.ConfigFromJSON(b, calendar.CalendarScope) //calendar.CalendarScope)
if err != nil {
    log.Fatalf("Unable to parse client secret file to config: %v", err)
}

tok = token

if token.Expiry.Before(time.Now()) {

    tokenSource := config.TokenSource(ctx, token) //oauth2.NoContext

    newToken, err := tokenSource.Token()
    if err != nil {
        log.Fatalln(err)
    }

    if tok.AccessToken != newToken.AccessToken {
        SetAuthCredToCache(userid, tok)
        tok = newToken
        fmt.Println(newToken)
    }
}

fmt.Println(tok.Expiry, tok.Valid(), tok.Type(), tok.RefreshToken, tok.TokenType)

srv, _ := calendar.NewService(ctx, option.WithTokenSource(config.TokenSource(ctx, tok)))

t := time.Now().Format(time.RFC3339)

events, err := srv.Events.List("primary").ShowDeleted(true).
    SingleEvents(true).TimeMin(t).OrderBy("startTime").Do()

if err != nil {
    log.Fatalf("Unable to retrieve next ten of the user's events: %v", err)
}
return events

}


解决方案


这是一个解组问题。

当从 Node 保存令牌时,它将到期时间序列化为 "expiry_date" ,而 Go 令牌的 json 表示形式仅为 "expiry" 。将对象的其余部分解组到 oauth2.Token 对象并向该对象添加到期时间解决了问题。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>