Gsuite SDK java password reset throws not authorized access for superadmin users












1















I have an application in Java that allows users to reset their password for GSuite. We don't allow the users to change their own password, instead we redirect them to a web application that allows them to the change their password for both Active directory and then reset the same password with GSuite. I have followed the complicated security scheme of enabling the API in the gsuite account, and then creating a service account in Google Cloud environment then authorizing the service account back in GSuite. I also added a user superadmin user in Gsuites that will be used for this service. Keep in mind that the service works in the back end on the server and cannot use OAauth interactive authorization. The service account has been given the following permissions:



https://www.googleapis.com/auth/admin.directory.group 
https://www.googleapis.com/auth/admin.directory.user
https://www.googleapis.com/auth/admin.directory.user.readonly
https://www.googleapis.com/auth/admin.directory.user.security


What is happening is that when I attempt to change the password for standard email user, it works fine, but when I attempt to reset the password with superadmin role, it fails with the following exception:



Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Not Authorized to access this resource/api",
"reason" : "forbidden"
} ],
"message" : "Not Authorized to access this resource/api"
}
at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:150)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:401)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1056)

at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:499)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:432)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:549)
at gsuite.updateDirectory(gsuite.java:111)
at gsuite.changePassword(gsuite.java:53)
at gsuite.main(gsuite.java:118)


Here is the complete source:



import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson.JacksonFactory;
import com.google.api.services.admin.directory.Directory;
import com.google.api.services.admin.directory.DirectoryScopes;
import com.google.api.services.admin.directory.model.User;
import com.google.api.services.admin.directory.model.Users;

import javax.xml.bind.DatatypeConverter;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class gsuite {

/**
* Email of the Service Account
*/
private static final String SERVICE_ACCOUNT_EMAIL = "webapp@transactrxsecurity.iam.gserviceaccount.com";

private static Directory directory=null;

/**
* Path to the Service Account's Private Key file
*/
private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = "/Users/manuelelaraj/Downloads/transactrxsecurity-0ad733208988.p12";
private static final String DOMAIN_NAME="somedomain.com";
private static final String SUPER_USER_EMAIL = "system@Somedomain.com";
private static final String SUPER_USER_PASSWORD="Strongpassword";





public static void changePassword( Directory dir, final String username, final String newPassword ) throws Exception
{
Users users=getGSuiteUser( dir, DOMAIN_NAME, username );

if (users.isEmpty())
{

}

final User UserToBeUpdated = updatePassword( users.getUsers().get(0), SUPER_USER_PASSWORD);
updateDirectory( dir, UserToBeUpdated );
}

private static Directory getDirectory() throws IOException, GeneralSecurityException, URISyntaxException
{
if (directory!=null)
{
return directory;
}

final NetHttpTransport httpTransport = new NetHttpTransport();
final JacksonFactory jsonFactory = new JacksonFactory();
final File p12 = new File( SERVICE_ACCOUNT_PKCS12_FILE_PATH );
final GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountUser( SUPER_USER_EMAIL )
.setServiceAccountId( SERVICE_ACCOUNT_EMAIL ) //the one that ends in "@developer.gserviceaccount.com"
.setServiceAccountScopes( getCredentials() )
.setServiceAccountPrivateKeyFromP12File( p12 )
.build();
directory= new Directory.Builder( httpTransport, jsonFactory, null)
.setHttpRequestInitializer( credential )
.setApplicationName( "API Project" ) //Not necessary, but silences a runtime warning using any not-blank string here
.build();
return directory;
}

private static List<String> getCredentials()
{
final List<String> toReturn = new LinkedList<String>();
toReturn.add( DirectoryScopes.ADMIN_DIRECTORY_GROUP );
toReturn.add( DirectoryScopes.ADMIN_DIRECTORY_USER );
toReturn.add( DirectoryScopes.ADMIN_DIRECTORY_USER_READONLY );
toReturn.add( DirectoryScopes.ADMIN_DIRECTORY_USER_SECURITY );

return toReturn;
}

private static Users getGSuiteUser( final Directory dir, final String domain, final String username ) throws Exception
{
Directory.Users.List diruserlist = dir.users().list()
.setDomain( domain )
.setQuery( "email:" + username );
return diruserlist.execute();
}

private static User updatePassword( final User user, final String password ) throws Exception
{
final MessageDigest md = MessageDigest.getInstance( "MD5" ); //I've been warned that this is not thread-safe
final byte digested = md.digest( password.getBytes( "UTF-8" ) );
final String newHashword = DatatypeConverter.printHexBinary( digested );
return user.setHashFunction("MD5") //only accepts MD5, SHA-1, or CRYPT
.setPassword( newHashword );
}

private static void updateDirectory( final Directory dir, final User user ) throws IOException
{
final Directory.Users.Update updateRequest = dir.users().update( user.getPrimaryEmail(), user );
updateRequest.execute();
}

public static void main(String args) throws Exception {

Directory dir=getDirectory();

//regular user works!!
changePassword(dir,"userwithsuperadmin@transactrx.com","MaherManuco99!!");

//changing password for admin fails!!!
changePassword(dir,"userwithsuperadmin@transactrx.com","MaherManuco99!!");

}
}









share|improve this question



























    1















    I have an application in Java that allows users to reset their password for GSuite. We don't allow the users to change their own password, instead we redirect them to a web application that allows them to the change their password for both Active directory and then reset the same password with GSuite. I have followed the complicated security scheme of enabling the API in the gsuite account, and then creating a service account in Google Cloud environment then authorizing the service account back in GSuite. I also added a user superadmin user in Gsuites that will be used for this service. Keep in mind that the service works in the back end on the server and cannot use OAauth interactive authorization. The service account has been given the following permissions:



    https://www.googleapis.com/auth/admin.directory.group 
    https://www.googleapis.com/auth/admin.directory.user
    https://www.googleapis.com/auth/admin.directory.user.readonly
    https://www.googleapis.com/auth/admin.directory.user.security


    What is happening is that when I attempt to change the password for standard email user, it works fine, but when I attempt to reset the password with superadmin role, it fails with the following exception:



    Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
    {
    "code" : 403,
    "errors" : [ {
    "domain" : "global",
    "message" : "Not Authorized to access this resource/api",
    "reason" : "forbidden"
    } ],
    "message" : "Not Authorized to access this resource/api"
    }
    at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:150)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:401)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1056)

    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:499)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:432)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:549)
    at gsuite.updateDirectory(gsuite.java:111)
    at gsuite.changePassword(gsuite.java:53)
    at gsuite.main(gsuite.java:118)


    Here is the complete source:



    import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
    import com.google.api.client.http.HttpTransport;
    import com.google.api.client.http.javanet.NetHttpTransport;
    import com.google.api.client.json.JsonFactory;
    import com.google.api.client.json.jackson.JacksonFactory;
    import com.google.api.services.admin.directory.Directory;
    import com.google.api.services.admin.directory.DirectoryScopes;
    import com.google.api.services.admin.directory.model.User;
    import com.google.api.services.admin.directory.model.Users;

    import javax.xml.bind.DatatypeConverter;
    import java.io.File;
    import java.io.IOException;
    import java.net.URISyntaxException;
    import java.security.GeneralSecurityException;
    import java.security.MessageDigest;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.LinkedList;
    import java.util.List;

    public class gsuite {

    /**
    * Email of the Service Account
    */
    private static final String SERVICE_ACCOUNT_EMAIL = "webapp@transactrxsecurity.iam.gserviceaccount.com";

    private static Directory directory=null;

    /**
    * Path to the Service Account's Private Key file
    */
    private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = "/Users/manuelelaraj/Downloads/transactrxsecurity-0ad733208988.p12";
    private static final String DOMAIN_NAME="somedomain.com";
    private static final String SUPER_USER_EMAIL = "system@Somedomain.com";
    private static final String SUPER_USER_PASSWORD="Strongpassword";





    public static void changePassword( Directory dir, final String username, final String newPassword ) throws Exception
    {
    Users users=getGSuiteUser( dir, DOMAIN_NAME, username );

    if (users.isEmpty())
    {

    }

    final User UserToBeUpdated = updatePassword( users.getUsers().get(0), SUPER_USER_PASSWORD);
    updateDirectory( dir, UserToBeUpdated );
    }

    private static Directory getDirectory() throws IOException, GeneralSecurityException, URISyntaxException
    {
    if (directory!=null)
    {
    return directory;
    }

    final NetHttpTransport httpTransport = new NetHttpTransport();
    final JacksonFactory jsonFactory = new JacksonFactory();
    final File p12 = new File( SERVICE_ACCOUNT_PKCS12_FILE_PATH );
    final GoogleCredential credential = new GoogleCredential.Builder()
    .setTransport(httpTransport)
    .setJsonFactory(jsonFactory)
    .setServiceAccountUser( SUPER_USER_EMAIL )
    .setServiceAccountId( SERVICE_ACCOUNT_EMAIL ) //the one that ends in "@developer.gserviceaccount.com"
    .setServiceAccountScopes( getCredentials() )
    .setServiceAccountPrivateKeyFromP12File( p12 )
    .build();
    directory= new Directory.Builder( httpTransport, jsonFactory, null)
    .setHttpRequestInitializer( credential )
    .setApplicationName( "API Project" ) //Not necessary, but silences a runtime warning using any not-blank string here
    .build();
    return directory;
    }

    private static List<String> getCredentials()
    {
    final List<String> toReturn = new LinkedList<String>();
    toReturn.add( DirectoryScopes.ADMIN_DIRECTORY_GROUP );
    toReturn.add( DirectoryScopes.ADMIN_DIRECTORY_USER );
    toReturn.add( DirectoryScopes.ADMIN_DIRECTORY_USER_READONLY );
    toReturn.add( DirectoryScopes.ADMIN_DIRECTORY_USER_SECURITY );

    return toReturn;
    }

    private static Users getGSuiteUser( final Directory dir, final String domain, final String username ) throws Exception
    {
    Directory.Users.List diruserlist = dir.users().list()
    .setDomain( domain )
    .setQuery( "email:" + username );
    return diruserlist.execute();
    }

    private static User updatePassword( final User user, final String password ) throws Exception
    {
    final MessageDigest md = MessageDigest.getInstance( "MD5" ); //I've been warned that this is not thread-safe
    final byte digested = md.digest( password.getBytes( "UTF-8" ) );
    final String newHashword = DatatypeConverter.printHexBinary( digested );
    return user.setHashFunction("MD5") //only accepts MD5, SHA-1, or CRYPT
    .setPassword( newHashword );
    }

    private static void updateDirectory( final Directory dir, final User user ) throws IOException
    {
    final Directory.Users.Update updateRequest = dir.users().update( user.getPrimaryEmail(), user );
    updateRequest.execute();
    }

    public static void main(String args) throws Exception {

    Directory dir=getDirectory();

    //regular user works!!
    changePassword(dir,"userwithsuperadmin@transactrx.com","MaherManuco99!!");

    //changing password for admin fails!!!
    changePassword(dir,"userwithsuperadmin@transactrx.com","MaherManuco99!!");

    }
    }









    share|improve this question

























      1












      1








      1








      I have an application in Java that allows users to reset their password for GSuite. We don't allow the users to change their own password, instead we redirect them to a web application that allows them to the change their password for both Active directory and then reset the same password with GSuite. I have followed the complicated security scheme of enabling the API in the gsuite account, and then creating a service account in Google Cloud environment then authorizing the service account back in GSuite. I also added a user superadmin user in Gsuites that will be used for this service. Keep in mind that the service works in the back end on the server and cannot use OAauth interactive authorization. The service account has been given the following permissions:



      https://www.googleapis.com/auth/admin.directory.group 
      https://www.googleapis.com/auth/admin.directory.user
      https://www.googleapis.com/auth/admin.directory.user.readonly
      https://www.googleapis.com/auth/admin.directory.user.security


      What is happening is that when I attempt to change the password for standard email user, it works fine, but when I attempt to reset the password with superadmin role, it fails with the following exception:



      Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
      {
      "code" : 403,
      "errors" : [ {
      "domain" : "global",
      "message" : "Not Authorized to access this resource/api",
      "reason" : "forbidden"
      } ],
      "message" : "Not Authorized to access this resource/api"
      }
      at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:150)
      at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
      at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
      at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:401)
      at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1056)

      at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:499)
      at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:432)
      at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:549)
      at gsuite.updateDirectory(gsuite.java:111)
      at gsuite.changePassword(gsuite.java:53)
      at gsuite.main(gsuite.java:118)


      Here is the complete source:



      import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
      import com.google.api.client.http.HttpTransport;
      import com.google.api.client.http.javanet.NetHttpTransport;
      import com.google.api.client.json.JsonFactory;
      import com.google.api.client.json.jackson.JacksonFactory;
      import com.google.api.services.admin.directory.Directory;
      import com.google.api.services.admin.directory.DirectoryScopes;
      import com.google.api.services.admin.directory.model.User;
      import com.google.api.services.admin.directory.model.Users;

      import javax.xml.bind.DatatypeConverter;
      import java.io.File;
      import java.io.IOException;
      import java.net.URISyntaxException;
      import java.security.GeneralSecurityException;
      import java.security.MessageDigest;
      import java.util.ArrayList;
      import java.util.Collections;
      import java.util.LinkedList;
      import java.util.List;

      public class gsuite {

      /**
      * Email of the Service Account
      */
      private static final String SERVICE_ACCOUNT_EMAIL = "webapp@transactrxsecurity.iam.gserviceaccount.com";

      private static Directory directory=null;

      /**
      * Path to the Service Account's Private Key file
      */
      private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = "/Users/manuelelaraj/Downloads/transactrxsecurity-0ad733208988.p12";
      private static final String DOMAIN_NAME="somedomain.com";
      private static final String SUPER_USER_EMAIL = "system@Somedomain.com";
      private static final String SUPER_USER_PASSWORD="Strongpassword";





      public static void changePassword( Directory dir, final String username, final String newPassword ) throws Exception
      {
      Users users=getGSuiteUser( dir, DOMAIN_NAME, username );

      if (users.isEmpty())
      {

      }

      final User UserToBeUpdated = updatePassword( users.getUsers().get(0), SUPER_USER_PASSWORD);
      updateDirectory( dir, UserToBeUpdated );
      }

      private static Directory getDirectory() throws IOException, GeneralSecurityException, URISyntaxException
      {
      if (directory!=null)
      {
      return directory;
      }

      final NetHttpTransport httpTransport = new NetHttpTransport();
      final JacksonFactory jsonFactory = new JacksonFactory();
      final File p12 = new File( SERVICE_ACCOUNT_PKCS12_FILE_PATH );
      final GoogleCredential credential = new GoogleCredential.Builder()
      .setTransport(httpTransport)
      .setJsonFactory(jsonFactory)
      .setServiceAccountUser( SUPER_USER_EMAIL )
      .setServiceAccountId( SERVICE_ACCOUNT_EMAIL ) //the one that ends in "@developer.gserviceaccount.com"
      .setServiceAccountScopes( getCredentials() )
      .setServiceAccountPrivateKeyFromP12File( p12 )
      .build();
      directory= new Directory.Builder( httpTransport, jsonFactory, null)
      .setHttpRequestInitializer( credential )
      .setApplicationName( "API Project" ) //Not necessary, but silences a runtime warning using any not-blank string here
      .build();
      return directory;
      }

      private static List<String> getCredentials()
      {
      final List<String> toReturn = new LinkedList<String>();
      toReturn.add( DirectoryScopes.ADMIN_DIRECTORY_GROUP );
      toReturn.add( DirectoryScopes.ADMIN_DIRECTORY_USER );
      toReturn.add( DirectoryScopes.ADMIN_DIRECTORY_USER_READONLY );
      toReturn.add( DirectoryScopes.ADMIN_DIRECTORY_USER_SECURITY );

      return toReturn;
      }

      private static Users getGSuiteUser( final Directory dir, final String domain, final String username ) throws Exception
      {
      Directory.Users.List diruserlist = dir.users().list()
      .setDomain( domain )
      .setQuery( "email:" + username );
      return diruserlist.execute();
      }

      private static User updatePassword( final User user, final String password ) throws Exception
      {
      final MessageDigest md = MessageDigest.getInstance( "MD5" ); //I've been warned that this is not thread-safe
      final byte digested = md.digest( password.getBytes( "UTF-8" ) );
      final String newHashword = DatatypeConverter.printHexBinary( digested );
      return user.setHashFunction("MD5") //only accepts MD5, SHA-1, or CRYPT
      .setPassword( newHashword );
      }

      private static void updateDirectory( final Directory dir, final User user ) throws IOException
      {
      final Directory.Users.Update updateRequest = dir.users().update( user.getPrimaryEmail(), user );
      updateRequest.execute();
      }

      public static void main(String args) throws Exception {

      Directory dir=getDirectory();

      //regular user works!!
      changePassword(dir,"userwithsuperadmin@transactrx.com","MaherManuco99!!");

      //changing password for admin fails!!!
      changePassword(dir,"userwithsuperadmin@transactrx.com","MaherManuco99!!");

      }
      }









      share|improve this question














      I have an application in Java that allows users to reset their password for GSuite. We don't allow the users to change their own password, instead we redirect them to a web application that allows them to the change their password for both Active directory and then reset the same password with GSuite. I have followed the complicated security scheme of enabling the API in the gsuite account, and then creating a service account in Google Cloud environment then authorizing the service account back in GSuite. I also added a user superadmin user in Gsuites that will be used for this service. Keep in mind that the service works in the back end on the server and cannot use OAauth interactive authorization. The service account has been given the following permissions:



      https://www.googleapis.com/auth/admin.directory.group 
      https://www.googleapis.com/auth/admin.directory.user
      https://www.googleapis.com/auth/admin.directory.user.readonly
      https://www.googleapis.com/auth/admin.directory.user.security


      What is happening is that when I attempt to change the password for standard email user, it works fine, but when I attempt to reset the password with superadmin role, it fails with the following exception:



      Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
      {
      "code" : 403,
      "errors" : [ {
      "domain" : "global",
      "message" : "Not Authorized to access this resource/api",
      "reason" : "forbidden"
      } ],
      "message" : "Not Authorized to access this resource/api"
      }
      at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:150)
      at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
      at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
      at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:401)
      at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1056)

      at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:499)
      at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:432)
      at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:549)
      at gsuite.updateDirectory(gsuite.java:111)
      at gsuite.changePassword(gsuite.java:53)
      at gsuite.main(gsuite.java:118)


      Here is the complete source:



      import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
      import com.google.api.client.http.HttpTransport;
      import com.google.api.client.http.javanet.NetHttpTransport;
      import com.google.api.client.json.JsonFactory;
      import com.google.api.client.json.jackson.JacksonFactory;
      import com.google.api.services.admin.directory.Directory;
      import com.google.api.services.admin.directory.DirectoryScopes;
      import com.google.api.services.admin.directory.model.User;
      import com.google.api.services.admin.directory.model.Users;

      import javax.xml.bind.DatatypeConverter;
      import java.io.File;
      import java.io.IOException;
      import java.net.URISyntaxException;
      import java.security.GeneralSecurityException;
      import java.security.MessageDigest;
      import java.util.ArrayList;
      import java.util.Collections;
      import java.util.LinkedList;
      import java.util.List;

      public class gsuite {

      /**
      * Email of the Service Account
      */
      private static final String SERVICE_ACCOUNT_EMAIL = "webapp@transactrxsecurity.iam.gserviceaccount.com";

      private static Directory directory=null;

      /**
      * Path to the Service Account's Private Key file
      */
      private static final String SERVICE_ACCOUNT_PKCS12_FILE_PATH = "/Users/manuelelaraj/Downloads/transactrxsecurity-0ad733208988.p12";
      private static final String DOMAIN_NAME="somedomain.com";
      private static final String SUPER_USER_EMAIL = "system@Somedomain.com";
      private static final String SUPER_USER_PASSWORD="Strongpassword";





      public static void changePassword( Directory dir, final String username, final String newPassword ) throws Exception
      {
      Users users=getGSuiteUser( dir, DOMAIN_NAME, username );

      if (users.isEmpty())
      {

      }

      final User UserToBeUpdated = updatePassword( users.getUsers().get(0), SUPER_USER_PASSWORD);
      updateDirectory( dir, UserToBeUpdated );
      }

      private static Directory getDirectory() throws IOException, GeneralSecurityException, URISyntaxException
      {
      if (directory!=null)
      {
      return directory;
      }

      final NetHttpTransport httpTransport = new NetHttpTransport();
      final JacksonFactory jsonFactory = new JacksonFactory();
      final File p12 = new File( SERVICE_ACCOUNT_PKCS12_FILE_PATH );
      final GoogleCredential credential = new GoogleCredential.Builder()
      .setTransport(httpTransport)
      .setJsonFactory(jsonFactory)
      .setServiceAccountUser( SUPER_USER_EMAIL )
      .setServiceAccountId( SERVICE_ACCOUNT_EMAIL ) //the one that ends in "@developer.gserviceaccount.com"
      .setServiceAccountScopes( getCredentials() )
      .setServiceAccountPrivateKeyFromP12File( p12 )
      .build();
      directory= new Directory.Builder( httpTransport, jsonFactory, null)
      .setHttpRequestInitializer( credential )
      .setApplicationName( "API Project" ) //Not necessary, but silences a runtime warning using any not-blank string here
      .build();
      return directory;
      }

      private static List<String> getCredentials()
      {
      final List<String> toReturn = new LinkedList<String>();
      toReturn.add( DirectoryScopes.ADMIN_DIRECTORY_GROUP );
      toReturn.add( DirectoryScopes.ADMIN_DIRECTORY_USER );
      toReturn.add( DirectoryScopes.ADMIN_DIRECTORY_USER_READONLY );
      toReturn.add( DirectoryScopes.ADMIN_DIRECTORY_USER_SECURITY );

      return toReturn;
      }

      private static Users getGSuiteUser( final Directory dir, final String domain, final String username ) throws Exception
      {
      Directory.Users.List diruserlist = dir.users().list()
      .setDomain( domain )
      .setQuery( "email:" + username );
      return diruserlist.execute();
      }

      private static User updatePassword( final User user, final String password ) throws Exception
      {
      final MessageDigest md = MessageDigest.getInstance( "MD5" ); //I've been warned that this is not thread-safe
      final byte digested = md.digest( password.getBytes( "UTF-8" ) );
      final String newHashword = DatatypeConverter.printHexBinary( digested );
      return user.setHashFunction("MD5") //only accepts MD5, SHA-1, or CRYPT
      .setPassword( newHashword );
      }

      private static void updateDirectory( final Directory dir, final User user ) throws IOException
      {
      final Directory.Users.Update updateRequest = dir.users().update( user.getPrimaryEmail(), user );
      updateRequest.execute();
      }

      public static void main(String args) throws Exception {

      Directory dir=getDirectory();

      //regular user works!!
      changePassword(dir,"userwithsuperadmin@transactrx.com","MaherManuco99!!");

      //changing password for admin fails!!!
      changePassword(dir,"userwithsuperadmin@transactrx.com","MaherManuco99!!");

      }
      }






      java sdk gsuite






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 20 '18 at 12:11









      Manuel ElarajManuel Elaraj

      61




      61
























          0






          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53392739%2fgsuite-sdk-java-password-reset-throws-not-authorized-access-for-superadmin-users%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53392739%2fgsuite-sdk-java-password-reset-throws-not-authorized-access-for-superadmin-users%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          'app-layout' is not a known element: how to share Component with different Modules

          android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

          WPF add header to Image with URL pettitions [duplicate]