Google Directory API returns Not Authorized when call users().list().execute()

后端 未结 4 1294
孤独总比滥情好
孤独总比滥情好 2020-12-17 05:06

I need to read the list of users (and groups) from my google domain.

So I went to my Google APIs Console and enabled Admin SDK and created a

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-17 05:16

    Google Directory API works with Compute Engine default service account, you do not need to setup Google Drive domain-wide. The only thing: you have to set serviceAccountUser, which is not supported in JSON based credentials. So you can

    • use P12 keys
    • user JSON credentials with workaround:

    make credential copy:

    import static com.google.api.client.googleapis.util.Utils.getDefaultJsonFactory;
    import static com.google.api.client.googleapis.util.Utils.getDefaultTransport;
    
    private static final String APPLICATION_NAME = "AnyAppName";
    
    private final List SCOPES = ImmutableList.of(
            DirectoryScopes.ADMIN_DIRECTORY_GROUP_MEMBER, DirectoryScopes.ADMIN_DIRECTORY_USER, DirectoryScopes.ADMIN_DIRECTORY_GROUP);
    
    private Directory service;
    
    @PostConstruct
    void init() throws GeneralSecurityException, IOException {
        GoogleCredential credential;
        try (InputStream is = new FileInputStream("./config/client_secret.json")) {
            credential = GoogleCredential.fromStream(is);
        }
        GoogleCredential credentialWithUser = new GoogleCredential.Builder()
                .setTransport(getDefaultTransport())
                .setJsonFactory(getDefaultJsonFactory())
                .setServiceAccountUser("admin@yourdomain.ru")  // <--- mail of domain's admin
                .setServiceAccountId(credential.getServiceAccountId())
                .setServiceAccountScopes(SCOPES)
                .setServiceAccountPrivateKey(credential.getServiceAccountPrivateKey())
                .setServiceAccountPrivateKeyId(credential.getServiceAccountPrivateKeyId())
                .setTokenServerEncodedUrl(credential.getTokenServerEncodedUrl()).build();
    
        service = new Directory.Builder(getDefaultTransport(), getDefaultJsonFactory(), credentialWithUser).setApplicationName(APPLICATION_NAME).build();
    }
    
     public void members() throws IOException {
        Members members = service.members().list("groupName@yourdomain.ru").execute();
        System.out.println(members);
     }
    

    For my trial G Suite account it works!

提交回复
热议问题