Java Code Examples for com.google.auth.oauth2.GoogleCredentials#getApplicationDefault()

The following examples show how to use com.google.auth.oauth2.GoogleCredentials#getApplicationDefault() . 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: GoogleKms.java    From halyard with Apache License 2.0 6 votes vote down vote up
private static GoogleCredentials loadKmsCredential(String jsonPath) throws IOException {
  GoogleCredentials credentials;
  if (!jsonPath.isEmpty()) {
    FileInputStream stream = new FileInputStream(jsonPath);
    credentials = GoogleCredentials.fromStream(stream);
    log.info("Loaded kms credentials from " + jsonPath);
  } else {
    log.info("Using kms default application credentials.");
    credentials = GoogleCredentials.getApplicationDefault();
  }

  if (credentials.createScopedRequired()) {
    credentials = credentials.createScoped(CloudKMSScopes.all());
  }

  return credentials;
}
 
Example 2
Source File: StorageFactory.java    From java-docs-samples with Apache License 2.0 6 votes vote down vote up
private static Storage buildService() throws IOException, GeneralSecurityException {
  HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport();
  JsonFactory jsonFactory = new JacksonFactory();
  GoogleCredentials credential = GoogleCredentials.getApplicationDefault();

  // Depending on the environment that provides the default credentials (for
  // example: Compute Engine, App Engine), the credentials may require us to
  // specify the scopes we need explicitly.  Check for this case, and inject
  // the Cloud Storage scope if required.
  if (credential.createScopedRequired()) {
    Collection<String> scopes = StorageScopes.all();
    credential = credential.createScoped(scopes);
  }

  return new Storage.Builder(transport, jsonFactory, new HttpCredentialsAdapter(credential))
      .setApplicationName("GCS Samples")
      .build();
}
 
Example 3
Source File: GoogleCredentialsAccessTokenSupplier.java    From helios with Apache License 2.0 6 votes vote down vote up
/**
 * Attempt to load Google Credentials with specified scopes.
 * <ol>
 * <li>First check to see if the environment variable HELIOS_GOOGLE_CREDENTIALS is set
 * and points to a readable file</li>
 * <li>Otherwise check if Google Application Default Credentials (ADC) can be loaded</li>
 * </ol>
 *
 * <p>Note that we use a special environment variable of our own in addition to any environment
 * variable that the ADC loading uses (GOOGLE_APPLICATION_CREDENTIALS) in case there is a need
 * for the user to use the latter env var for some other purpose.
 *
 * @return Return a {@link GoogleCredentials}
 */
private static GoogleCredentials getCredentialsWithScopes(final List<String> scopes)
    throws IOException {
  GoogleCredentials credentials = null;

  // first check whether the environment variable is set
  final String googleCredentialsPath = System.getenv("HELIOS_GOOGLE_CREDENTIALS");
  if (googleCredentialsPath != null) {
    final File file = new File(googleCredentialsPath);
    if (file.exists()) {
      try (final FileInputStream s = new FileInputStream(file)) {
        credentials = GoogleCredentials.fromStream(s);
        LOG.info("Using Google Credentials from file: " + file.getAbsolutePath());
      }
    }
  }

  // fallback to application default credentials
  if (credentials == null) {
    credentials = GoogleCredentials.getApplicationDefault();
    LOG.info("Using Google Application Default Credentials");
  }

  return scopes.isEmpty() ? credentials : credentials.createScoped(scopes);
}
 
Example 4
Source File: MyDataStore.java    From smart-home-java with Apache License 2.0 6 votes vote down vote up
public MyDataStore() {
  // Use a service account
  try {
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
    String projectId = System.getenv("GOOGLE_CLOUD_PROJECT");
    FirebaseOptions options =
        new FirebaseOptions.Builder().setCredentials(credentials).setProjectId(projectId).build();
    FirebaseApp.initializeApp(options);
    database = FirestoreClient.getFirestore();
  } catch (Exception e) {
    LOGGER.error("ERROR: invalid service account credentials. See README.");
    LOGGER.error(e.getMessage());

    throw new RuntimeException(e);
  }
}
 
Example 5
Source File: HttpHealthcareApiClient.java    From beam with Apache License 2.0 6 votes vote down vote up
private void initClient() throws IOException {

    credentials = GoogleCredentials.getApplicationDefault();
    // Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
    HttpRequestInitializer requestInitializer =
        new AuthenticatedRetryInitializer(
            credentials.createScoped(
                CloudHealthcareScopes.CLOUD_PLATFORM, StorageScopes.CLOUD_PLATFORM_READ_ONLY));

    client =
        new CloudHealthcare.Builder(
                new NetHttpTransport(), new JacksonFactory(), requestInitializer)
            .setApplicationName("apache-beam-hl7v2-io")
            .build();
    httpClient =
        HttpClients.custom().setRetryHandler(new DefaultHttpRequestRetryHandler(10, false)).build();
  }
 
Example 6
Source File: GoogleAuthUtils.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
private static Credentials newCredentials(
    @Nullable InputStream credentialsFile, List<String> authScopes) throws IOException {
  try {
    GoogleCredentials creds =
        credentialsFile == null
            ? GoogleCredentials.getApplicationDefault()
            : GoogleCredentials.fromStream(credentialsFile);
    if (!authScopes.isEmpty()) {
      creds = creds.createScoped(authScopes);
    }
    return creds;
  } catch (IOException e) {
    String message = "Failed to init auth credentials: " + e.getMessage();
    throw new IOException(message, e);
  }
}
 
Example 7
Source File: CredentialModule.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Provides the default {@link GoogleCredentialsBundle} from the Google Cloud runtime.
 *
 * <p>The credential returned depends on the runtime environment:
 *
 * <ul>
 *   <li>On AppEngine, returns the service account credential for
 *       [email protected]
 *   <li>On Compute Engine, returns the service account credential for
 *       [email protected]
 *   <li>On end user host, this returns the credential downloaded by gcloud. Please refer to <a
 *       href="https://cloud.google.com/sdk/gcloud/reference/auth/application-default/login">Cloud
 *       SDK documentation</a> for details.
 * </ul>
 */
@DefaultCredential
@Provides
@Singleton
public static GoogleCredentialsBundle provideDefaultCredential(
    @Config("defaultCredentialOauthScopes") ImmutableList<String> requiredScopes) {
  GoogleCredentials credential;
  try {
    credential = GoogleCredentials.getApplicationDefault();
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
  if (credential.createScopedRequired()) {
    credential = credential.createScoped(requiredScopes);
  }
  return GoogleCredentialsBundle.create(credential);
}
 
Example 8
Source File: AbstractDockerMojo.java    From dockerfile-maven with Apache License 2.0 5 votes vote down vote up
/**
 * Attempt to load a GCR compatible RegistryAuthSupplier based on a few conditions:
 * <ol>
 * <li>First check to see if the environemnt variable DOCKER_GOOGLE_CREDENTIALS is set and points
 * to a readable file</li>
 * <li>Otherwise check if the Google Application Default Credentials can be loaded</li>
 * </ol>
 * Note that we use a special environment variable of our own in addition to any environment
 * variable that the ADC loading uses (GOOGLE_APPLICATION_CREDENTIALS) in case there is a need for
 * the user to use the latter env var for some other purpose in their build.
 *
 * @return a GCR RegistryAuthSupplier, or null
 * @throws IOException if an IOException occurs while loading the credentials
 */
@Nullable
private RegistryAuthSupplier googleContainerRegistryAuthSupplier() throws IOException {
  GoogleCredentials credentials = null;

  final String googleCredentialsPath = System.getenv("DOCKER_GOOGLE_CREDENTIALS");
  if (googleCredentialsPath != null) {
    final File file = new File(googleCredentialsPath);
    if (file.exists()) {
      try (FileInputStream inputStream = new FileInputStream(file)) {
        credentials = GoogleCredentials.fromStream(inputStream);
        getLog().info("Using Google credentials from file: " + file.getAbsolutePath());
      }
    }
  }

  // use the ADC last
  if (credentials == null) {
    try {
      credentials = GoogleCredentials.getApplicationDefault();
      getLog().info("Using Google application default credentials");
    } catch (IOException ex) {
      // No GCP default credentials available
      getLog().debug("Failed to load Google application default credentials", ex);
    }
  }

  if (credentials == null) {
    return null;
  }

  return ContainerRegistryAuthSupplier.forCredentials(credentials).build();
}
 
Example 9
Source File: GoogleUtils.java    From kork with Apache License 2.0 5 votes vote down vote up
static GoogleCredentials buildGoogleCredentials() throws IOException {
  GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();

  if (credentials.createScopedRequired()) {
    credentials =
        credentials.createScoped(Collections.singleton(StorageScopes.DEVSTORAGE_READ_ONLY));
  }

  return credentials;
}
 
Example 10
Source File: GcpConfiguration.java    From spydra with Apache License 2.0 5 votes vote down vote up
@Override
public Credentials getCredentials() {
  try {
    return GoogleCredentials.getApplicationDefault();
  } catch (IOException e) {
    throw new RuntimeException("Failed to load application default credentials", e);
  }
}
 
Example 11
Source File: BigqueryClient.java    From beam with Apache License 2.0 5 votes vote down vote up
private static Credentials getDefaultCredential() {
  GoogleCredentials credential;
  try {
    credential = GoogleCredentials.getApplicationDefault();
  } catch (IOException e) {
    throw new RuntimeException("Failed to get application default credential.", e);
  }

  if (credential.createScopedRequired()) {
    Collection<String> bigqueryScope = Lists.newArrayList(BigqueryScopes.all());
    credential = credential.createScoped(bigqueryScope);
  }
  return credential;
}
 
Example 12
Source File: ProxyModule.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Singleton
@Provides
static GoogleCredentialsBundle provideCredential(ProxyConfig config) {
  try {
    GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
    if (credentials.createScopedRequired()) {
      credentials = credentials.createScoped(config.gcpScopes);
    }
    return GoogleCredentialsBundle.create(credentials);
  } catch (IOException e) {
    throw new RuntimeException("Unable to obtain OAuth2 credential.", e);
  }
}
 
Example 13
Source File: ComputeExample.java    From google-cloud-java with Apache License 2.0 5 votes vote down vote up
private static AddressClient createCredentialedClient() throws IOException {
  Credentials myCredentials = GoogleCredentials.getApplicationDefault();
  String myEndpoint = AddressSettings.getDefaultEndpoint();

  AddressSettings addressSettings =
      AddressSettings.newBuilder()
          .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
          .setTransportChannelProvider(
              AddressSettings.defaultHttpJsonTransportProviderBuilder()
                  .setEndpoint(myEndpoint)
                  .build())
          .build();
  return AddressClient.create(addressSettings);
}
 
Example 14
Source File: ServiceAccountProvider.java    From gcp-token-broker with Apache License 2.0 5 votes vote down vote up
@Override
public AccessToken getAccessToken(String googleIdentity, List<String> scopes) {
    if (! googleIdentity.endsWith(".iam.gserviceaccount.com")) {
        throw new IllegalArgumentException("Google identity `" + googleIdentity + "` is not a service account");
    }
    try {
        GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
        ImpersonatedCredentials impersonatedCredentials = ImpersonatedCredentials.create(credentials, googleIdentity, null, scopes, 3600);
        com.google.auth.oauth2.AccessToken token = impersonatedCredentials.refreshAccessToken();
        return new AccessToken(token.getTokenValue(), token.getExpirationTime().getTime());
    } catch (IOException e) {
        throw Status.PERMISSION_DENIED.asRuntimeException();
    }
}
 
Example 15
Source File: CoreSocketFactory.java    From cloud-sql-jdbc-socket-factory with Apache License 2.0 5 votes vote down vote up
@Override
public HttpRequestInitializer create() {
  GoogleCredentials credentials;
  try {
    credentials = GoogleCredentials.getApplicationDefault();
  } catch (IOException err) {
    throw new RuntimeException(
        "Unable to obtain credentials to communicate with the Cloud SQL API", err);
  }
  if (credentials.createScopedRequired()) {
    credentials =
        credentials.createScoped(Collections.singletonList(SQLAdminScopes.SQLSERVICE_ADMIN));
  }
  return new HttpCredentialsAdapter(credentials);
}
 
Example 16
Source File: GoogleCredentialsFactory.java    From micronaut-gcp with Apache License 2.0 5 votes vote down vote up
/**
 * Method used to return the default {@link GoogleCredentials} and provide it as a bean.
 *
 * It will determine which credential in the following way:
 * <ol>
 *     <li>If <pre>gcp.credentials.location</pre> is specified, use its location</li>
 *     <li>Otherwise, if <pre>gcp.credentials.encodedKey</pre> is specified, decode it and use its content</li>
 *     <li>None of the 2 properties were specified, use Application Default credential resolution. See
 *     <a href="https://github.com/googleapis/google-cloud-java#authentication">Google Cloud Java authentication</a>.
 *     This will resolve credential in the following order:
 *       <ol>
 *           <li>The credentials file pointed to by the <pre>GOOGLE_APPLICATION_CREDENTIALS</pre> environment variable</li>
 *           <li>Credentials provided by the Google Cloud SDK <pre>gcloud auth application-default login</pre> command</li>
 *           <li>Google App Engine built-in credentials when running inside of Google App Engine</li>
 *           <li>Google Cloud Shell built-in credentials when running inside of Google Cloud Shell</li>
 *           <li>Google Compute Engine built-in credentials when running inside of Google Compute Engine or Kubernetes Engine</li>
 *       </ol>
 *     </li>
 * </ol>
 *
 * @return The {@link GoogleCredentials}
 * @throws IOException An exception if an error occurs
 */
@Requires(missingBeans = GoogleCredentials.class)
@Requires(classes = com.google.auth.oauth2.GoogleCredentials.class)
@Primary
@Singleton
protected GoogleCredentials defaultGoogleCredentials() throws IOException {
    final List<String> scopes = configuration.getScopes().stream()
            .map(URI::toString).collect(Collectors.toList());

    GoogleCredentials credentials;
    if (configuration.getLocation().isPresent() && configuration.getEncodedKey().isPresent()) {
        throw new ConfigurationException("Please specify only one of gcp.credentials.location or gcp.credentials.encodedKey");
    } else if (configuration.getLocation().isPresent()) {
        LOG.info("Google Credentials from gcp.credentials.location = " + configuration.getLocation());
        FileInputStream fis = new FileInputStream(configuration.getLocation().get());
        credentials = GoogleCredentials.fromStream(fis);
        fis.close();
    } else if (configuration.getEncodedKey().isPresent()) {
        LOG.info("Google Credentials from gcp.credentials.encodedKey");
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] bytes = decoder.decode(configuration.getEncodedKey().get());
        ByteArrayInputStream is = new ByteArrayInputStream(bytes);
        credentials = GoogleCredentials.fromStream(is);
        is.close();
    } else {
        LOG.info("Google Credentials from Application Default Credentials");
        credentials = GoogleCredentials.getApplicationDefault();
    }

    return credentials.createScoped(scopes);
}
 
Example 17
Source File: BigQueryCredentialsSupplier.java    From spark-bigquery-connector with Apache License 2.0 5 votes vote down vote up
public static Credentials createDefaultCredentials() {
    try {
        return GoogleCredentials.getApplicationDefault();
    } catch (IOException e) {
        throw new UncheckedIOException("Failed to create default Credentials", e);
    }
}
 
Example 18
Source File: LabelsSample.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
/**
 * Add or modify a label on a dataset.
 *
 * See <a href="https://cloud.google.com/bigquery/docs/labeling-datasets">the BigQuery
 * documentation</a>.
 */
public static void labelDataset(
    String projectId, String datasetId, String labelKey, String labelValue) throws IOException {

  // Authenticate requests using Google Application Default credentials.
  GoogleCredentials credential = GoogleCredentials.getApplicationDefault();
  credential = credential.createScoped(Arrays.asList("https://www.googleapis.com/auth/bigquery"));

  // Get a new access token.
  // Note that access tokens have an expiration. You can reuse a token rather than requesting a
  // new one if it is not yet expired.
  AccessToken accessToken = credential.refreshAccessToken();

  // Set the content of the request.
  Dataset dataset = new Dataset();
  dataset.addLabel(labelKey, labelValue);
  HttpContent content = new JsonHttpContent(JSON_FACTORY, dataset);

  // Send the request to the BigQuery API.
  String urlFormat =
      "https://www.googleapis.com/bigquery/v2/projects/%s/datasets/%s"
          + "?fields=labels&access_token=%s";
  GenericUrl url =
      new GenericUrl(String.format(urlFormat, projectId, datasetId, accessToken.getTokenValue()));
  HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory();
  HttpRequest request = requestFactory.buildPostRequest(url, content);
  request.setParser(JSON_FACTORY.createJsonObjectParser());

  // Workaround for transports which do not support PATCH requests.
  // See: http://stackoverflow.com/a/32503192/101923
  request.setHeaders(new HttpHeaders().set("X-HTTP-Method-Override", "PATCH"));
  HttpResponse response = request.execute();

  // Check for errors.
  if (response.getStatusCode() != 200) {
    throw new RuntimeException(response.getStatusMessage());
  }

  Dataset responseDataset = response.parseAs(Dataset.class);
  System.out.printf(
      "Updated label \"%s\" with value \"%s\"\n",
      labelKey, responseDataset.getLabels().get(labelKey));
}
 
Example 19
Source File: GoogleCloudClientBuilder.java    From paintera with GNU General Public License v2.0 4 votes vote down vote up
private static boolean verifyCredentials() throws IOException
{
	return GoogleCredentials.getApplicationDefault() != null;
}
 
Example 20
Source File: TestApp.java    From gcpsamples with Apache License 2.0 4 votes vote down vote up
public TestApp() {
	try
	{
		/*
		// For GoogleAPIs
		HttpTransport httpTransport = new NetHttpTransport();             
		JacksonFactory jsonFactory = new JacksonFactory();
		//ComputeCredential credential = new ComputeCredential.Builder(httpTransport, jsonFactory).build();	
		GoogleCredential credential = GoogleCredential.getApplicationDefault(httpTransport,jsonFactory);				            
		if (credential.createScopedRequired())
		    credential = credential.createScoped(Arrays.asList(Oauth2Scopes.USERINFO_EMAIL));           				            
		Oauth2 service = new Oauth2.Builder(httpTransport, jsonFactory, credential)
		            .setApplicationName("oauth client")   
		            .build();				            
		Userinfoplus ui = service.userinfo().get().execute();
		System.out.println(ui.getEmail());
		*/

         // Using Google Cloud APIs
	  Storage storage_service = StorageOptions.newBuilder()
		.build()
		.getService();	
	  for (Bucket b : storage_service.list().iterateAll()){
		  System.out.println(b);
	  }

         // String cred_file = "/path/to/cred.json";
	  //GoogleCredentials creds = GoogleCredentials.fromStream(new FileInputStream(cred_file));	
	  GoogleCredentials creds = GoogleCredentials.getApplicationDefault();	  	  
	  FixedCredentialsProvider credentialsProvider = FixedCredentialsProvider.create(creds);
	  
	  ///ManagedChannel channel = ManagedChannelBuilder.forTarget("pubsub.googleapis.com:443").build();
         //TransportChannelProvider channelProvider = FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel));	
	  
	  TransportChannelProvider channelProvider = TopicAdminSettings.defaultTransportChannelProvider();

	  TopicAdminClient topicClient =
		  TopicAdminClient.create(
			  TopicAdminSettings.newBuilder()
				  .setTransportChannelProvider(channelProvider)
				  .setCredentialsProvider(credentialsProvider)
				  .build());

	  ListTopicsRequest listTopicsRequest =
						ListTopicsRequest.newBuilder()
							.setProject(ProjectName.format("your_project"))
							.build();
	  ListTopicsPagedResponse response = topicClient.listTopics(listTopicsRequest);
	  Iterable<Topic> topics = response.iterateAll();
	  for (Topic topic : topics) 
		 System.out.println(topic);
	 		  

	} 
	catch (Exception ex) {
		System.out.println("Error:  " + ex);
	}
}