如何使用Java Google Admin SDK API删除用户

时间:2017-07-10 16:08:17

标签: java google-admin-sdk

我使用了Java Quickstart并获得了一个正常运行的应用程序,该应用程序只显示连接到登录帐户的所有用户的完整列表。我已经浏览了Java文档,我发现的唯一与删除用户相关的是" setDeletionTime"在User类中,但我尝试使用虚拟帐户并将时间设置为" null"并试图创建一个设置为今天的时间,并且都不能删除用户。我不知道我在这里缺少什么。

我正在使用的代码,其中大部分都是从google快速入门中复制的

import com.google.api.client.auth.oauth2.Credential;

import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledAp;

import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;

import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;

import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;

import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;

import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.admin.directory.DirectoryScopes;
import com.google.api.services.admin.directory.model.*;
import com.google.api.services.admin.directory.Directory;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;


public class Quickstart {
/** Application name. */
private static final String APPLICATION_NAME =
    "Directory API Java Quickstart";

/** Directory to store user credentials for this application. */
private static final java.io.File DATA_STORE_DIR = new java.io.File(
    System.getProperty("user.home"), ".credentials/admin-directory_v1-java-quickstart");

/** Global instance of the {@link FileDataStoreFactory}. */
private static FileDataStoreFactory DATA_STORE_FACTORY;

/** Global instance of the JSON factory. */
private static final JsonFactory JSON_FACTORY =
    JacksonFactory.getDefaultInstance();

/** Global instance of the HTTP transport. */
private static HttpTransport HTTP_TRANSPORT;

/** Global instance of the scopes required by this quickstart.
 *
 * If modifying these scopes, delete your previously saved credentials
 * at ~/.credentials/admin-directory_v1-java-quickstart
 */
private static final List<String> SCOPES =
    Arrays.asList(DirectoryScopes.ADMIN_DIRECTORY_USER_READONLY);

static {
    try {
        HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(1);
    }
}

/**
 * Creates an authorized Credential object.
 * @return an authorized Credential object.
 * @throws IOException
 */
public static Credential authorize() throws IOException {
    // Load client secrets.
    /* This does not work as of now
    InputStream in = Quickstart.class.getResourceAsStream("src/resources/client_secret.json");
    */
    InputStream in = new FileInputStream("src/resources/client_secret.json");
    GoogleClientSecrets clientSecrets =
        GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow =
            new GoogleAuthorizationCodeFlow.Builder(
                    HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(DATA_STORE_FACTORY)
            .setAccessType("offline")
            .build();
    Credential credential = new AuthorizationCodeInstalledApp(
        flow, new LocalServerReceiver()).authorize("user");
    System.out.println(
            "Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
    return credential;
}

/**
 * Build and return an authorized Admin SDK Directory client service.
 * @return an authorized Directory client service
 * @throws IOException
 */
public static Directory getDirectoryService() throws IOException {
    Credential credential = authorize();
    return new Directory.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, credential)
            .setApplicationName(APPLICATION_NAME)
            .build();
}

public static void main(String[] args) throws IOException {


    // Build a new authorized API client service.
    Directory service = getDirectoryService();

    // Print the first 10 users in the domain.
    Users result = service.users().list().setCustomer("my_customer").setOrderBy("email").execute();
    List<User> users = result.getUsers();


    if (users == null || users.size() == 0) {
        System.out.println("No users found.");
    } else {
        for (User user : users) {
            //This is where I tried to delete the users
            //I have also tried using a normal for loop and nothing changes 
            that
            System.out.println();
        }
    }

}

1 个答案:

答案 0 :(得分:0)

在阅读了我可以在谷歌提供的所有内容后,我终于明白了......我想。我将在这里解释并将其作为答案,因为它有效;但是,如果我做错了,请告诉我。无论如何,这就是我所做的:

首先是第一件事。每个动作(据我所知)都通过http作为一个带有命令的URL。这意味着为了使任何事情发生,你必须有一个传输(由HttpTransport类给出)和一个工厂(由HttpRequestFactory类给出)来创建持有的HttpRequest对象动作/命令。

我们要做的请求是在“删除用户帐户”下显示here的DELETE请求

这可以通过以下方式完成:

HttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
HttpRequestFactory HTTP_REQUEST_FACTORY = HTTP_TRANSPORT.createRequestFactory();
HttpRequest deleteRequest = HTTP_REQUEST_FACTORY.buildDeleteRequest(new GenericUrl("https://www.googleapis.com/admin/directory/v1/users/userkey"));

但等等!我们在这里缺少一个非常重要的 key 元素。我们必须为Factory提供正确的凭据以标记标题。基本上是告诉谷歌我们能够删除用户。那我们该怎么做呢?

首先,我们必须设置范围,我们想要访问的内容。我们的范围是ADMIN_DIRECTORY_USER。像这样设置范围:(如果你已经完成了这个程序,请确认你在.credentials目录中删除文件!!!!)

List<String> SCOPES = Arrays.asList(DirectoryScopes.ADMIN_DIRECTORY_USER);

接下来我们需要一个凭证对象。这可以通过使用google在quickstartauthorize方法)中提供的方法来完成。要将凭证提供给我们的工厂,我们只需通过传递凭证对象来编辑上面的行:

HttpRequestFactory HTTP_REQUEST_FACTORY = HTTP_TRANSPORT.createRequestFactory(credentials);

注意:不要从HttpRequestInitializer方法传递credentials.getRequestInitializer(),因为这是空的(至少对我来说,这可能就像我正在做的那样,但我宁愿不尝试)。

在这里,我将附上我的代码,向您展示完整版本:

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestFactory;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;

import com.google.api.services.admin.directory.DirectoryScopes;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;

public class Quickstart {
    /** Application name. */
    private static final String APPLICATION_NAME = "Deleting user example";

    /** Directory to store user credentials for this application. */
    private static final java.io.File DATA_STORE_DIR = new java.io.File(System.getProperty("user.home"), ".credentials/admin-directory_v1-java-quickstart");

    /** Global instance of the {@link FileDataStoreFactory}. */
    private static FileDataStoreFactory DATA_STORE_FACTORY;

    /** Global instance of the JSON factory. */
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

    /** Global instance of the HTTP transport. */
    private static HttpTransport HTTP_TRANSPORT;

    //This creates the factory that is used for the user made requests
    private static HttpRequestFactory HTTP_REQUEST_FACTORY;

    //This is the credentials for the entire application
    private static Credential credential;

    /** Global instance of the scopes required by this quickstart.
     *
     * If modifying these scopes, delete your previously saved credentials
     * at ~/.credentials/admin-directory_v1-java-quickstart
     */
    private static final List<String> SCOPES = Arrays.asList(DirectoryScopes.ADMIN_DIRECTORY_USER);

    static {
        try {
            HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
            DATA_STORE_FACTORY = new FileDataStoreFactory(DATA_STORE_DIR);
        } catch (Throwable t) {
            t.printStackTrace();
            System.exit(1);
        }
    }


    /**
     * Creates an authorized Credential object.
     * @return an authorized Credential object.
     * @throws IOException
     */
    public static Credential authorize() throws IOException {
        // Load client secrets.
        /* This does not work as of now
        InputStream in = Quickstart.class.getResourceAsStream("src/resources/client_secret.json");
        */
        InputStream in = new FileInputStream("src/resources/client_secret.json");
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

        // Build flow and trigger user authorization request.
        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES).setDataStoreFactory(DATA_STORE_FACTORY).setAccessType("offline").build();
        Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
        System.out.println("Credentials saved to " + DATA_STORE_DIR.getAbsolutePath());
        return credential;
    }


    public static void main(String[] args) throws IOException {



        System.out.println("Deleting user with email");
        credential = authorize();
        HTTP_REQUEST_FACTORY = HTTP_TRANSPORT.createRequestFactory(credential);
        HttpRequest deleteRequest = HTTP_REQUEST_FACTORY.buildDeleteRequest(new GenericUrl("https://www.googleapis.com/admin/directory/v1/users/REPLACEMEWITHEMAILORUSERKEY"));
        deleteRequest.execute();

    }

}