Tạo trình kết nối danh tính

Theo mặc định, Google Cloud Search chỉ nhận dạng các danh tính Google trong Google Cloud Directory. Hãy sử dụng trình kết nối danh tính để đồng bộ hoá danh tính doanh nghiệp với danh tính Google mà Cloud Search sử dụng.

Google cung cấp các lựa chọn sau đây để phát triển trình kết nối danh tính:

Tạo trình kết nối danh tính bằng SDK trình kết nối danh tính

Một trình kết nối danh tính thông thường thực hiện các tác vụ sau:

  1. Định cấu hình trình kết nối.
  2. Truy xuất người dùng từ hệ thống danh tính của bạn và gửi họ đến Google.
  3. Truy xuất nhóm từ hệ thống danh tính của bạn và gửi họ đến Google.

Thiết lập phần phụ thuộc

Đưa các phần phụ thuộc này vào tệp bản dựng.

Maven

<dependency>
  <groupId>com.google.enterprise.cloudsearch</groupId>
  <artifactId>google-cloudsearch-identity-connector-sdk</artifactId>
  <version>v1-0.0.3</version>
</dependency>

Gradle

compile group: 'com.google.enterprise.cloudsearch',
        name: 'google-cloudsearch-identity-connector-sdk',
        version: 'v1-0.0.3'

Tạo cấu hình trình kết nối

Mỗi trình kết nối sử dụng một tệp cấu hình cho các tham số như mã kho lưu trữ. Xác định các tham số dưới dạng khoá-giá trị cặp, chẳng hạn như api.sourceId=1234567890abcdef.

SDK Google Cloud Search bao gồm các tham số do Google cung cấp cho tất cả trình kết nối. Bạn phải khai báo những tham số sau trong tệp cấu hình:

  • Trình kết nối nội dung: Khai báo api.sourceIdapi.serviceAccountPrivateKeyFile. Các tham số này xác định kho lưu trữ và khoá riêng tư cần thiết để truy cập.
  • Trình kết nối danh tính: Khai báo api.identitySourceId để xác định nguồn nhận dạng bên ngoài. Đối với việc đồng bộ hoá người dùng, hãy khai báo api.customerId (mã nhận dạng duy nhất cho tài khoản Google Workspace của bạn).

Chỉ khai báo các tham số khác do Google cung cấp để ghi đè giá trị mặc định của các tham số đó. Để biết thông tin chi tiết về cách tạo mã nhận dạng và khoá, hãy xem Các tham số do Google cung cấp.

Bạn cũng có thể xác định các tham số dành riêng cho kho lưu trữ trong tệp cấu hình.

Truyền tệp cấu hình đến trình kết nối

Đặt thuộc tính hệ thống config để truyền tệp cấu hình. Sử dụng đối số -D khi bắt đầu trình kết nối. Ví dụ:

java -classpath myconnector.jar -Dconfig=MyConfig.properties MyConnector

Nếu bạn bỏ qua đối số này, SDK sẽ cố gắng sử dụng một tệp có tên là connector-config.properties trong thư mục cục bộ.

Tạo trình kết nối danh tính đồng bộ hoá đầy đủ bằng lớp mẫu

SDK bao gồm một mẫu FullSyncIdentityConnector để đồng bộ hoá tất cả người dùng và nhóm từ kho lưu trữ của bạn. Phần này giải thích cách sử dụng mẫu này.

Phần này đề cập đến mã từ mẫu IdentityConnectorSample.java, đọc danh tính từ tệp CSV.

Triển khai điểm nhập trình kết nối

Điểm nhập là phương thức main(). Phương thức này tạo một Application thực thể và gọi start() để chạy trình kết nối.

Trước khi gọi application.start(), hãy sử dụng IdentityApplication.Builder để tạo thực thể mẫu FullSyncIdentityConnector.

IdentityConnectorSample.java
/**
 * This sample connector uses the Cloud Search SDK template class for a full
 * sync connector. In the full sync case, the repository is responsible
 * for providing a snapshot of the complete identity mappings and
 * group rosters. This is then reconciled against the current set
 * of mappings and groups in Cloud Directory.
 *
 * @param args program command line arguments
 * @throws InterruptedException thrown if an abort is issued during initialization
 */
public static void main(String[] args) throws InterruptedException {
  Repository repository = new CsvRepository();
  IdentityConnector connector = new FullSyncIdentityConnector(repository);
  IdentityApplication application = new IdentityApplication.Builder(connector, args).build();
  application.start();
}

SDK gọi initConfig() sau khi phương thức main() gọi Application.build(). Phương thức initConfig():

  1. Đảm bảo Configuration chưa được khởi chạy.
  2. Khởi chạy đối tượng Configuration bằng các cặp khoá-giá trị do Google cung cấp.

Triển khai giao diện Repository

Đối tượng Repository đồng bộ hoá danh tính kho lưu trữ với danh tính Google. Khi sử dụng mẫu, bạn chỉ cần ghi đè một số phương thức. Đối với FullSyncIdentityConnector, hãy ghi đè các phương thức sau:

  • init(): Để thiết lập và khởi chạy.
  • listUsers(): Để đồng bộ hoá tất cả người dùng.
  • listGroups(): Để đồng bộ hoá tất cả nhóm.
  • (Không bắt buộc) close(): Để dọn dẹp trong quá trình tắt.

Nhận các tham số cấu hình tuỳ chỉnh

Truy xuất các tham số tuỳ chỉnh từ đối tượng Configuration, thường là trong phương thức init(). Đoạn mã sau đây cho biết cách truy xuất đường dẫn CSV:

IdentityConnectorSample.java
/**
 * Initializes the repository once the SDK is initialized.
 *
 * @param context Injected context, contains convenienve methods
 *                for building users & groups
 * @throws IOException if unable to initialize.
 */
@Override
public void init(RepositoryContext context) throws IOException {
  log.info("Initializing repository");
  this.context = context;
  userMappingCsvPath = Configuration.getString(
      "sample.usersFile", "users.csv").get().trim();
  groupMappingCsvPath = Configuration.getString(
      "sample.groupsFile", "groups.csv").get().trim();
}

Để nhận và phân tích cú pháp một tham số chứa nhiều giá trị, hãy sử dụng một trong các trình phân tích cú pháp kiểu của lớp Configuration để phân tích cú pháp dữ liệu thành các khối riêng biệt. Đoạn mã sau đây, từ trình kết nối hướng dẫn, sử dụng getMultiValue phương thức để lấy danh sách tên kho lưu trữ GitHub:

GithubRepository.java
ConfigValue<List<String>> repos = Configuration.getMultiValue(
    "github.repos",
    Collections.emptyList(),
    Configuration.STRING_PARSER);

Nhận thông tin liên kết cho tất cả người dùng

Ghi đè listUsers() để truy xuất thông tin liên kết người dùng. Phương thức này chấp nhận một điểm kiểm tra để tiếp tục đồng bộ hoá nếu bị gián đoạn. Đối với mỗi người dùng:

  1. Nhận thông tin liên kết giữa danh tính Google và danh tính bên ngoài.
  2. Đóng gói cặp này vào trình vòng lặp do listUsers() trả về.

Nhận thông tin liên kết người dùng

Đoạn mã này minh hoạ cách truy xuất thông tin liên kết danh tính từ tệp CSV:

IdentityConnectorSample.java
/**
 * Retrieves all user identity mappings for the identity source. For the
 * full sync connector, the repository must provide a complete snapshot
 * of the mappings. This is reconciled against the current mappings
 * in Cloud Directory. All identity mappings returned here are
 * set in Cloud Directory. Any previously mapped users that are omitted
 * are unmapped.
 *
 * The connector does not create new users. All users are assumed to
 * exist in Cloud Directory.
 *
 * @param checkpoint Saved state if paging over large result sets. Not used
 *                   for this sample.
 * @return Iterator of user identity mappings
 * @throws IOException if unable to read user identity mappings
 */
@Override
public CheckpointCloseableIterable<IdentityUser> listUsers(byte[] checkpoint)
    throws IOException {
  List<IdentityUser> users = new ArrayList<>();
  try (Reader in = new FileReader(userMappingCsvPath)) {
    // Read user mappings from CSV file
    CSVParser parser = CSVFormat.RFC4180
        .withIgnoreSurroundingSpaces()
        .withIgnoreEmptyLines()
        .withCommentMarker('#')
        .parse(in);
    for (CSVRecord record : parser.getRecords()) {
      // Each record is in form: "primary_email", "external_id"
      String primaryEmailAddress = record.get(0);
      String externalId = record.get(1);
      if (primaryEmailAddress.isEmpty() || externalId.isEmpty()) {
        // Skip any malformed mappings
        continue;
      }
      log.info(() -> String.format("Adding user %s/%s",
          primaryEmailAddress, externalId));

      // Add the identity mapping
      IdentityUser user = context.buildIdentityUser(
          primaryEmailAddress, externalId);
      users.add(user);
    }
  }
  // ...
}

Đóng gói thông tin liên kết người dùng vào một trình vòng lặp

Phương thức listUsers() trả về một CheckpointCloseableIterable của IdentityUser đối tượng.

IdentityConnectorSample.java
CheckpointCloseableIterable<IdentityUser> iterator =
  new CheckpointCloseableIterableImpl.Builder<IdentityUser>(users)
      .setHasMore(false)
      .setCheckpoint((byte[])null)
      .build();

Nhận một nhóm

Ghi đè listGroups() để truy xuất các nhóm và thành viên của nhóm. Phương thức này chấp nhận một điểm kiểm tra. Đối với mỗi nhóm:

  1. Nhận nhóm và thành viên của nhóm.
  2. Đóng gói nhóm và thành viên vào trình vòng lặp do listGroups() trả về.

Nhận danh tính nhóm

Đoạn mã này minh hoạ cách truy xuất các nhóm và thành viên từ tệp CSV:

IdentityConnectorSample.java
/**
 * Retrieves all group rosters for the identity source. For the
 * full sync connector, the repository must provide a complete snapshot
 * of the rosters. This is reconciled against the current rosters
 * in Cloud Directory. All groups and members  returned here are
 * set in Cloud Directory. Any previously created groups or members
 * that are omitted are removed.
 *
 * @param checkpoint Saved state if paging over large result sets. Not used
 *                   for this sample.
 * @return Iterator of group rosters
 * @throws IOException if unable to read groups
 */    @Override
public CheckpointCloseableIterable<IdentityGroup> listGroups(byte[] checkpoint)
    throws IOException {
  List<IdentityGroup> groups = new ArrayList<>();
  try (Reader in = new FileReader(groupMappingCsvPath)) {
    // Read group rosters from CSV
    CSVParser parser = CSVFormat.RFC4180
        .withIgnoreSurroundingSpaces()
        .withIgnoreEmptyLines()
        .withCommentMarker('#')
        .parse(in);
    for (CSVRecord record : parser.getRecords()) {
      // Each record is in form: "group_id", "member"[, ..., "memberN"]
      String groupName = record.get(0);
      log.info(() -> String.format("Adding group %s", groupName));
      // Parse the remaining columns as group memberships
      Supplier<Set<Membership>> members = new MembershipsSupplier(record);
      IdentityGroup group = context.buildIdentityGroup(groupName, members);
      groups.add(group);
    }
  }
  // ...

}

Đóng gói nhóm và thành viên vào một trình vòng lặp

Phương thức listGroups() trả về một CheckpointCloseableIterable của IdentityGroup đối tượng.

IdentityConnectorSample.java
CheckpointCloseableIterable<IdentityGroup> iterator =
   new CheckpointCloseableIterableImpl.Builder<IdentityGroup>(groups)
      .setHasMore(false)
      .setCheckpoint((byte[])null)
      .build();

Các bước tiếp theo