1
votes

I am using this code in Apps script

function getUserObjByEmail(email){

    // Same as using AdminDirectory class.
    var apiUrl = "https://www.googleapis.com/admin/directory/v1/users/"+email+"?fields=id";
    var token = ScriptApp.getOAuthToken();
    var header = {"Authorization":"Bearer " + token};
    var options = {
        "method": "GET",
        "headers": header
    };

    var response = JSON.parse(UrlFetchApp.fetch(apiUrl, options));
    return response;
}

which I run as a function from App Maker project. Things go smoothly when I use the app since I have an admin role( I guess, not sure ) but the problem arises when other normal users in our domain start using the deployed app maker app. I checked the server logs and its full of this message:

Exception: Request failed for 
https://www.googleapis.com/admin/directory/v1/users/[email protected]?fields=id 
returned code 403. 
Truncated server response: { "error": { "errors": [ { "domain": "global",
"reason": "forbidden", "message": "Not Authorized to access this
resource/api" ... (use muteHttpExceptions option to examine full response)

Any idea how to fix this? I have manually added the required scopes for the apps script library, I added the following:

"https://www.googleapis.com/auth/script.external_request",
"https://www.googleapis.com/auth/admin.directory.user"
1

1 Answers

1
votes

The reason this happens is because YOU have admin rights, otherwise you'd be getting the same error message. The other users don't have admin rights hence they get the error. To solve this problem, you can either deploy the application running it as the developer or you can use a service account to impersonate an admin and do the process.

Regarding the first approach, you can find more info here https://developers.google.com/appmaker/security/identity.

Regarding the second approach, you can use the following app script library https://github.com/gsuitedevs/apps-script-oauth2#using-service-accounts

Moreover, if you do not require to get custom schemas information, then you can simply use a directory model and that should work for all users. Check the reference here: https://developers.google.com/appmaker/models/directory