登录
首页 >  Golang >  Go问答

服务帐户在Golang Oauth2中返回的刷新令牌为空字符串

来源:stackoverflow

时间:2024-02-06 14:09:21 481浏览 收藏

学习Golang要努力,但是不要急!今天的这篇文章《服务帐户在Golang Oauth2中返回的刷新令牌为空字符串》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!

问题内容

当我尝试使用服务器到服务器身份验证通过服务帐户进行身份验证时,我遇到了 google/oauth2 包的问题。 google 使用带有空刷新令牌字符串的令牌结构进行响应,令牌将在 1 小时后过期,但我无法刷新,因为我没有刷新令牌。 这是我正在使用的代码片段:

/*
import(
    "github.com/google/go-containerregistry/pkg/authn"
    gcr "github.com/google/go-containerregistry/pkg/name"
    "github.com/google/go-containerregistry/pkg/v1/remote"
)

*/
data, err := ioutil.ReadFile(fmt.Sprintf("%s/%s", path, serviceAccountFilePath))
if err != nil {
   log.Fatalf("Failed to read GCP service account key file: %s", err)
}
ctx := context.Background()
fmt.Println(scopes)
creds, err := google.CredentialsFromJSON(ctx, data, scopes...)

if err != nil {
   log.Fatalf("Failed to load GCP service account credentials: %s", err)

}
t, _ := creds.TokenSource.Token()
fmt.Println(t.Expiry.Sub(time.Now()).String(), t.RefreshToken, ">>>")

r, err := gcr.NewRegistry("https://gcr.io")
if err != nil {
 log.Fatalf("failed to ping registry: %s", err)
}
authToken := authn.FromConfig(authn.AuthConfig{
    RegistryToken: t.AccessToken,
})

repo, err := gcr.NewRepository(fmt.Sprintf("%s/%s", urlPrefix, imageName))
repo.Registry = r
list, err := remote.List(repo, remote.WithAuth(authToken))

我在使用服务帐户进行身份验证时尝试了不同的方法,例如配置和 jwt,但仍然得到相同的结果。


正确答案


感谢@dalmto的提示,我解决了问题。

因此,解决此类问题的方法是不使用 google.credentialsfromjson() 函数中的凭据,如果将服务帐户传递给该函数,则将返回令牌源而不刷新令牌,这意味着您可以'当您的令牌稍后再次过期时,请不要刷新您的令牌。此外,预测并重新验证以生成新令牌对我来说不起作用(不知道为什么)。

所以我必须通过这个函数将服务帐户的 json 转换为 jwt

scopes := []string{"https://www.googleapis.com/auth/cloud-platform"}
tokenSource, err := google.JWTAccessTokenSourceWithScope(serviceAccountFileBytes, scopes...)

这个之所以有效,是因为它通过 service_account 的属性(例如客户电子邮件、client_id 和 private_key)在内部创建 jwt 令牌,因为 gcp 允许我们创建本地 jwt 令牌并对其进行编码。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《服务帐户在Golang Oauth2中返回的刷新令牌为空字符串》文章吧,也可关注golang学习网公众号了解相关技术文章。

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