Search code examples
javascriptjquerypostgoogle-admin-sdkgoogle-directory-api

POST request for Google Admin SDK in Javascript/Jquery


Trying to add aliases to users using post request to Directory (Admin SDK). I know that the JS client libraries is still in beta, but it's the simplest solution for what I have to do.

The below returns a 401 error. My credentials are just fine on Console.

    <script>
  var apiKey = "my_key";
  var clientId = "my_client_id";
  var scopes = "https://www.googleapis.com/auth/admin.directory.user.alias";
  var users = {}; // external JSON file

  function load() {
    gapi.client.setApiKey(apiKey);
    gapi.auth.authorize({
      client_id: clientId,
      scope: scopes,
      immediate: true
    },

    function(){
      for (var i = 0; i < users.length; i++) {
        var thisUser = users[i]["emailAddress"];
        var thisAlias = users[i]["secondaryEmail"];
        var thisURL = "https://www.googleapis.com/admin/directory/v1/users/" + thisUser + "/aliases"

        $.post(thisURL, {alias: thisAlias});
      }
    });
  }
</script>
<script src="https://apis.google.com/js/client.js?onload=load"></script>

Solution

  • You can try following the Sample code in the JavaScript Quickstart:

    // Your Client ID can be retrieved from your project in the Google
    // Developer Console, https://console.developers.google.com
    var CLIENT_ID = '<YOUR_CLIENT_ID>';
    
    var SCOPES = ['https://www.googleapis.com/auth/admin.directory.user.readonly'];
    
    /**
    * Check if current user has authorized this application.
    */
    function checkAuth() {
    gapi.auth.authorize(
    {
    'client_id': CLIENT_ID,
    'scope': SCOPES.join(' '),
    'immediate': true
    }, handleAuthResult);
    }
    
    /**
    * Handle response from authorization server.
    *
    * @param {Object} authResult Authorization result.
    */
    function handleAuthResult(authResult) {
    var authorizeDiv = document.getElementById('authorize-div');
    if (authResult && !authResult.error) {
    // Hide auth UI, then load client library.
    authorizeDiv.style.display = 'none';
    loadDirectoryApi();
    } else {
    // Show auth UI, allowing the user to initiate authorization by
    // clicking authorize button.
    authorizeDiv.style.display = 'inline';
    }
    }
    

    Try changing the format of your code to this and I think that will work.