Java 在交叉账户中列出ServiceAccount&;谷歌云IAM项目
我想做跨帐户和跨项目访问。在本例中,我在项目中创建了一个服务帐户(accessor@myproject.iam.gserviceaccount.com)并要求oher用户将我的服务帐户插入到他的IAM项目GuestProject中,该项目名为GuestProject,角色为Security Viewer 这是我的密码:Java 在交叉账户中列出ServiceAccount&;谷歌云IAM项目,java,google-cloud-platform,google-cloud-iam,Java,Google Cloud Platform,Google Cloud Iam,我想做跨帐户和跨项目访问。在本例中,我在项目中创建了一个服务帐户(accessor@myproject.iam.gserviceaccount.com)并要求oher用户将我的服务帐户插入到他的IAM项目GuestProject中,该项目名为GuestProject,角色为Security Viewer 这是我的密码: Iam iam = initIam(); List<ServiceAccount> lists = listServiceAccounts(iam); publi
Iam iam = initIam();
List<ServiceAccount> lists = listServiceAccounts(iam);
public static Iam initIam() throws IOException, GeneralSecurityException {
Map<String, String> m = ImmutableMap.<String, String>builder().put("user-agent", "my custom useragent").build();
HeaderProvider headerProvider = FixedHeaderProvider.create(m);
InputStream resourceAsStream = GCPIAM.class.getClassLoader().getResourceAsStream("credential.json");
GoogleCredential credential = GoogleCredential.fromStream(resourceAsStream);
HttpRequestInitializer init = new HttpRequestInitializer() {
@Override
public void initialize(HttpRequest request) throws IOException {
request.setHeaders(new HttpHeaders().setUserAgent("test"));
}
};
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
if (credential.createScopedRequired()) {
List<String> scopes = new ArrayList<>();
// Enable full Cloud Platform scope.
scopes.add(IamScopes.CLOUD_PLATFORM);
credential = credential.createScoped(scopes);
}
// Create IAM API object associated with the authenticated transport.
return new Iam.Builder(httpTransport, JSON_FACTORY, credential).setApplicationName("stuffs").build();
}
public static List<ServiceAccount> listServiceAccounts(Iam iam)throws IOException{
Iam.Projects.ServiceAccounts.List request = iam.projects().serviceAccounts().list("projects/" + "GuestProject");
List<ServiceAccount> serviceAccounts = new ArrayList<>();
ListServiceAccountsResponse response;
do {
response = request.execute();
if (response.getAccounts() == null) {
continue;
}
for (ServiceAccount serviceAccount : response.getAccounts()) {
// TODO: Change code below to process each `serviceAccount` resource:
// System.out.println(serviceAccount);
serviceAccounts.add(serviceAccount);
}
request.setPageToken(response.getNextPageToken());
} while (response.getNextPageToken() != null);
return serviceAccounts;
}
我的代码有什么问题吗?确保您使用的是
项目ID
或项目编号
,而不是项目名称。要查看这三种值类型,请使用CLIgcloud projects list
@JohnHanley,它现在可以工作了。谢谢
Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "GuestProject does not match [a-z\\d][a-z\\d\\-]*.",
"reason" : "badRequest"
} ],
"message" : "GuestProject does not match [a-z\\d][a-z\\d\\-]*.",
"status" : "INVALID_ARGUMENT"
}