com.google.api.services.iam.v1.IamScopes Java Examples

The following examples show how to use com.google.api.services.iam.v1.IamScopes. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GetPolicy.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #2
Source File: DeleteServiceAccount.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #3
Source File: QuickstartV2.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #4
Source File: DeleteServiceAccountKey.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #5
Source File: CreateServiceAccountKey.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #6
Source File: ListServiceAccounts.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #7
Source File: RenameServiceAccount.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #8
Source File: EnableServiceAccount.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #9
Source File: ListServiceAccountKeys.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #10
Source File: SetPolicy.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #11
Source File: GCPServiceAccount.java    From policyscanner with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #12
Source File: TestPermissions.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #13
Source File: CreateServiceAccount.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #14
Source File: DisableServiceAccount.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #15
Source File: ServiceAccountCleanupTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@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);
    }
  }
}
 
Example #16
Source File: StyxScheduler.java    From styx with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example #17
Source File: ManagedServiceAccountKeyCredentialTest.java    From styx with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #18
Source File: EndToEndTestBase.java    From styx with Apache License 2.0 5 votes vote down vote up
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 styx-circle-ci@
  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();
}
 
Example #19
Source File: AuthenticatorFactory.java    From styx with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
GoogleCredential loadCredential() {
  try {
    return GoogleCredential.getApplicationDefault().createScoped(IamScopes.all());
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #20
Source File: GrantableRoles.java    From java-docs-samples with Apache License 2.0 5 votes vote down vote up
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]
  }
 
Example #21
Source File: GoogleIdTokenAuth.java    From styx with Apache License 2.0 5 votes vote down vote up
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");
}
 
Example #22
Source File: ServiceAccountUsageAuthorizer.java    From styx with Apache License 2.0 4 votes vote down vote up
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);
}