带有服务帐户的Google Apps API 403

时间:2015-07-16 23:33:48

标签: go google-apps google-admin-sdk google-oauth2 service-accounts

我一直在尝试对Google的Admin API进行查询,以列出我的Google Apps Organization中的所有用户。我有权在web UI example中进行此查询并获得结果,但当我尝试使用服务帐户进行查询时,它是403。

import (
    "fmt"
    "io/ioutil"
    "log"

    "golang.org/x/net/context"
    "golang.org/x/oauth2/google"
    directory "google.golang.org/api/admin/directory_v1"
)

func main() {
    serviceAccountJSON, err := ioutil.ReadFile(serviceAccountFile)
    if err != nil {
        log.Fatalf("Could not read service account credentials file, %s => {%s}", serviceAccountFile, err)
    }
    config, err := google.JWTConfigFromJSON(serviceAccountJSON,
        directory.AdminDirectoryUserScope,
        directory.AdminDirectoryUserReadonlyScope,
    )

    client, err := directory.New(config.Client(context.Background()))
    if err != nil {
        log.Fatalf("Could not create directory service client => {%s}", err)
    }

    users, err := client.Users.List().ViewType(publicDataView).Domain(domain).Do()
    if err != nil {
        log.Fatalf("Failed to query all users => {%s}", err)
    }

    for _, u := range users.Users {
        fmt.Println(u.Name.FullName)
    }
}

每次执行时我都会获得403.相同的查询参数在Try it!部分here中有效,所以我不确定它为什么会失败。

结果:Failed to query all users => {googleapi: Error 403: Not Authorized to access this resource/api, forbidden}

1 个答案:

答案 0 :(得分:3)

我知道这个问题已经有一年了,但是我无法在任何地方找到任何相关内容 - 但是我遇到了与你一样的错误后设法修复它。

基本上你需要将委托用户设置为你的配置,例如:

func main() {
    serviceAccountJSON, err := ioutil.ReadFile(serviceAccountFile)
    if err != nil {
        log.Fatalf("Could not read service account credentials file, %s => {%s}", serviceAccountFile, err)
    }
    config, err := google.JWTConfigFromJSON(serviceAccountJSON,
        directory.AdminDirectoryUserScope,
        directory.AdminDirectoryUserReadonlyScope,
    )

    // Add me
    config.Subject = "someone@example.com"

    client, err := directory.New(config.Client(context.Background()))
    if err != nil {
        log.Fatalf("Could not create directory service client => {%s}", err)
    }

    users, err := client.Users.List().ViewType(publicDataView).Domain(domain).Do()
    if err != nil {
        log.Fatalf("Failed to query all users => {%s}", err)
    }

    for _, u := range users.Users {
        fmt.Println(u.Name.FullName)
    }
}

请参阅https://github.com/golang/oauth2/blob/master/google/example_test.go#L118

希望这有助于其他人!