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

How to delete Users using the Java Google Admin SDK API

我进入了 Java 快速入门并获得了一个工作应用程序,它只显示连接到已登录帐户的所有用户的完整列表。我已经查看了 Java 文档,我发现唯一与删除用户有关的是用户 class 中的 "setDeletionTime",但我已经用虚拟机尝试过帐户并将时间设置为 "null" 并尝试创建一个设置为今天的时间,但都无法删除用户。我不知道我在这里错过了什么。

我正在使用的代码,大部分是从 google quickstart

复制的
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();
        }
    }

}

在阅读了 google 提供的所有我能找到的内容后,我终于弄明白了……我想。我将在这里解释它并将其作为答案,因为它有效;但是,如果我做错了什么,请告诉我。无论如何,这就是我所做的:

所以第一件事就是第一。每个动作(据我所知)都通过 http 作为 URL 加上命令。这意味着为了让任何事情发生,你必须有一个传输(由 HttpTransport class 给出)和一个工厂(由 HttpRequestFactory class 给出)来创建HttpRequest object 持有 action/command.

我们将发出的请求是 "Delete a user account"

here 显示的删除请求

这一切都可以通过做这样的事情来完成:

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 元素。我们必须向工厂提供正确的凭据以标记 header。基本上是告诉 google 我们可以删除用户。那我们该怎么做呢?

首先我们必须设置范围,即我们想要访问的内容。我们的范围是ADMIN_DIRECTORY_USER。像这样设置范围:(确保删除 .credentials 目录中的文件,如果您已经 运行 这个程序!!!)

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

接下来我们需要一个凭据object。这可以通过使用 google 在他们的 quickstart 中给我们的方法(authorize 方法)来完成。为了向我们的工厂提供凭据,我们只需编辑上面的行,将凭据传递给它 object:

HttpRequestFactory HTTP_REQUEST_FACTORY = HTTP_TRANSPORT.createRequestFactory(credentials);

注意:不要从 credentials.getRequestInitializer() 方法向它传递 HttpRequestInitializer,因为这是空的(至少对我来说,这可能只是我这样做的方式,但我宁愿不这样做试一试)。

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

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();

    }

}