我正在嘗試從在Google App Engine Go 1.11 Standard Environment上運行的應用程序通過 API 訪問 google 電子表格。不幸的是,應用程序無法讀取此電子表格。我在Spreadsheets.Values.Get通話中遇到下一個錯誤:googleapi: Error 403: Request had insufficient authentication scopes., forbidden示例代碼// Sample app showing issue with GAE -> google spreadsheetspackage mainimport ( "context" "fmt" "log" "net/http" "os" "cloud.google.com/go/compute/metadata" "golang.org/x/oauth2/google" "google.golang.org/api/sheets/v4")func main() { http.HandleFunc("/", indexHandler) // [START setting_port] port := os.Getenv("PORT") if port == "" { port = "8080" log.Printf("Defaulting to port %s\n", port) } // let's check app engine instance scopes scopes, _ := metadata.Get("instance/service-accounts/default/scopes") log.Printf("[DEBUG] metadata scopes: %s.\n", scopes) log.Printf("Listening on port %s", port) log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil)) // [END setting_port]}// indexHandler responds to requests with our greeting.func indexHandler(w http.ResponseWriter, r *http.Request) { ctx := context.Background() client, _ := google.DefaultClient(ctx, "https://www.googleapis.com/auth/spreadsheets.readonly") srv, err := sheets.New(client) // Prints the names and majors of students in a sample spreadsheet: // https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit spreadsheetId := "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms" readRange := "Class Data!A2:E" resp, err := srv.Spreadsheets.Values.Get(spreadsheetId, readRange).Do() if err != nil { log.Fatalf("Unable to retrieve data from sheet: %v\n", err) }重現步驟:1) 部署應用程序:gcloud app deploy2) 在瀏覽器中打開(您將獲得 502):gcloud app browse3) 檢查日志:gcloud app logs read
1 回答

呼喚遠方
TA貢獻1856條經驗 獲得超11個贊
我之前也遇到過這個問題以及 App Engine 到 G Suite 的集成。您需要使用服務帳戶密鑰。默認的是不夠的(我相信是因為它沒有私鑰,但這可能是錯誤的)。
本質上,您需要使用您的代碼上傳一個密鑰并使用它來獲取Client(而不是使用默認密鑰):
func getOauthClient(serviceAccountKeyPath string) *http.Client {
ctx := context.Background()
data, err := ioutil.ReadFile(serviceAccountKeyPath)
if err != nil {
log.Fatal(err)
}
creds, err := google.CredentialsFromJSON(ctx, data, "https://www.googleapis.com/auth/spreadsheets.readonly")
if err != nil {
log.Fatal(err)
}
return oauth2.NewClient(ctx, creds.TokenSource)
}
- 1 回答
- 0 關注
- 162 瀏覽
添加回答
舉報
0/150
提交
取消