使用服务帐户访问 Google 经销商 API

Accessing Google Reseller API using Service Accounts

我们在使用服务帐户访问经销商 api 时遇到问题。 带有客户端机密的示例运行良好,但我们需要在 k8s(Kubernetes 引擎)中部署它,而不需要定期刷新 oauth 会话(特别是这样做一次,因为它在 docker容器)。

虽然有很多关于如何使用 python 执行此操作的文档,但我们找不到任何使用服务帐户获取访问权限的方法。

我们尝试了两个帐户,一个是默认计算引擎,一个是直接为我们的用例创建的。 两者都获得了 G Suite 中的经销商范围。

    https://www.googleapis.com/auth/apps.order,
    https://www.googleapis.com/auth/admin.directory.user,
    https://www.googleapis.com/auth/siteverification,

尽管在使用

时我们不断收到 "googleapi: Error 403: Authenticated user is not authorized to perform this action., insufficientPermissions" 错误
    client, err = google.DefaultClient(ctx, reseller.AppsOrderScope)
    if err != nil {
        log.Fatal("creating oauth client failed", zap.Error(err))
    }
    subs, err := client.Subscriptions.List().Do()
    if err != nil {
        log.Fatal("listing subscriptions failed", zap.Error(err))
    }

我在 Whosebug 上的 post 上读到,经销商 API 需要用户模拟,但在整个 Google 中搜索这个并且 oauth2 和客户端库回购没有导致方法来做到这一点。 Python 按照端到端教程中的描述执行此操作

    credentials = ServiceAccountCredentials.from_json_keyfile_name(
        JSON_PRIVATE_KEY_FILE, 
    OAUTH2_SCOPES).create_delegated(RESELLER_ADMIN_USER)

但是对于 Go,我找不到任何记录在案的方法。

这里有几点:

  • 经销商API仅在使用服务帐户时需要模拟/全域授权。换句话说,服务帐户本身无权直接调用 API,但它可以模拟有权调用转销商的转销商用户(例如 admin@reseller.example.com 等) API.
  • 您可以 use regular 3-legged OAuth 而不是服务帐户。您只需要确保请求离线访问,以便获得长期有效的刷新令牌。
  • 模拟/全域委派与 AppEngine 和 ComputeEngine 内置的默认服务帐户不兼容。您必须使用您在 API 项目中创建的服务帐户。

看看 the samples Google provides 是否能带您到达目的地。

问题已通过使用不同的配置然后设置 jwt.Subject 来解决,这显然是在进行模拟:

const envVar = "GOOGLE_APPLICATION_CREDENTIALS"
if filename := os.Getenv(envVar); filename != "" {
    serviceAccount, err := ioutil.ReadFile(filename)
    if err != nil {
        log.Fatal("creating oauth client failed", zap.Error(err))
    }
    config, err := google.JWTConfigFromJSON(serviceAccount,
        reseller.AppsOrderScope,
    )

    config.Subject = *impersonationUser // like user@google.com
    client = config.Client(ctx)
}