Google Admin Directory API-使用Google表格脚本授予对服务帐户的访问权限

时间:2019-01-16 00:27:12

标签: google-apps-script google-sheets google-directory-api

我有一个脚本,可以从目录中提取用户数据并将其推送到Google工作表。我不断收到错误消息,说我没有访问权限,并且尝试了所有操作。我不知道为什么。

这是我的代码:

    var PRIVATE_KEY =
    '-----BEGIN PRIVATE KEY--------END PRIVATE KEY-----\n';
var CLIENT_EMAIL = 'contacts@automation.iam.gserviceaccount.com';
var USER_EMAIL = 'admin@domain.com';


function getService() {
  return OAuth2.createService('Domain:' + USER_EMAIL)
      // Set the endpoint URL.
      .setTokenUrl('https://accounts.google.com/o/oauth2/token')

      // Set the private key and issuer.
      .setPrivateKey(PRIVATE_KEY)
      .setIssuer(CLIENT_EMAIL)

      // Set the name of the user to impersonate. This will only work for
      // Google Apps for Work/EDU accounts whose admin has setup domain-wide
      // delegation:
      // https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority
      .setSubject(USER_EMAIL)

      // Set the property store where authorized tokens should be persisted.
      .setPropertyStore(PropertiesService.getScriptProperties())

      // Set the scope. This must match one of the scopes configured during the
      // setup of domain-wide delegation.
      .setScope('https://www.googleapis.com/auth/admin.directory.user.readonly');
}

function listAllUsers() {

  var service = getService();
  if (service.hasAccess()) {
    var ss = SpreadsheetApp.getActive();
    var pageToken,
    page,
    count = 0;
    var listArray = [];
    listArray.push(['full name', 'first name', 'last name', 'email', 'orgunit', 'department', 'title', 'phoneType', 'phoneNumber', 'ID'])
    do {
        page = AdminDirectory.Users.list({
                domain: "domain.com",     // Google Apps domain name
                orderBy: "email",     
                pageToken : pageToken
            });
        var users = page.users;
        if (users) {
            for (var i = 0; i < users.length; i++) {
                var user = users[i];
                var department,
                title, phonetype, phonenumber, orgunit; // Addded two new variables 
                try { // Try to get the users department if there is an error push the error to the array
                    department = user.organizations[0].department;
                } catch (e) {
                    department = e
                }
                try {// Try to get the users title if there is an error push the error to the array
                    title = user.organizations[0].title;
                } catch (e) {
                    title = e
                }
              try {// Try to get the users PhoneType if there is an error push the error to the array
                    phonetype = user.phones[0].type;
                } catch (e) {
                    title = e
                }
              try {// Try to get the users PhoneNumber if there is an error push the error to the array
                    phonenumber = user.phones[0].value;
                } catch (e) {
                    title = e
                }
              try {// Try to get the users PhoneNumber if there is an error push the error to the array
                    orgunit = user.organizations[0].name;
                } catch (e) {
                    title = e
                }
                listArray.push([user.name.fullName, user.name.givenName, user.name.familyName, user.primaryEmail, orgunit, department, title, phonetype, phonenumber, user.id]);

            }
        }
        pageToken = page.nextPageToken;
         // This means you only get one page
    } while (pageToken);
    try {
        var outputSheet = ss.getSheetByName('allMembers');
        outputSheet.getDataRange();
    } catch (err) {
        var outputSheet = ss.insertSheet('allMembers', 2);
    }
    outputSheet.getDataRange().clear();
    outputSheet.getRange(1, 1, listArray.length, listArray[0].length).setValues(listArray);
    outputSheet.getRange(1, 6, outputSheet.getLastRow(), 4).setHorizontalAlignment("center");
    outputSheet.getRange(1, 1, outputSheet.getLastRow(), 1).setHorizontalAlignment("center");
    var width = [150, 150, 180, 250, 250, 200];
  } }

当我使用viewtype domain_public运行它时,它可以工作,但仅提取全局目录数据,而不提取组织单位之类的隐藏数据。

我收到错误“未授权”以访问此资源/ api(第41行,文件“代码”)

我确保为该项目启用了高级服务和API,该服务帐户具有域范围内的域范围委派:https://www.googleapis.com/auth/admin.directory.user.readonly

无论我如何尝试,我似乎仍然无法使其正常工作。

我尝试从https://github.com/gsuitedevs/apps-script-oauth2添加身份验证代码,但是如您所见,它仍然无法正常工作。

0 个答案:

没有答案