com.google.auth.oauth2.ComputeEngineCredentials Java Examples
The following examples show how to use
com.google.auth.oauth2.ComputeEngineCredentials.
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: ComputeEngineChannelBuilder.java From grpc-java with Apache License 2.0 | 6 votes |
private ComputeEngineChannelBuilder(String target) { delegate = NettyChannelBuilder.forTarget(target); SslContext sslContext; try { sslContext = GrpcSslContexts.forClient().build(); } catch (SSLException e) { throw new RuntimeException(e); } InternalNettyChannelBuilder.setProtocolNegotiatorFactory( delegate(), new GoogleDefaultProtocolNegotiatorFactory( /* targetServiceAccounts= */ ImmutableList.<String>of(), SharedResourcePool.forResource(HandshakerServiceChannel.SHARED_HANDSHAKER_CHANNEL), sslContext)); CallCredentials credentials = MoreCallCredentials.from(ComputeEngineCredentials.create()); Status status = Status.OK; if (!CheckGcpEnvironment.isOnGcp()) { status = Status.INTERNAL.withDescription( "Compute Engine Credentials can only be used on Google Cloud Platform"); } delegate().intercept(new CallCredentialsInterceptor(credentials, status)); }
Example #2
Source File: AbstractInteropTest.java From grpc-nebula-java with Apache License 2.0 | 5 votes |
/** Sends a large unary rpc with compute engine credentials. */ public void computeEngineCreds(String serviceAccount, String oauthScope) throws Exception { ComputeEngineCredentials credentials = ComputeEngineCredentials.create(); 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); assertEquals(serviceAccount, response.getUsername()); assertFalse(response.getOauthScope().isEmpty()); assertTrue("Received oauth scope: " + response.getOauthScope(), oauthScope.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 #3
Source File: CredentialsFactoryTest.java From localization_nifi with Apache License 2.0 | 5 votes |
@Test public void testComputeEngineCredentials() throws Exception { final TestRunner runner = TestRunners.newTestRunner(MockCredentialsFactoryProcessor.class); runner.setProperty(CredentialPropertyDescriptors.USE_COMPUTE_ENGINE_CREDENTIALS, "true"); runner.assertValid(); Map<PropertyDescriptor, String> properties = runner.getProcessContext().getProperties(); final CredentialsFactory factory = new CredentialsFactory(); final GoogleCredentials credentials = factory.getGoogleCredentials(properties); assertNotNull(credentials); assertEquals("credentials class should be equal", ComputeEngineCredentials.class, credentials.getClass()); }
Example #4
Source File: ComputeEngineAccessTokenProvider.java From curiostack with MIT License | 5 votes |
@Override protected CompletableFuture<AggregatedHttpResponse> fetchToken(Type type) { URI uri = URI.create(ComputeEngineCredentials.getTokenServerEncodedUrl()); // In practice, this URL shouldn't change at runtime but it's not infeasible, and since this // shouldn't be executed often, just create a client every time. WebClient client = WebClient.builder("h1c://" + uri.getAuthority() + "/") .decorator(LoggingClient.builder().newDecorator()) .build(); return client .execute(RequestHeaders.of(HttpMethod.GET, uri.getPath(), METADATA_FLAVOR_HEADER, "Google")) .aggregate(); }
Example #5
Source File: AccessTokenProvider.java From curiostack with MIT License | 5 votes |
public AccessTokenProvider create(Credentials credentials) { if (credentials instanceof UserCredentials) { return new UserCredentialsAccessTokenProvider( googleAccountsClient, clock, (UserCredentials) credentials); } else if (credentials instanceof ServiceAccountCredentials) { return new ServiceAccountAccessTokenProvider( googleAccountsClient, clock, (ServiceAccountCredentials) credentials); } else if (credentials instanceof ComputeEngineCredentials) { return new ComputeEngineAccessTokenProvider(googleAccountsClient, clock); } throw new IllegalArgumentException("Unsupported credentials type: " + credentials); }
Example #6
Source File: GoogleIdTokenAuth.java From styx with Apache License 2.0 | 5 votes |
private String getToken(String targetAudience, GoogleCredentials credentials) throws IOException, GeneralSecurityException { if (credentials instanceof ServiceAccountCredentials) { return getServiceAccountToken((ServiceAccountCredentials) credentials, targetAudience); } else if (credentials instanceof UserCredentials) { return getUserToken((UserCredentials) credentials); } else if (credentials instanceof ComputeEngineCredentials) { return getDefaultGCEIdToken(targetAudience); } else if (credentials instanceof ImpersonatedCredentials) { return getImpersonatedIdToken((ImpersonatedCredentials) credentials, targetAudience); } else { // Assume a type of service account credential return getServiceAccountIdTokenUsingAccessToken(credentials, targetAudience); } }
Example #7
Source File: GoogleIdTokenAuthTest.java From styx with Apache License 2.0 | 5 votes |
@Test public void testGCEMetadataToken() throws IOException, GeneralSecurityException, InterruptedException { metadataServer.setDispatcher(new Dispatcher() { @Override public MockResponse dispatch(RecordedRequest request) { final MockResponse response = new MockResponse() .setHeader("Metadata-Flavor", "Google"); if (request.getPath().equals("/")) { return response; } if (!"Google".equals(request.getHeader("Metadata-Flavor"))) { return response.setResponseCode(404); } if (request.getPath().startsWith("/computeMetadata/v1/instance/service-accounts/default/identity?")) { return response .setBody(TEST_ID_TOKEN) .setHeader("Metadata-Flavor", "Google"); } return response.setResponseCode(404); } }); metadataServer.start(); environmentVariables.set("GCE_METADATA_HOST", "127.0.0.1:" + metadataServer.getPort()); final GoogleIdTokenAuth idTokenAuth = GoogleIdTokenAuth.of(ComputeEngineCredentials.create()); final Optional<String> token = idTokenAuth.getToken("http://styx.foo.bar"); assertThat(token, is(Optional.of(TEST_ID_TOKEN))); final RecordedRequest tokenRequest = metadataServer.takeRequest(); assertThat(tokenRequest.getPath(), is("/computeMetadata/v1/instance/service-accounts/default/identity" + "?audience=http://styx.foo.bar&format=full")); assertThat(tokenRequest.getHeader("Metadata-Flavor"), is("Google")); }
Example #8
Source File: AuthExample.java From java-docs-samples with Apache License 2.0 | 5 votes |
static void authCompute() { // Explicitly request service account credentials from the compute engine instance. GoogleCredentials credentials = ComputeEngineCredentials.create(); Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService(); System.out.println("Buckets:"); Page<Bucket> buckets = storage.list(); for (Bucket bucket : buckets.iterateAll()) { System.out.println(bucket.toString()); } }
Example #9
Source File: AbstractInteropTest.java From grpc-java with Apache License 2.0 | 5 votes |
/** Sends a large unary rpc with compute engine credentials. */ public void computeEngineCreds(String serviceAccount, String oauthScope) throws Exception { ComputeEngineCredentials credentials = ComputeEngineCredentials.create(); 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); assertEquals(serviceAccount, response.getUsername()); assertFalse(response.getOauthScope().isEmpty()); assertTrue("Received oauth scope: " + response.getOauthScope(), oauthScope.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 #10
Source File: CredentialsFactoryTest.java From nifi with Apache License 2.0 | 5 votes |
@Test public void testComputeEngineCredentials() throws Exception { final TestRunner runner = TestRunners.newTestRunner(MockCredentialsFactoryProcessor.class); runner.setProperty(CredentialPropertyDescriptors.USE_COMPUTE_ENGINE_CREDENTIALS, "true"); runner.assertValid(); Map<PropertyDescriptor, String> properties = runner.getProcessContext().getProperties(); final CredentialsFactory factory = new CredentialsFactory(); final GoogleCredentials credentials = factory.getGoogleCredentials(properties, TRANSPORT_FACTORY); assertNotNull(credentials); assertEquals("credentials class should be equal", ComputeEngineCredentials.class, credentials.getClass()); }
Example #11
Source File: ComputeEngineCredentialsStrategy.java From localization_nifi with Apache License 2.0 | 4 votes |
@Override public GoogleCredentials getGoogleCredentials(Map<PropertyDescriptor, String> properties) throws IOException { return new ComputeEngineCredentials(); }
Example #12
Source File: CloudSpannerDriverTest.java From spanner-jdbc with MIT License | 4 votes |
@Test public void testCredentials() throws Exception { CloudSpannerDriver driver = CloudSpannerDriver.getDriver(); assertNotNull(driver); // get connection without any credentials CloudSpannerConnection connection = (CloudSpannerConnection) DriverManager.getConnection( "jdbc:cloudspanner://localhost;Project=adroit-hall-123;Instance=test-instance;Database=testdb2"); // allow ComputeEngineCredentials as this is the default when running on Travis GoogleCredentials def = null; try { def = GoogleCredentials.getApplicationDefault(); } catch (IOException e) { // ignore } assertTrue(NoCredentials.getInstance() .equals(connection.getSpanner().getOptions().getCredentials()) || connection.getSpanner().getOptions().getCredentials().getClass() .equals(ComputeEngineCredentials.class) || (def != null && connection.getSpanner().getOptions().getCredentials().equals(def))); EnvironmentVariablesUtil.clearCachedDefaultCredentials(); // get connection with application default credentials env.set("GOOGLE_APPLICATION_CREDENTIALS", "cloudspanner-emulator-key.json"); connection = (CloudSpannerConnection) DriverManager.getConnection( "jdbc:cloudspanner://localhost;Project=adroit-hall-123;Instance=test-instance;Database=testdb2"); assertEquals( GoogleCredentials.fromStream(new FileInputStream("cloudspanner-emulator-key.json")), connection.getSpanner().getOptions().getCredentials()); EnvironmentVariablesUtil.clearCachedDefaultCredentials(); // get connection without any credentials again env.clear("GOOGLE_APPLICATION_CREDENTIALS"); connection = (CloudSpannerConnection) DriverManager.getConnection( "jdbc:cloudspanner://localhost;Project=adroit-hall-123;Instance=test-instance;Database=testdb2"); // allow ComputeEngineCredentials as this is the default when running on Travis assertTrue( NoCredentials.getInstance().equals(connection.getSpanner().getOptions().getCredentials()) || connection.getSpanner().getOptions().getCredentials().getClass() .equals(ComputeEngineCredentials.class)); EnvironmentVariablesUtil.clearCachedDefaultCredentials(); }
Example #13
Source File: DefaultCredentialsProvider.java From spring-cloud-gcp with Apache License 2.0 | 4 votes |
/** * The credentials provided by this object originate from the following sources: * <ul> * <li>*.credentials.location: Credentials built from JSON content inside the file pointed * to by this property,</li> * <li>*.credentials.encoded-key: Credentials built from JSON String, encoded on * base64,</li> * <li>Google Cloud Client Libraries default credentials provider.</li> * </ul> * * <p>If credentials are provided by one source, the next sources are discarded. * @param credentialsSupplier provides properties that can override OAuth2 * scopes list used by the credentials, and the location of the OAuth2 credentials private * key. * @throws IOException if an issue occurs creating the DefaultCredentialsProvider */ public DefaultCredentialsProvider(CredentialsSupplier credentialsSupplier) throws IOException { List<String> scopes = resolveScopes(credentialsSupplier.getCredentials().getScopes()); Resource providedLocation = credentialsSupplier.getCredentials().getLocation(); String encodedKey = credentialsSupplier.getCredentials().getEncodedKey(); if (!StringUtils.isEmpty(providedLocation)) { this.wrappedCredentialsProvider = FixedCredentialsProvider .create(GoogleCredentials.fromStream( providedLocation.getInputStream()) .createScoped(scopes)); } else if (!StringUtils.isEmpty(encodedKey)) { this.wrappedCredentialsProvider = FixedCredentialsProvider.create( GoogleCredentials.fromStream( new ByteArrayInputStream(Base64.getDecoder().decode(encodedKey))) .createScoped(scopes)); } else { this.wrappedCredentialsProvider = GoogleCredentialsProvider.newBuilder() .setScopesToApply(scopes) .build(); } try { Credentials credentials = this.wrappedCredentialsProvider.getCredentials(); if (LOGGER.isInfoEnabled()) { if (credentials instanceof UserCredentials) { LOGGER.info("Default credentials provider for user " + ((UserCredentials) credentials).getClientId()); } else if (credentials instanceof ServiceAccountCredentials) { LOGGER.info("Default credentials provider for service account " + ((ServiceAccountCredentials) credentials).getClientEmail()); } else if (credentials instanceof ComputeEngineCredentials) { LOGGER.info("Default credentials provider for Google Compute Engine."); } LOGGER.info("Scopes in use by default credentials: " + scopes.toString()); } } catch (IOException ioe) { LOGGER.warn("No core credentials are set. Service-specific credentials " + "(e.g., spring.cloud.gcp.pubsub.credentials.*) should be used if your app uses " + "services that require credentials.", ioe); } }
Example #14
Source File: ComputeEngineCredentialsBuilder.java From heroic with Apache License 2.0 | 4 votes |
@Override public CredentialOptions build() { return CredentialOptions.credential(ComputeEngineCredentials.create()); }
Example #15
Source File: ComputeEngineCredentialsStrategy.java From nifi with Apache License 2.0 | 4 votes |
@Override public GoogleCredentials getGoogleCredentials(Map<PropertyDescriptor, String> properties, HttpTransportFactory transportFactory) throws IOException { return ComputeEngineCredentials.newBuilder() .setHttpTransportFactory(transportFactory) .build(); }