2 回答

TA贡献1872条经验 获得超4个赞
在深入研究了Google 的 Oauth 协议和OAuth2之后,我发现 Golang 中的库并没有完全遵循 google 的 OAuth2 协议。
谷歌规范中的流程:在 HTTP 客户端(使用服务帐户)中生成和签署 JWT --> 发送到谷歌的服务器 --> 获取新的签名 JWT --> 将新令牌用于其他请求
Golang lib:生成并签署 JWT --> 将此令牌用于其他请求
令人惊讶的是,Nodejs 库正确处理了流程,而 Golang 库却没有。我将我的调查总结为一篇博文。
对于那些想要简短回答的人,这是我的实现(我将一些部分移到了公共仓库中):
import (
"context"
"fmt"
"io/ioutil"
"os"
"github.com/CodeLinkIO/go-cloudfunction-auth/cloudfunction"
"golang.org/x/oauth2/google"
)
func main() {
baseUrl := "your-cloudfunction-baseurl"
ctx := context.Background()
targetAudience := baseUrl
credentials, err := google.FindDefaultCredentials(ctx)
if err != nil {
fmt.Printf("cannot get credentials: %v", err)
os.Exit(1)
}
jwtSource, err := cloudfunction.JWTAccessTokenSourceFromJSON(credentials.JSON, targetAudience)
if err != nil {
fmt.Printf("cannot create jwt source: %v", err)
os.Exit(1)
}
client := cloudfunction.NewClient(jwtSource)
res, err := client.Get(baseUrl + "/cloudfunction-sub-page")
if err != nil {
fmt.Printf("cannot fetch result: %v", err)
os.Exit(1)
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Printf("cannot read response: %v", err)
os.Exit(1)
}
println(string(body))
}

TA贡献1802条经验 获得超6个赞
我编写了一个名为token-generator的开源应用程序。它在 Go 中,我生成签名身份令牌,以便能够调用私有 Cloud Run 和 Cloud Function。
随意使用它或复制您自己的应用所需的核心代码!如果您愿意,我们可以在这里讨论或在 GitHub 上打开一个问题。
- 2 回答
- 0 关注
- 161 浏览
添加回答
举报