【问题标题】:How to validate if a GCP PubSub Topic has write access using the service account in java?java - 如何使用Java中的服务帐户验证GCP PubSub主题是否具有写入权限?
【发布时间】:2020-07-21 17:25:25
【问题描述】:

我有一个项目 A 的服务帐户,它对项目 B 中定义的 Pubsub 主题具有写入权限。我想以编程方式验证相同的内容吗?有人可以帮我解决这个问题吗?

【问题讨论】:

  • 您对项目 B 有 IAM 权限吗?如果没有,你不能。
  • 您要使用哪种语言进行检查?您是否确切知道要检查哪个权限或角色?

标签: google-cloud-platform google-cloud-pubsub google-cloud-iam


【解决方案1】:

我自己解决了。 这是示例代码

public static void PubSubTopicValidator(String projectId, String topicId)
    throws IOException {

    TopicAdminSettings topicAdminSettings = getTopicAdminSettings(projectId);

    try (TopicAdminClient topicAdminClient = TopicAdminClient.create(topicAdminSettings)) {
        ProjectTopicName topicName = ProjectTopicName.of(projectId, topicId);

        List<String> permissions = new LinkedList<>();
        permissions.add("pubsub.topics.attachSubscription");
        permissions.add("pubsub.topics.publish");
        permissions.add("pubsub.topics.update");

        TestIamPermissionsRequest testIamPermissionsRequest =
            TestIamPermissionsRequest.newBuilder()
                .setResource(topicName.toString())
                .addAllPermissions(permissions)
                .build();

        TestIamPermissionsResponse testedPermissionsResponse = topicAdminClient.testIamPermissions(testIamPermissionsRequest);

        log.info("Tested:\n" + testedPermissionsResponse);


    }
}

private static TopicAdminSettings getTopicAdminSettings(String projectId) throws IOException {
    log.info("Get Topic admin settings ");
    String defaultProjectId = System.getenv("GOOGLE_CLOUD_PROJECT");
    GoogleCredentials credentials;
    ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream is = classloader.getResourceAsStream("int_sa.json");

    log.info(" inputstream "+ is);
    if(projectId.equals(defaultProjectId)){
        credentials = getDefaultCredentials();
    }
    else{
        credentials = getGoogleCredentials(is);
    }

    return TopicAdminSettings.newBuilder()
                .setCredentialsProvider(FixedCredentialsProvider.create(credentials))
                 .build();
}

【讨论】:

    猜你喜欢
    • 2019-06-20
    • 2019-03-06
    • 1970-01-01
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 2012-08-03
    • 2021-04-15
    相关资源
    最近更新 更多