google-app-engine - Google App Engine Go 1.11 应用程序无法访问 Google 电子表格

标签 google-app-engine go google-cloud-platform google-sheets-api

我正在尝试从 Google App Engine Go 1.11 Standard Environment 上运行的应用程序通过 API 访问 google 电子表格. 不幸的是,应用程序无法读取 this spreadsheet .

我在 Spreadsheets.Values.Get 上收到下一个错误调用:

googleapi: Error 403: Request had insufficient authentication scopes., forbidden

示例代码

// Sample app showing issue with GAE -> google spreadsheets
package main

import (
    "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)
    }

    if len(resp.Values) == 0 {
        fmt.Fprintf(w, "No data found.\n")
    } else {
        fmt.Fprintf(w, "Name, Major:\n")
        for _, row := range resp.Values {
            // Print columns A and E, which correspond to indices 0 and 4.
            fmt.Fprintf(w, "%s, %s\n", row[0], row[4])
        }
    }

}

重现步骤:

1) 部署应用:gcloud app deploy
2)在浏览器中打开(你会得到502):gcloud app browse
3) 检查日志:gcloud app logs read

2018-12-11 21:44:56 default[20181211t134352]  "GET / HTTP/1.1" 502
2018-12-11 21:44:57 default[20181211t134352]  2018/12/11 21:44:57 [DEBUG] metadata scopes: https://www.googleapis.com/auth/appengine.apis
2018-12-11 21:44:57 default[20181211t134352]  https://www.googleapis.com/auth/cloud-platform
2018-12-11 21:44:57 default[20181211t134352]  https://www.googleapis.com/auth/cloud_debugger
2018-12-11 21:44:57 default[20181211t134352]  https://www.googleapis.com/auth/devstorage.full_control
2018-12-11 21:44:57 default[20181211t134352]  https://www.googleapis.com/auth/logging.write
2018-12-11 21:44:57 default[20181211t134352]  https://www.googleapis.com/auth/monitoring.write
2018-12-11 21:44:57 default[20181211t134352]  https://www.googleapis.com/auth/trace.append
2018-12-11 21:44:57 default[20181211t134352]  https://www.googleapis.com/auth/userinfo.email
2018-12-11 21:44:57 default[20181211t134352]  .
2018-12-11 21:44:57 default[20181211t134352]  2018/12/11 21:44:57 Listening on port 8081
2018-12-11 21:44:58 default[20181211t134352]  2018/12/11 21:44:58 Unable to retrieve data from sheet: googleapi: Error 403: Request had insufficient authentication scopes., forbidden

有人可以帮助了解如何修复它吗?

示例项目:https://github.com/vistrcm/gae-spreadsheet-issue

最佳答案

我之前在 App Engine 到 G Suite 集成时也遇到过这个问题。您需要使用服务帐户 key 。默认的是不够的(我相信是因为它没有私钥,但这可能是错误的)。

本质上,您需要使用您的代码上传一个 key ,并使用它来获取 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)
}

关于google-app-engine - Google App Engine Go 1.11 应用程序无法访问 Google 电子表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53733022/

相关文章:

java - 高效地从 Google Cloud Storage 中删除多个 blob

google-app-engine - 在 GCP Cloud Run/Function 上使用固定的公共(public) IP(到白名单)

Win 7 家庭高级版上的 Python 2.7.2 和 Google App Engine SDK 1.6.1 无法正常工作

arrays - 谁能解释这种附加到 golang slice 的奇怪行为

postgresql - 更新 golang 中的 Jsonb 列

google-cloud-platform - 如何在 Hbase Row 和 Bigtable Row 上设置 TTL

java - Google App Engine Standard env - 找不到 Controller 方法 - Spring Boot 应用程序

google-app-engine - Google Cloud Shell,从1.9.1升级Docker,这不可能吗?

go - Windows 上的 VIM-Go Debugger 结果为 "Goroutine not found"

node.js - 如何在 Cloud Run 中获取环境变量?