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 關注
- 151 瀏覽
添加回答
舉報