如何使用java中的服务帐户验证GCP PubSub Topic是否具有写访问权限



我有一个服务帐户,比如说项目a,它对项目B中定义的Pubsub主题有写访问权限。我想用程序验证同一个吗?有人能帮我吗?

我自己解决了这个问题。这是的样本代码

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

相关内容

最新更新