/** * Example of creating a signed URL for the blob passing the {@link * SignUrlOption#signWith(ServiceAccountSigner)} option, that will be used to sign the URL. */ // [TARGET signUrl(long, TimeUnit, SignUrlOption...)] // [VARIABLE "/path/to/key.json"] public URL signUrlWithSigner(String keyPath) throws IOException { // [START signUrlWithSigner] URL signedUrl = blob.signUrl( 14, TimeUnit.DAYS, SignUrlOption.signWith( ServiceAccountCredentials.fromStream(new FileInputStream(keyPath)))); // [END signUrlWithSigner] return signedUrl; }
private Subscriber createSubscriberWithCustomCredentials() throws Exception { // [START pubsub_subscriber_custom_credentials] CredentialsProvider credentialsProvider = FixedCredentialsProvider.create( ServiceAccountCredentials.fromStream(new FileInputStream("credentials.json"))); Subscriber subscriber = Subscriber.newBuilder(subscriptionName, receiver) .setCredentialsProvider(credentialsProvider) .build(); // [END pubsub_subscriber_custom_credentials] return subscriber; }
private Publisher createPublisherWithCustomCredentials(ProjectTopicName topicName) throws Exception { // [START pubsub_publisher_custom_credentials] // read service account credentials from file CredentialsProvider credentialsProvider = FixedCredentialsProvider.create( ServiceAccountCredentials.fromStream(new FileInputStream("credentials.json"))); Publisher publisher = Publisher.newBuilder(topicName).setCredentialsProvider(credentialsProvider).build(); // [END pubsub_publisher_custom_credentials] return publisher; } }
/** * Example of creating a signed URL passing the {@link * SignUrlOption#signWith(ServiceAccountSigner)} option, that will be used for signing the URL. */ // [TARGET signUrl(BlobInfo, long, TimeUnit, SignUrlOption...)] // [VARIABLE "my_unique_bucket"] // [VARIABLE "my_blob_name"] // [VARIABLE "/path/to/key.json"] public URL signUrlWithSigner(String bucketName, String blobName, String keyPath) throws IOException { // [START signUrlWithSigner] URL signedUrl = storage.signUrl( BlobInfo.newBuilder(bucketName, blobName).build(), 14, TimeUnit.DAYS, SignUrlOption.signWith( ServiceAccountCredentials.fromStream(new FileInputStream(keyPath)))); // [END signUrlWithSigner] return signedUrl; }
/** * Creates a {@code RemoteLoggingHelper} object for the given project id and JSON key input * stream. * * @param projectId id of the project to be used for running the tests * @param keyStream input stream for a JSON key * @return A {@code RemoteLoggingHelper} object for the provided options * @throws com.google.cloud.logging.testing.RemoteLoggingHelper.LoggingHelperException if {@code * keyStream} is not a valid JSON key stream */ public static RemoteLoggingHelper create(String projectId, InputStream keyStream) throws LoggingHelperException { try { GrpcTransportOptions transportOptions = LoggingOptions.getDefaultGrpcTransportOptions(); LoggingOptions storageOptions = LoggingOptions.newBuilder() .setCredentials(ServiceAccountCredentials.fromStream(keyStream)) .setProjectId(projectId) .setRetrySettings(retrySettings()) .setTransportOptions(transportOptions) .build(); return new RemoteLoggingHelper(storageOptions); } catch (IOException ex) { if (log.isLoggable(Level.WARNING)) { log.log(Level.WARNING, ex.getMessage()); } throw LoggingHelperException.translate(ex); } }
/** * Creates a {@code RemoteComputeHelper} object for the given project id and JSON key input * stream. * * @param projectId id of the project to be used for running the tests * @param keyStream input stream for a JSON key * @return A {@code RemoteComputeHelper} object for the provided options * @throws ComputeHelperException if {@code keyStream} is not a valid JSON key stream */ public static RemoteComputeHelper create(String projectId, InputStream keyStream) { try { HttpTransportOptions transportOptions = ComputeOptions.getDefaultHttpTransportOptions(); transportOptions = transportOptions.toBuilder().setConnectTimeout(60000).setReadTimeout(60000).build(); ComputeOptions computeOptions = ComputeOptions.newBuilder() .setCredentials(ServiceAccountCredentials.fromStream(keyStream)) .setProjectId(projectId) .setRetrySettings(retrySettings()) .setTransportOptions(transportOptions) .build(); return new RemoteComputeHelper(computeOptions); } catch (IOException ex) { if (log.isLoggable(Level.WARNING)) { log.log(Level.WARNING, ex.getMessage()); } throw ComputeHelperException.translate(ex); } }
BigQueryOptions bigqueryOptions = BigQueryOptions.newBuilder() .setCredentials(ServiceAccountCredentials.fromStream(keyStream)) .setProjectId(projectId) .setRetrySettings(retrySettings())
public static void explicit() throws IOException { // Load credentials from JSON key file. If you can't set the GOOGLE_APPLICATION_CREDENTIALS // environment variable, you can explicitly load the credentials file to construct the // credentials. GoogleCredentials credentials; File credentialsPath = new File("service_account.json"); // TODO: update to your key path. try (FileInputStream serviceAccountStream = new FileInputStream(credentialsPath)) { credentials = ServiceAccountCredentials.fromStream(serviceAccountStream); } // Instantiate a client. BigQuery bigquery = BigQueryOptions.newBuilder().setCredentials(credentials).build().getService(); // Use the client. System.out.println("Datasets:"); for (Dataset dataset : bigquery.listDatasets().iterateAll()) { System.out.printf("%s%n", dataset.getDatasetId().getDataset()); } } // [END bigquery_client_json_credentials]
/** * Returns credentials defined by a Service Account key file in JSON format from the Google * Developers Console. * * @param credentialsStream the stream with the credential definition. * @return the credential defined by the credentialsStream. * @throws IOException if the credential cannot be created from the stream. **/ public static ServiceAccountCredentials fromStream(InputStream credentialsStream) throws IOException { return fromStream(credentialsStream, OAuth2Utils.HTTP_TRANSPORT_FACTORY); }
/** * Returns credentials defined by a Service Account key file in JSON format from the Google * Developers Console. * * @param credentialsStream the stream with the credential definition. * @return the credential defined by the credentialsStream. * @throws IOException if the credential cannot be created from the stream. **/ public static ServiceAccountCredentials fromStream(InputStream credentialsStream) throws IOException { return fromStream(credentialsStream, OAuth2Utils.HTTP_TRANSPORT_FACTORY); }
@Inject public CredentialsProvider( @Property(GoogleCloudAccessToken.class) String googleCloudAccessTokenFilename) throws IOException { credentials = ServiceAccountCredentials.fromStream(new FileInputStream(googleCloudAccessTokenFilename)); }
@Override public Credentials getCredentials() { try { return ServiceAccountCredentials.fromStream( new ByteArrayInputStream(credentialJsonFromEnv().getBytes("UTF-8"))); } catch (IOException e) { throw new RuntimeException("Failed to load service account credentials from file", e); } }
@Override public Credentials getCredentials() throws IOException { if (StringUtils.isNotEmpty(this.jsonPath)) { try { return ServiceAccountCredentials.fromStream(new FileInputStream(this.jsonPath)); } catch (IOException e) { log.error("Could not import Google Pubsub json credentials: {}", e.getMessage()); } } else { try { return GoogleCredentials.getApplicationDefault(); } catch (IOException e) { log.error("Could not import default application credentials: {}", e.getMessage()); } } throw new IllegalStateException("Unable to authenticate to Google Pubsub."); } }
private static void testFromStreamException(InputStream stream, String expectedMessageContent) { try { ServiceAccountCredentials.fromStream(stream, DUMMY_TRANSPORT_FACTORY); fail(String.format("Should throw exception with message containing '%s'", expectedMessageContent)); } catch (IOException expected) { assertTrue(expected.getMessage().contains(expectedMessageContent)); } } }
@Test public void fromStream_nullTransport_throws() throws IOException { InputStream stream = new ByteArrayInputStream("foo".getBytes()); try { ServiceAccountCredentials.fromStream(stream, null); fail("Should throw if HttpTransportFactory is null"); } catch (NullPointerException expected) { // Expected } }
private Bucket getBucket(String editAddress) throws ContentAccessException { File credentialsFile = getCredentialsFile(); if (credentialsFile == null) { throw new ContentAccessException("Google service account credentials not found. " + "Please set the credentialsFile property or the GOOGLE_APPLICATION_CREDENTIALS environment variable"); } if (!credentialsFile.exists()) { throw new ContentAccessException("Credentials file does not exist: " + credentialsFile.getAbsolutePath()); } try (FileInputStream credentialsStream = new FileInputStream(credentialsFile)) { Storage storage = StorageOptions.newBuilder() .setCredentials(ServiceAccountCredentials.fromStream(credentialsStream)) .build().getService(); int slash = editAddress.lastIndexOf('/'); String bucketName = editAddress.substring(slash+1); return storage.get(bucketName); } catch (IOException e) { throw new ContentAccessException(e); } }
@Bean @ConditionalOnMissingBean public StackdriverMeterRegistry stackdriverMeterRegistry(StackdriverConfig config, StackdriverProperties props, Clock clock) { return StackdriverMeterRegistry.builder(config) .metricServiceSettings(() -> { MetricServiceSettings.Builder settingsBuilder = MetricServiceSettings.newBuilder(); Resource credentials = props.getServiceAccountCredentials(); if (credentials != null) { settingsBuilder.setCredentialsProvider( FixedCredentialsProvider.create(ServiceAccountCredentials.fromStream(credentials.getInputStream()))); } return settingsBuilder.build(); }) .build(); } }
@Test public void fromStream_nullStream_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); try { ServiceAccountCredentials.fromStream(null, transportFactory); fail("Should throw if InputStream is null"); } catch (NullPointerException expected) { // Expected } }
@Test public void fromStream_nullStream_throws() throws IOException { MockHttpTransportFactory transportFactory = new MockHttpTransportFactory(); try { ServiceAccountCredentials.fromStream(null, transportFactory); fail("Should throw if InputStream is null"); } catch (NullPointerException expected) { // Expected } }
@Test public void fromStream_providesToken() throws IOException { MockTokenServerTransportFactory transportFactory = new MockTokenServerTransportFactory(); transportFactory.transport.addServiceAccount(SA_CLIENT_EMAIL, ACCESS_TOKEN); InputStream serviceAccountStream = writeServiceAccountStream( SA_CLIENT_ID, SA_CLIENT_EMAIL, SA_PRIVATE_KEY_PKCS8, SA_PRIVATE_KEY_ID); GoogleCredentials credentials = ServiceAccountCredentials.fromStream(serviceAccountStream, transportFactory); assertNotNull(credentials); credentials = credentials.createScoped(SCOPES); Map<String, List<String>> metadata = credentials.getRequestMetadata(CALL_URI); TestUtils.assertContainsBearerToken(metadata, ACCESS_TOKEN); }