无法使用Golang使用服务帐户凭据访问Google Spreadsheets

时间:2019-11-15 09:56:48

标签: authentication go google-api google-oauth google-sheets-api

我正在编写一个AWS Lambda代码,用于使用Golang输入URL来访问和更新电子表格。到目前为止,我可以按照Google指南-https://developers.google.com/sheets/api/quickstart/go

使用OAuth Client ID在本地访问电子表格

但是,由于我想从AWS Lambda运行代码,所以我想使用Google Service帐户执行身份验证。我已经创建了一个服务帐户,并已收到包含以下信息的凭据。

{
"type": "service_account",
"project_id": "quickstart-1XXXXXXX806",
"private_key_id": "a1XXXXXXXXXXXXXXXXXXXXX3c3e5d8e",
"private_key": "-----BEGIN PRIVATE KEY-----\nMZ4C8......\nD\n-----END PRIVATE KEY-----\n",
"client_email": "lambda@quickstart-1XXXXXXX806.iam.gserviceaccount.com",
"client_id": "1XXXXXXXXXXXXXXXXX2",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/lambda%40quickstart-1573627656806.iam.gserviceaccount.com"

}

我已经阅读了许多文档,但是找不到使用Golang代码使用Google服务帐户访问Google电子表格的任何参考。每个文档都引用以下Github链接-https://github.com/googleapis/google-api-go-client 但是,由于我最近开始在Golang中工作,我真的不知道如何实现它。阅读Google指南后,我了解了以下服务帐户所需的流程- enter image description here

但是我仍然不能为此编写Golang代码。如果有人可以分享一些参考文献,我将不胜感激:)

2 个答案:

答案 0 :(得分:1)

经过一番挖掘,我发现了一些documentation,它解释了如何在Golang上使用服务帐户。文档中有example关于如何使用服务帐户执行身份验证的

// Your credentials should be obtained from the Google
// Developer Console (https://console.developers.google.com).
conf := &jwt.Config{
    Email: "xxx@developer.gserviceaccount.com",
    // The contents of your RSA private key or your PEM file
    // that contains a private key.
    // If you have a p12 file instead, you
    // can use `openssl` to export the private key into a pem file.
    //
    //    $ openssl pkcs12 -in key.p12 -passin pass:notasecret -out key.pem -nodes
    //
    // The field only supports PEM containers with no passphrase.
    // The openssl command will convert p12 keys to passphrase-less PEM containers.
    PrivateKey: []byte("-----BEGIN RSA PRIVATE KEY-----..."),
    Scopes: []string{
        "https://www.googleapis.com/auth/bigquery",
        "https://www.googleapis.com/auth/blogger",
    },
    TokenURL: google.JWTTokenURL,
    // If you would like to impersonate a user, you can
    // create a transport with a subject. The following GET
    // request will be made on the behalf of user@example.com.
    // Optional.
    Subject: "user@example.com",
}
// Initiate an http.Client, the following GET request will be
// authorized and authenticated on the behalf of user@example.com.
client := conf.Client(oauth2.NoContext)
client.Get("...")

答案 1 :(得分:1)

@ZektorH的答案帮助我完成了此代码。以下是使用服务帐户从Google电子表格中提取数据的完整工作示例。

package main

import (
    "fmt"
    "log"

    "golang.org/x/oauth2"
    "golang.org/x/oauth2/jwt"
    "google.golang.org/api/sheets/v4"
)


func main() {

    // Create a JWT configurations object for the Google service account
    conf := &jwt.Config{
        Email:        "lambda@quickstart-XXXXXXXXXX.iam.gserviceaccount.com",
        PrivateKey:   []byte("-----BEGIN PRIVATE KEY-----\nxxxxxx\n-----END PRIVATE KEY-----\n"),
        PrivateKeyID: "a1a6xxxxxxxxxxxxxxxxxxxxxxxe5d8e",
        TokenURL:     "https://oauth2.googleapis.com/token",
        Scopes: []string{
            "https://www.googleapis.com/auth/spreadsheets.readonly",
        },
    }

    client := conf.Client(oauth2.NoContext)

    // Create a service object for Google sheets
    srv, err := sheets.New(client)
    if err != nil {
        log.Fatalf("Unable to retrieve Sheets client: %v", err)
    }

    // Change the Spreadsheet Id with yours    
    spreadsheetId := "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms"

    // Define the Sheet Name and fields to select
    readRange := "Sheet1!A2:B"

    // Pull the data from the sheet
    resp, err := srv.Spreadsheets.Values.Get(spreadsheetId, readRange).Do()
    if err != nil {
        log.Fatalf("Unable to retrieve data from sheet: %v", err)
    }

    // Display pulled data
    if len(resp.Values) == 0 {
        fmt.Println("No data found.")
    } else {
        fmt.Println("Name, Major:")
        for _, row := range resp.Values {
            fmt.Printf("%s, %s\n", row[0], row[1])
        }
    }
}

另外,请注意,如果出现以下错误:

  

googleapi:错误403:呼叫者没有权限,被禁止

那么您可能未获得访问该电子表格的google帐户的权限。如果是这样

  • 只需在浏览器中转到要与之交互的Google表格即可。

  • 转到屏幕右上角的共享。

  • 转到高级设置,并与您的服务帐户ex的电子邮件地址共享。 lambda@quickstart-XXXXXXXXXX.iam.gserviceaccount.com