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

Theo mặc định, Google Cloud Search chỉ nhận dạng danh tính trên Google trong Danh mục Google Cloud. 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 những lựa chọn sau để phát triển trình kết nối nhận dạng:

Tạo trình kết nối nhận dạng bằng Identity Connector SDK

Một trình kết nối danh tính thông thường sẽ thực hiện những việc 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 nhận dạng của bạn và gửi họ đến Google.
  3. Truy xuất các nhóm từ hệ thống nhận dạng của bạn và gửi các nhóm đó đế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 đều sử dụng một tệp cấu hình cho các tham số như mã nhận dạng kho lưu trữ. Xác định các tham số dưới dạng các cặp khoá-giá trị, 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ả các trình kết nối. Bạn phải khai báo những nội dung 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 khoá này xác định kho lưu trữ của bạn 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 danh tính bên ngoài của bạn. Đối với việc đồng bộ hoá người dùng, hãy khai báo cả 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 thông số khác do Google cung cấp để ghi đè giá trị mặc định của chúng. Để biết thông tin chi tiết về cách tạo mã nhận dạng và khoá, hãy xem phần 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 khởi động 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 này có một mẫu FullSyncIdentityConnector để đồng bộ hoá tất cả người dùng và nhóm trong kho lưu trữ của bạn. Phần này giải thích cách sử dụng tính năng 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 truy cập của trình kết nối

Điểm truy cập là phương thức main(). Thao tác này sẽ tạo một phiên bản Application và gọi start() để chạy trình kết nối.

Trước khi gọi application.start(), hãy dùng IdentityApplication.Builder để tạo thực thể cho 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() của bạn gọi Application.build(). Phương thức initConfig():

  1. Đảm bảo rằng 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 Kho lưu trữ

Đối tượng Repository đồng bộ hoá danh tính kho lưu trữ với danh tính trên Google. Khi sử dụng một mẫu, bạn chỉ cần ghi đè một số phương thức nhất định. Đố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ả cá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 các đườ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();
}

Để lấy 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 loại 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 (trong trình kết nối hướng dẫn) sử dụng phương thức getMultiValue để lấy danh sách tên kho lưu trữ trên GitHub:

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

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

Ghi đè listUsers() để truy xuất các mối 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. Lấy mối liên kết giữa danh tính trên Google và danh tính bên ngoài.
  2. Đóng gói cặp này vào trình 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 mối 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 một tệp liên kết người dùng vào một trình lặp

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

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

Lấy 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. Lấy nhóm và các thành viên của nhóm.
  2. Đóng gói chúng vào trình lặp do listGroups() trả về.

Nhận danh tính của nhóm

Đoạn mã này minh hoạ cách truy xuất các nhóm và thành viên từ mộ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à các thành viên vào một trình lặp

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

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

Các bước tiếp theo