Java Code Examples for com.google.auth.oauth2.GoogleCredentials#createScoped()
The following examples show how to use
com.google.auth.oauth2.GoogleCredentials#createScoped() .
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: AbstractInteropTest.java From grpc-java with Apache License 2.0 | 9 votes |
/** Sends a unary rpc with raw oauth2 access token credentials. */ public void oauth2AuthToken(String jsonKey, InputStream credentialsStream, String authScope) throws Exception { GoogleCredentials utilCredentials = GoogleCredentials.fromStream(credentialsStream); utilCredentials = utilCredentials.createScoped(Arrays.asList(authScope)); AccessToken accessToken = utilCredentials.refreshAccessToken(); OAuth2Credentials credentials = OAuth2Credentials.create(accessToken); TestServiceGrpc.TestServiceBlockingStub stub = blockingStub .withCallCredentials(MoreCallCredentials.from(credentials)); final SimpleRequest request = SimpleRequest.newBuilder() .setFillUsername(true) .setFillOauthScope(true) .build(); final SimpleResponse response = stub.unaryCall(request); assertFalse(response.getUsername().isEmpty()); assertTrue("Received username: " + response.getUsername(), jsonKey.contains(response.getUsername())); assertFalse(response.getOauthScope().isEmpty()); assertTrue("Received oauth scope: " + response.getOauthScope(), authScope.contains(response.getOauthScope())); }
Example 2
Source File: GoogleAuthClient.java From grpc-java with Apache License 2.0 | 6 votes |
/** * The app requires 2 arguments as described in * @see <a href="../../../../../../GOOGLE_AUTH_EXAMPLE.md">Google Auth Example README</a> * * arg0 = location of the JSON file for the service account you created in the GCP console * arg1 = project name in the form "projects/balmy-cirrus-225307" where "balmy-cirrus-225307" is * the project ID for the project you created. * */ public static void main(String[] args) throws Exception { if (args.length < 2) { logger.severe("Usage: please pass 2 arguments:\n" + "arg0 = location of the JSON file for the service account you created in the GCP console\n" + "arg1 = project name in the form \"projects/xyz\" where \"xyz\" is the project ID of the project you created.\n"); System.exit(1); } GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(args[0])); // We need to create appropriate scope as per https://cloud.google.com/storage/docs/authentication#oauth-scopes credentials = credentials.createScoped(Arrays.asList("https://www.googleapis.com/auth/cloud-platform")); // credentials must be refreshed before the access token is available credentials.refreshAccessToken(); GoogleAuthClient client = new GoogleAuthClient("pubsub.googleapis.com", 443, MoreCallCredentials.from(credentials)); try { client.getTopics(args[1]); } finally { client.shutdown(); } }
Example 3
Source File: StorageFactory.java From java-docs-samples with Apache License 2.0 | 6 votes |
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 4
Source File: TransferClientCreator.java From java-docs-samples with Apache License 2.0 | 6 votes |
/** * Create a Storage Transfer client using user-supplied credentials and other settings. * * @param httpTransport a user-supplied HttpTransport * @param jsonFactory a user-supplied JsonFactory * @param credential a user-supplied Google credential * @return a Storage Transfer client */ public static Storagetransfer createStorageTransferClient( HttpTransport httpTransport, JsonFactory jsonFactory, GoogleCredentials credential) { Preconditions.checkNotNull(httpTransport); Preconditions.checkNotNull(jsonFactory); Preconditions.checkNotNull(credential); // In some cases, you need to add the scope explicitly. if (credential.createScopedRequired()) { credential = credential.createScoped(StoragetransferScopes.all()); } // Please use custom HttpRequestInitializer for automatic // retry upon failures. We provide a simple reference // implementation in the "Retry Handling" section. HttpRequestInitializer initializer = new HttpCredentialsAdapter(credential); return new Storagetransfer.Builder(httpTransport, jsonFactory, initializer) .setApplicationName("storagetransfer-sample") .build(); }
Example 5
Source File: GoogleCredentialsAccessTokenSupplier.java From helios with Apache License 2.0 | 6 votes |
/** * 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 6
Source File: CredentialModule.java From nomulus with Apache License 2.0 | 6 votes |
/** * 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 7
Source File: GoogleKms.java From halyard with Apache License 2.0 | 6 votes |
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 8
Source File: GoogleAuthUtils.java From bazel-buildfarm with Apache License 2.0 | 6 votes |
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 9
Source File: GoogleAuthUtils.java From bazel with Apache License 2.0 | 6 votes |
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 10
Source File: StackdriverSenderFactory.java From micronaut-gcp with Apache License 2.0 | 6 votes |
/** * The {@link StackdriverSender} bean. * @param cloudConfiguration The google cloud configuration * @param credentials The credentials * @param channel The channel to use * @return The sender */ @RequiresGoogleProjectId @Requires(classes = StackdriverSender.class) @Singleton protected @Nonnull Sender stackdriverSender( @Nonnull GoogleCloudConfiguration cloudConfiguration, @Nonnull GoogleCredentials credentials, @Nonnull @Named("stackdriverTraceSenderChannel") ManagedChannel channel) { GoogleCredentials traceCredentials = credentials.createScoped(Arrays.asList(TRACE_SCOPE.toString())); return StackdriverSender.newBuilder(channel) .projectId(cloudConfiguration.getProjectId()) .callOptions(CallOptions.DEFAULT .withCallCredentials(MoreCallCredentials.from(traceCredentials))) .build(); }
Example 11
Source File: AbstractInteropTest.java From grpc-nebula-java with Apache License 2.0 | 6 votes |
/** Sends a unary rpc with raw oauth2 access token credentials. */ public void oauth2AuthToken(String jsonKey, InputStream credentialsStream, String authScope) throws Exception { GoogleCredentials utilCredentials = GoogleCredentials.fromStream(credentialsStream); utilCredentials = utilCredentials.createScoped(Arrays.asList(authScope)); AccessToken accessToken = utilCredentials.refreshAccessToken(); OAuth2Credentials credentials = OAuth2Credentials.create(accessToken); TestServiceGrpc.TestServiceBlockingStub stub = blockingStub .withCallCredentials(MoreCallCredentials.from(credentials)); final SimpleRequest request = SimpleRequest.newBuilder() .setFillUsername(true) .setFillOauthScope(true) .build(); final SimpleResponse response = stub.unaryCall(request); assertFalse(response.getUsername().isEmpty()); assertTrue("Received username: " + response.getUsername(), jsonKey.contains(response.getUsername())); assertFalse(response.getOauthScope().isEmpty()); assertTrue("Received oauth scope: " + response.getOauthScope(), authScope.contains(response.getOauthScope())); }
Example 12
Source File: AbstractInteropTest.java From grpc-java with Apache License 2.0 | 5 votes |
/** Sends a large unary rpc with service account credentials. */ public void serviceAccountCreds(String jsonKey, InputStream credentialsStream, String authScope) throws Exception { // cast to ServiceAccountCredentials to double-check the right type of object was created. GoogleCredentials credentials = ServiceAccountCredentials.class.cast(GoogleCredentials.fromStream(credentialsStream)); credentials = credentials.createScoped(Arrays.asList(authScope)); TestServiceGrpc.TestServiceBlockingStub stub = blockingStub .withCallCredentials(MoreCallCredentials.from(credentials)); final SimpleRequest request = SimpleRequest.newBuilder() .setFillUsername(true) .setFillOauthScope(true) .setResponseSize(314159) .setPayload(Payload.newBuilder() .setBody(ByteString.copyFrom(new byte[271828]))) .build(); final SimpleResponse response = stub.unaryCall(request); assertFalse(response.getUsername().isEmpty()); assertTrue("Received username: " + response.getUsername(), jsonKey.contains(response.getUsername())); assertFalse(response.getOauthScope().isEmpty()); assertTrue("Received oauth scope: " + response.getOauthScope(), authScope.contains(response.getOauthScope())); final SimpleResponse goldenResponse = SimpleResponse.newBuilder() .setOauthScope(response.getOauthScope()) .setUsername(response.getUsername()) .setPayload(Payload.newBuilder() .setBody(ByteString.copyFrom(new byte[314159]))) .build(); assertResponse(goldenResponse, response); }
Example 13
Source File: CoreSocketFactory.java From cloud-sql-jdbc-socket-factory with Apache License 2.0 | 5 votes |
@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 14
Source File: BigqueryClient.java From beam with Apache License 2.0 | 5 votes |
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 15
Source File: GoogleUtils.java From kork with Apache License 2.0 | 5 votes |
static GoogleCredentials buildGoogleCredentials() throws IOException { GoogleCredentials credentials = GoogleCredentials.getApplicationDefault(); if (credentials.createScopedRequired()) { credentials = credentials.createScoped(Collections.singleton(StorageScopes.DEVSTORAGE_READ_ONLY)); } return credentials; }
Example 16
Source File: ProxyModule.java From nomulus with Apache License 2.0 | 5 votes |
@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 17
Source File: Main.java From cloud-pubsub-samples-java with Apache License 2.0 | 5 votes |
public static void main(final String[] args) throws Exception { if (args.length == 0) { System.err.println("Please specify your project name."); System.exit(1); } final String project = args[0]; ManagedChannelImpl channelImpl = NettyChannelBuilder .forAddress("pubsub.googleapis.com", 443) .negotiationType(NegotiationType.TLS) .build(); GoogleCredentials creds = GoogleCredentials.getApplicationDefault(); // Down-scope the credential to just the scopes required by the service creds = creds.createScoped(Arrays.asList("https://www.googleapis.com/auth/pubsub")); // Intercept the channel to bind the credential ExecutorService executor = Executors.newSingleThreadExecutor(); ClientAuthInterceptor interceptor = new ClientAuthInterceptor(creds, executor); Channel channel = ClientInterceptors.intercept(channelImpl, interceptor); // Create a stub using the channel that has the bound credential PublisherGrpc.PublisherBlockingStub publisherStub = PublisherGrpc.newBlockingStub(channel); ListTopicsRequest request = ListTopicsRequest.newBuilder() .setPageSize(10) .setProject("projects/" + project) .build(); ListTopicsResponse resp = publisherStub.listTopics(request); System.out.println("Found " + resp.getTopicsCount() + " topics."); for (Topic topic : resp.getTopicsList()) { System.out.println(topic.getName()); } }
Example 18
Source File: GoogleCredentialsFactory.java From micronaut-gcp with Apache License 2.0 | 5 votes |
/** * 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 19
Source File: ComputeEngineSample.java From java-docs-samples with Apache License 2.0 | 4 votes |
public static void main(String[] args) { try { httpTransport = GoogleNetHttpTransport.newTrustedTransport(); // Authenticate using Google Application Default Credentials. GoogleCredentials credential = GoogleCredentials.getApplicationDefault(); if (credential.createScopedRequired()) { List<String> scopes = new ArrayList<>(); // Set Google Cloud Storage scope to Full Control. scopes.add(ComputeScopes.DEVSTORAGE_FULL_CONTROL); // Set Google Compute Engine scope to Read-write. scopes.add(ComputeScopes.COMPUTE); credential = credential.createScoped(scopes); } HttpRequestInitializer requestInitializer = new HttpCredentialsAdapter(credential); // Create Compute Engine object for listing instances. Compute compute = new Compute.Builder(httpTransport, JSON_FACTORY, requestInitializer) .setApplicationName(APPLICATION_NAME) .build(); // List out instances, looking for the one created by this sample app. boolean foundOurInstance = printInstances(compute); Operation op; if (foundOurInstance) { op = deleteInstance(compute, SAMPLE_INSTANCE_NAME); } else { op = startInstance(compute, SAMPLE_INSTANCE_NAME); } // Call Compute Engine API operation and poll for operation completion status System.out.println("Waiting for operation completion..."); Operation.Error error = blockUntilComplete(compute, op, OPERATION_TIMEOUT_MILLIS); if (error == null) { System.out.println("Success!"); } else { System.out.println(error.toPrettyString()); } } catch (IOException e) { System.err.println(e.getMessage()); } catch (Throwable t) { t.printStackTrace(); } System.exit(1); }
Example 20
Source File: LabelsSample.java From java-docs-samples with Apache License 2.0 | 4 votes |
/** * 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)); }