Java源码示例:com.google.api.services.iam.v1.IamScopes
示例1
/**
* Get the API stub for accessing the IAM Service Accounts API.
* @return ServiceAccounts api stub for accessing the IAM Service Accounts API.
* @throws IOException Thrown if there's an IO error initializing the api connection.
* @throws GeneralSecurityException Thrown if there's a security error
* initializing the connection.
*/
public static ServiceAccounts getServiceAccountsApiStub() throws IOException, GeneralSecurityException {
if (serviceAccountsApiStub == null) {
HttpTransport transport;
GoogleCredential credential;
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
transport = GoogleNetHttpTransport.newTrustedTransport();
credential = GoogleCredential.getApplicationDefault(transport, jsonFactory);
if (credential.createScopedRequired()) {
Collection<String> scopes = IamScopes.all();
credential = credential.createScoped(scopes);
}
serviceAccountsApiStub = new Iam.Builder(transport, jsonFactory, credential)
.build()
.projects()
.serviceAccounts();
}
return serviceAccountsApiStub;
}
示例2
@Before
public void setUp() throws Exception {
var defaultCredentials = GoogleCredentials.getApplicationDefault();
var serviceCredentials = ImpersonatedCredentials.create(
defaultCredentials, SERVICE_ACCOUNT,
List.of(), List.of("https://www.googleapis.com/auth/cloud-platform"), 300);
try {
serviceCredentials.refreshAccessToken();
} catch (IOException e) {
// Do not run this test if we do not have permission to impersonate the test user.
Assume.assumeNoException(e);
}
iam = new Iam.Builder(
Utils.getDefaultTransport(), Utils.getDefaultJsonFactory(),
new HttpCredentialsAdapter(serviceCredentials.createScoped(IamScopes.all())))
.setApplicationName("styx-test")
.build();
}
示例3
private static ServiceAccountKeyManager createServiceAccountKeyManager() {
try {
final HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
final JsonFactory jsonFactory = Utils.getDefaultJsonFactory();
final GoogleCredential credential = GoogleCredential
.getApplicationDefault(httpTransport, jsonFactory)
.createScoped(IamScopes.all());
final Iam iam = new Iam.Builder(
httpTransport, jsonFactory, credential)
.setApplicationName(SERVICE_NAME)
.build();
return new ServiceAccountKeyManager(iam);
} catch (GeneralSecurityException | IOException e) {
throw new RuntimeException(e);
}
}
示例4
@Test
public void deleteExpiredTestServiceAccounts() throws IOException {
var iam = new Iam.Builder(
Utils.getDefaultTransport(), Utils.getDefaultJsonFactory(),
GoogleCredential.getApplicationDefault().createScoped(IamScopes.all()))
.setApplicationName(TestNamespaces.TEST_NAMESPACE_PREFIX)
.build();
var accounts = listServiceAccounts(iam);
for (final ServiceAccount account : accounts) {
var displayName = account.getDisplayName();
if (displayName == null || !TestNamespaces.isExpiredTestNamespace(displayName, NOW)) {
continue;
}
log.info("Deleting old test service account: {}", account.getEmail());
try {
var request = iam.projects().serviceAccounts()
.delete("projects/styx-oss-test/serviceAccounts/" + account.getEmail());
executeWithRetries(request);
} catch (Throwable e) {
log.error("Failed to delete old test service account: {}", account.getEmail(), e);
}
}
}
示例5
private static Iam initService() throws GeneralSecurityException, IOException {
// Use the Application Default Credentials strategy for authentication. For more info, see:
// https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
// Initialize the IAM service, which can be used to send requests to the IAM API.
Iam service =
new Iam.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
new HttpCredentialsAdapter(credential))
.setApplicationName("service-accounts")
.build();
return service;
}
示例6
private static Iam initService() throws GeneralSecurityException, IOException {
// Use the Application Default Credentials strategy for authentication. For more info, see:
// https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
// Initialize the IAM service, which can be used to send requests to the IAM API.
Iam service =
new Iam.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
new HttpCredentialsAdapter(credential))
.setApplicationName("service-accounts")
.build();
return service;
}
示例7
public static CloudResourceManager createCloudResourceManagerService()
throws IOException, GeneralSecurityException {
// Use the Application Default Credentials strategy for authentication. For more info, see:
// https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
CloudResourceManager service =
new CloudResourceManager.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
new HttpCredentialsAdapter(credential))
.setApplicationName("service-accounts")
.build();
return service;
}
示例8
public static CloudResourceManager createCloudResourceManagerService()
throws IOException, GeneralSecurityException {
// Use the Application Default Credentials strategy for authentication. For more info, see:
// https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
CloudResourceManager service =
new CloudResourceManager.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
new HttpCredentialsAdapter(credential))
.setApplicationName("service-accounts")
.build();
return service;
}
示例9
public static CloudResourceManager createCloudResourceManagerService()
throws IOException, GeneralSecurityException {
// Use the Application Default Credentials strategy for authentication. For more info, see:
// https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
CloudResourceManager service =
new CloudResourceManager.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
new HttpCredentialsAdapter(credential))
.setApplicationName("service-accounts")
.build();
return service;
}
示例10
private static Iam initService() throws GeneralSecurityException, IOException {
// Use the Application Default Credentials strategy for authentication. For more info, see:
// https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
// Initialize the IAM service, which can be used to send requests to the IAM API.
Iam service =
new Iam.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
new HttpCredentialsAdapter(credential))
.setApplicationName("service-account-keys")
.build();
return service;
}
示例11
private static Iam initService() throws GeneralSecurityException, IOException {
// Use the Application Default Credentials strategy for authentication. For more info, see:
// https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
// Initialize the IAM service, which can be used to send requests to the IAM API.
Iam service =
new Iam.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
new HttpCredentialsAdapter(credential))
.setApplicationName("service-accounts")
.build();
return service;
}
示例12
private static Iam initService() throws GeneralSecurityException, IOException {
// Use the Application Default Credentials strategy for authentication. For more info, see:
// https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
// Initialize the IAM service, which can be used to send requests to the IAM API.
Iam service =
new Iam.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
new HttpCredentialsAdapter(credential))
.setApplicationName("service-accounts")
.build();
return service;
}
示例13
private static Iam initService() throws GeneralSecurityException, IOException {
// Use the Application Default Credentials strategy for authentication. For more info, see:
// https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
// Initialize the IAM service, which can be used to send requests to the IAM API.
Iam service =
new Iam.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
new HttpCredentialsAdapter(credential))
.setApplicationName("service-accounts")
.build();
return service;
}
示例14
private static Iam initService() throws GeneralSecurityException, IOException {
// Use the Application Default Credentials strategy for authentication. For more info, see:
// https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
// Initialize the IAM service, which can be used to send requests to the IAM API.
Iam service =
new Iam.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
new HttpCredentialsAdapter(credential))
.setApplicationName("service-account-keys")
.build();
return service;
}
示例15
private static Iam initService() throws GeneralSecurityException, IOException {
// Use the Application Default Credentials strategy for authentication. For more info, see:
// https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
// Initialize the IAM service, which can be used to send requests to the IAM API.
Iam service =
new Iam.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
new HttpCredentialsAdapter(credential))
.setApplicationName("service-account-keys")
.build();
return service;
}
示例16
public static CloudResourceManager initializeService()
throws IOException, GeneralSecurityException {
// Use the Application Default Credentials strategy for authentication. For more info, see:
// https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
// Creates the Cloud Resource Manager service object.
CloudResourceManager service =
new CloudResourceManager.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
new HttpCredentialsAdapter(credential))
.setApplicationName("service-accounts")
.build();
return service;
}
示例17
private static Iam initService() throws GeneralSecurityException, IOException {
// Use the Application Default Credentials strategy for authentication. For more info, see:
// https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
// Initialize the IAM service, which can be used to send requests to the IAM API.
Iam service =
new Iam.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
new HttpCredentialsAdapter(credential))
.setApplicationName("service-accounts")
.build();
return service;
}
示例18
private String getServiceAccountIdTokenUsingAccessToken(GoogleCredentials credentials,
String serviceAccount, String targetAudience)
throws IOException {
final String tokenServerUrl = "https://oauth2.googleapis.com/token";
final Header header = jwtHeader();
final JsonWebToken.Payload payload = jwtPayload(
targetAudience, serviceAccount, tokenServerUrl);
final Iam iam = new Iam.Builder(httpTransport, JSON_FACTORY,
new HttpCredentialsAdapter(withScopes(credentials, IamScopes.all()))).build();
final String content = Base64.encodeBase64URLSafeString(JSON_FACTORY.toByteArray(header)) + "."
+ Base64.encodeBase64URLSafeString(JSON_FACTORY.toByteArray(payload));
byte[] contentBytes = StringUtils.getBytesUtf8(content);
final SignBlobResponse signResponse;
try {
signResponse = iam.projects().serviceAccounts()
.signBlob("projects/-/serviceAccounts/" + serviceAccount, new SignBlobRequest()
.encodeBytesToSign(contentBytes))
.execute();
} catch (GoogleJsonResponseException e) {
if (e.getStatusCode() == 403) {
throw new IOException(
"Unable to sign request for id token, missing Service Account Token Creator role for self on "
+ serviceAccount + " or IAM api not enabled?", e);
}
throw e;
}
final String assertion = content + "." + signResponse.getSignature();
final TokenRequest request = new TokenRequest(
httpTransport, JSON_FACTORY,
new GenericUrl(tokenServerUrl),
"urn:ietf:params:oauth:grant-type:jwt-bearer");
request.put("assertion", assertion);
final TokenResponse tokenResponse = request.execute();
return (String) tokenResponse.get("id_token");
}
示例19
@VisibleForTesting
GoogleCredential loadCredential() {
try {
return GoogleCredential.getApplicationDefault().createScoped(IamScopes.all());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
示例20
private void setUpServiceAccounts() throws IOException {
// Create workflow service account
iam = new Iam.Builder(
Utils.getDefaultTransport(), Utils.getDefaultJsonFactory(),
GoogleCredential.getApplicationDefault().createScoped(IamScopes.all()))
.setApplicationName(testNamespace)
.build();
workflowServiceAccount = iam.projects().serviceAccounts()
.create("projects/styx-oss-test",
new CreateServiceAccountRequest().setAccountId(workflowServiceAccountId)
.setServiceAccount(new ServiceAccount().setDisplayName(testNamespace)))
.execute();
log.info("Created workflow test service account: {}", workflowServiceAccount.getEmail());
// Set up workflow service account permissions
var workflowServiceAccountFqn = "projects/styx-oss-test/serviceAccounts/" + workflowServiceAccount.getEmail();
var workflowServiceAccountPolicy = iam.projects().serviceAccounts()
.getIamPolicy(workflowServiceAccountFqn)
.execute();
if (workflowServiceAccountPolicy.getBindings() == null) {
workflowServiceAccountPolicy.setBindings(new ArrayList<>());
}
workflowServiceAccountPolicy.getBindings()
.add(new Binding().setRole("projects/styx-oss-test/roles/StyxWorkflowServiceAccountUser")
.setMembers(List.of("serviceAccount:[email protected]")));
// TODO: set up a styx service account instead of using [email protected]
workflowServiceAccountPolicy.getBindings()
.add(new Binding().setRole("roles/iam.serviceAccountKeyAdmin")
.setMembers(List.of("serviceAccount:[email protected]")));
iam.projects().serviceAccounts().setIamPolicy(workflowServiceAccountFqn,
new SetIamPolicyRequest().setPolicy(workflowServiceAccountPolicy))
.execute();
}
示例21
public static void main(String[] args) throws Exception {
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
Iam service =
new Iam.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
new HttpCredentialsAdapter(credential))
.setApplicationName("grantable-roles")
.build();
String fullResourceName = args[0];
// [START iam_view_grantable_roles]
QueryGrantableRolesRequest request = new QueryGrantableRolesRequest();
request.setFullResourceName(fullResourceName);
QueryGrantableRolesResponse response = service.roles().queryGrantableRoles(request).execute();
for (Role role : response.getRoles()) {
System.out.println("Title: " + role.getTitle());
System.out.println("Name: " + role.getName());
System.out.println("Description: " + role.getDescription());
System.out.println();
}
// [END iam_view_grantable_roles]
}
示例22
static ServiceAccountUsageAuthorizer create(String serviceAccountUserRole,
AuthorizationPolicy authorizationPolicy,
GoogleCredentials credentials,
String gsuiteUserEmail,
String serviceName,
String message,
List<String> administrators,
List<String> blacklist) {
final HttpTransport httpTransport;
try {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
} catch (GeneralSecurityException | IOException e) {
throw new RuntimeException(e);
}
final JsonFactory jsonFactory = Utils.getDefaultJsonFactory();
final CloudResourceManager crm = new CloudResourceManager.Builder(
httpTransport, jsonFactory, new HttpCredentialsAdapter(credentials.createScoped(IamScopes.all())))
.setApplicationName(serviceName)
.build();
final Iam iam = new Iam.Builder(
httpTransport, jsonFactory, new HttpCredentialsAdapter(credentials.createScoped(IamScopes.all())))
.setApplicationName(serviceName)
.build();
final GoogleCredential directoryCredential = new ManagedServiceAccountKeyCredential.Builder(iam)
.setServiceAccountId(ServiceAccounts.serviceAccountEmail(credentials))
.setServiceAccountUser(gsuiteUserEmail)
.setServiceAccountScopes(Set.of(ADMIN_DIRECTORY_GROUP_MEMBER_READONLY))
.build();
final Directory directory = new Directory.Builder(httpTransport, jsonFactory, directoryCredential)
.setApplicationName(serviceName)
.build();
return new Impl(iam, crm, directory, serviceAccountUserRole, authorizationPolicy,
Impl.DEFAULT_WAIT_STRATEGY, Impl.DEFAULT_RETRY_STOP_STRATEGY, message, administrators, blacklist);
}