目录API返回403禁止

时间:2017-12-17 10:08:29

标签: google-api service-accounts google-directory-api gsuite

我尝试使用目录API,使用我启用了Domain-wide Delegation的服务帐户,当然还使用json文件从管理控制台授权此服务创建服务帐户时下载的凭据。 我还从谷歌开发者控制台启用了admin sdk 并且我正在使用 googleapi 库 为了获得服务帐户的访问令牌

import * as  google from 'googleapis';//google sdk for api+Oauth
//creating JWT auth client for service account:

const jwtClient = new google.auth.JWT(
  client_email,
  null,
  private_key,
  scope, // (included the   "https://www.googleapis.com/auth/admin.directory.user" scope)
  null,
);


      let tokens
      jwtClient.authorize( (err, tokens)=> {
        if (err) {
          console.log(err);
          return;
        } else {
          tokens = tokens
        }
        // Make an authorized request to list of domain users.

        let url = `https://www.googleapis.com/admin/directory/v1/users?domain=mydomain`;
        let headers = {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${tokens.access_token}`
        }

        request.get({
          url: url,
          json: true,
          headers: headers,
        }, (err, res, body: {}) => {
          this.handleResponse(err, res, body, resolve, reject);
        });
      });

    })
  }

令牌成功重试,但在发送用户列表请求时,我收到403"未授权访问此资源/ api" 另一方面,当使用谷歌资源管理器api与相同的参数时,它工作

1 个答案:

答案 0 :(得分:0)

似乎在构造subject对象时(在代码中JWT之后的行中没有提供scope,)。您应该在此处提供管理员的电子邮件地址,以便获得模拟该管理员的令牌。否则,您将自己充当服务帐户,该帐户无权访问您域的目录(并且永远无法访问-这就是为什么您必须模拟管理员的原因)。

相关问题