com.google.auth.Credentials Java Examples

The following examples show how to use com.google.auth.Credentials. 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: HttpProxy.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
public HttpProxy(
    ServerBuilder<?> serverBuilder, @Nullable Credentials creds, HttpProxyOptions options)
    throws URISyntaxException, SSLException {
  super("HttpProxy");
  this.options = options;
  SimpleBlobStore simpleBlobStore =
      HttpBlobStore.create(
          URI.create(options.httpCache),
          /* remoteMaxConnections=*/ 0,
          (int) SECONDS.toMillis(options.timeout),
          creds);
  server =
      serverBuilder
          .addService(new ActionCacheService(simpleBlobStore))
          .addService(
              new ContentAddressableStorageService(
                  simpleBlobStore, options.treeDefaultPageSize, options.treeMaxPageSize))
          .addService(new ByteStreamService(simpleBlobStore))
          .intercept(TransmitStatusRuntimeExceptionInterceptor.instance())
          .build();
}
 
Example #2
Source File: DefaultPubSubSubscriberFactory.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public PubSubSubscriber getSubscriber(Credentials credentials) throws IOException {
	ManagedChannel channel = NettyChannelBuilder.forTarget(SubscriberStubSettings.getDefaultEndpoint())
												.negotiationType(NegotiationType.TLS)
												.sslContext(GrpcSslContexts.forClient().ciphers(null).build())
												.build();

	PullRequest pullRequest = PullRequest.newBuilder()
							.setMaxMessages(maxMessagesPerPull)
							.setReturnImmediately(false)
							.setSubscription(projectSubscriptionName)
							.build();
	SubscriberGrpc.SubscriberBlockingStub stub = SubscriberGrpc.newBlockingStub(channel)
						.withCallCredentials(MoreCallCredentials.from(credentials));
	return new BlockingGrpcPubSubSubscriber(projectSubscriptionName, channel, stub, pullRequest, retries, timeout);
}
 
Example #3
Source File: GoogleAdsVersionFactory.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
private VersionDescriptorInvocationHandler(
    Class<?> interfaceSpec,
    TransportChannelProvider transportChannelProvider,
    Credentials credentials)
    throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
  // Ensure the interface spec is annotated with VersionDescriptor.
  Preconditions.checkArgument(
      interfaceSpec.isAnnotationPresent(VersionDescriptor.class),
      "Missing VersionDescriptor annotation for: %s",
      interfaceSpec);

  this.transportChannelProvider = Preconditions.checkNotNull(transportChannelProvider);
  this.credentials = Preconditions.checkNotNull(credentials);

  // Reflected entities are loaded in the constructor so that any issues are caught at
  // creation/unit-test time, rather than waiting until an API call is made. This should also
  // (slightly) improve performance by avoiding repeated reflections at runtime.
  this.settingsBuilders = cacheSettingsBuilders(interfaceSpec);
  this.clientCreators = cacheClientCreators(interfaceSpec);
}
 
Example #4
Source File: GoogleAdsClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that the loginCustomerId can be unset when cloning the client via builder methods. This
 * is important so that users can easily change the login customer ID.
 */
@Test
public void setLoginCustomerId_canClearOnceSet() {
  Credentials credentials =
      UserCredentials.newBuilder()
          .setClientId(CLIENT_ID)
          .setClientSecret(CLIENT_SECRET)
          .setRefreshToken(REFRESH_TOKEN)
          .build();
  GoogleAdsClient client =
      GoogleAdsClient.newBuilder()
          .setCredentials(credentials)
          .setDeveloperToken(DEVELOPER_TOKEN)
          .setLoginCustomerId(1L)
          .setEnableGeneratedCatalog(enabledGeneratedCatalog)
          .build();
  client = client.toBuilder().setLoginCustomerId(null).build();
  assertNull("Unable to clear loginCustomerId", client.getLoginCustomerId());
}
 
Example #5
Source File: GoogleAdsClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
/**
 * Tests building a client without the use of a properties file.
 */
@Test
public void buildWithoutPropertiesFile_supportsAllFields() throws IOException {
  Credentials credentials =
      UserCredentials.newBuilder()
          .setClientId(CLIENT_ID)
          .setClientSecret(CLIENT_SECRET)
          .setRefreshToken(REFRESH_TOKEN)
          .build();
  GoogleAdsClient client =
      GoogleAdsClient.newBuilder()
          .setCredentials(credentials)
          .setDeveloperToken(DEVELOPER_TOKEN)
          .setLoginCustomerId(LOGIN_CUSTOMER_ID)
          .setEnableGeneratedCatalog(enabledGeneratedCatalog)
          .setTransportChannelProvider(localChannelProvider)
          .build();
  assertGoogleAdsClient(client);
}
 
Example #6
Source File: GoogleAdsClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that builder supports nullable loginCustomerId.
 */
@Test
public void build_loginCustomerId_allowsNullable() {
  Credentials credentials =
      UserCredentials.newBuilder()
          .setClientId(CLIENT_ID)
          .setClientSecret(CLIENT_SECRET)
          .setRefreshToken(REFRESH_TOKEN)
          .build();
  GoogleAdsClient client =
      GoogleAdsClient.newBuilder()
          .setCredentials(credentials)
          .setDeveloperToken(DEVELOPER_TOKEN)
          .setEnableGeneratedCatalog(enabledGeneratedCatalog)
          .build();
  assertNull("invalid login-customer-id", client.getLoginCustomerId());
}
 
Example #7
Source File: GoogleAdsClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
/**
 * Verifies that builder does not require enableGeneratedCatalog to be set explicitly.
 */
@Test
public void build_enableGeneratedCatalog_not_required() throws IOException {
  Credentials credentials =
      UserCredentials.newBuilder()
          .setClientId(CLIENT_ID)
          .setClientSecret(CLIENT_SECRET)
          .setRefreshToken(REFRESH_TOKEN)
          .build();
  GoogleAdsClient client =
      GoogleAdsClient.newBuilder()
          .setCredentials(credentials)
          .setDeveloperToken(DEVELOPER_TOKEN)
          .setLoginCustomerId(LOGIN_CUSTOMER_ID)
          .build();
  assertGoogleAdsClient(client, LOGIN_CUSTOMER_ID, false);
}
 
Example #8
Source File: GoogleAdsClientTest.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
/**
 * Asserts that the provided client matches expectations. Expects a login customer ID that matches
 * the provided value.
 */
private void assertGoogleAdsClient(
    GoogleAdsClient client,
    @Nullable Long loginCustomerId,
    boolean enableGeneratedCatalog)
    throws IOException {
  assertNotNull("Null client", client);

  Credentials credentials = client.getCredentials();
  assertNotNull("Null credentials", credentials);
  assertThat(credentials, Matchers.instanceOf(UserCredentials.class));
  UserCredentials userCredentials = (UserCredentials) credentials;
  assertEquals("Client ID", CLIENT_ID, userCredentials.getClientId());
  assertEquals("Client secret", CLIENT_SECRET, userCredentials.getClientSecret());
  assertEquals("Refresh token", REFRESH_TOKEN, userCredentials.getRefreshToken());

  assertEquals("Developer token", DEVELOPER_TOKEN, client.getDeveloperToken());
  assertEquals("Login customer id", loginCustomerId, client.getLoginCustomerId());
  assertEquals(
      "Enable generated catalog",
      enableGeneratedCatalog,
      client.getEnableGeneratedCatalog());
}
 
Example #9
Source File: PhotosLibraryClientFactory.java    From java-photoslibrary with Apache License 2.0 6 votes vote down vote up
private static Credentials getUserCredentials(String credentialsPath, List<String> selectedScopes)
    throws IOException, GeneralSecurityException {
  GoogleClientSecrets clientSecrets =
      GoogleClientSecrets.load(
          JSON_FACTORY, new InputStreamReader(new FileInputStream(credentialsPath)));
  String clientId = clientSecrets.getDetails().getClientId();
  String clientSecret = clientSecrets.getDetails().getClientSecret();

  GoogleAuthorizationCodeFlow flow =
      new GoogleAuthorizationCodeFlow.Builder(
              GoogleNetHttpTransport.newTrustedTransport(),
              JSON_FACTORY,
              clientSecrets,
              selectedScopes)
          .setDataStoreFactory(new FileDataStoreFactory(DATA_STORE_DIR))
          .setAccessType("offline")
          .build();
  LocalServerReceiver receiver =
      new LocalServerReceiver.Builder().setPort(LOCAL_RECEIVER_PORT).build();
  Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
  return UserCredentials.newBuilder()
      .setClientId(clientId)
      .setClientSecret(clientSecret)
      .setRefreshToken(credential.getRefreshToken())
      .build();
}
 
Example #10
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void googleCredential_integrityDenied() {
  final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
  final Credentials credentials = GoogleCredentials.create(token);
  // Anything less than PRIVACY_AND_INTEGRITY should fail

  GoogleAuthLibraryCallCredentials callCredentials =
      new GoogleAuthLibraryCallCredentials(credentials);
  callCredentials.applyRequestMetadata(
      new RequestInfoImpl(SecurityLevel.INTEGRITY), executor, applier);
  runPendingRunnables();

  verify(applier).fail(statusCaptor.capture());
  Status status = statusCaptor.getValue();
  assertEquals(Status.Code.UNAUTHENTICATED, status.getCode());
}
 
Example #11
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 #12
Source File: GoogleAuthLibraryCallCredentials.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
GoogleAuthLibraryCallCredentials(Credentials creds, JwtHelper jwtHelper) {
  checkNotNull(creds, "creds");
  boolean requirePrivacy = false;
  if (googleCredentialsClass != null) {
    // All GoogleCredentials instances are bearer tokens and should only be used on private
    // channels. This catches all return values from GoogleCredentials.getApplicationDefault().
    // This should be checked before upgrading the Service Account to JWT, as JWT is also a bearer
    // token.
    requirePrivacy = googleCredentialsClass.isInstance(creds);
  }
  if (jwtHelper != null) {
    creds = jwtHelper.tryServiceAccountToJwt(creds);
  }
  this.requirePrivacy = requirePrivacy;
  this.creds = creds;
}
 
Example #13
Source File: LoggingAppender.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
/**
 * Wraps {@link com.google.cloud.logging.logback.LoggingAppender#getLoggingOptions()} to
 * add {@link UserAgentHeaderProvider} configuration, so that usage can be properly
 * attributed to Spring Cloud GCP.
 */
@Override
protected LoggingOptions getLoggingOptions() {

	if (loggingOptions == null) {
		LoggingOptions.Builder loggingOptionsBuilder = LoggingOptions.newBuilder();

		// only credentials are set in the options of the parent class
		Credentials credentials = super.getLoggingOptions().getCredentials();
		if (credentials != null) {
			loggingOptionsBuilder.setCredentials(credentials);
		}

		// set User-Agent
		loggingOptionsBuilder.setHeaderProvider(new UserAgentHeaderProvider(this.getClass()));

		this.loggingOptions = loggingOptionsBuilder.build();
	}

	return this.loggingOptions;
}
 
Example #14
Source File: GoogleAuthUtils.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new {@link Credentials} object, or {@code null} if no options are provided.
 *
 * @throws IOException in case the credentials can't be constructed.
 */
@Nullable
public static Credentials newCredentials(@Nullable AuthAndTLSOptions options) throws IOException {
  if (options == null) {
    return null;
  } else if (options.googleCredentials != null) {
    // Credentials from file
    try (InputStream authFile = new FileInputStream(options.googleCredentials)) {
      return newCredentials(authFile, options.googleAuthScopes);
    } catch (FileNotFoundException e) {
      String message =
          String.format(
              "Could not open auth credentials file '%s': %s",
              options.googleCredentials, e.getMessage());
      throw new IOException(message, e);
    }
  } else if (options.useGoogleDefaultCredentials) {
    return newCredentials(
        null /* Google Application Default Credentials */, options.googleAuthScopes);
  }
  return null;
}
 
Example #15
Source File: StackdriverTraceAutoConfigurationTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Bean
public static CredentialsProvider googleCredentials() {
	return () -> {
		Credentials creds = mock(Credentials.class);
		doAnswer((Answer<Void>)
			(invocationOnMock) -> {
				RequestMetadataCallback callback =
						(RequestMetadataCallback) invocationOnMock.getArguments()[2];
				callback.onSuccess(Collections.emptyMap());
				return null;
			})
		.when(creds)
		.getRequestMetadata(any(), any(), any());
		return creds;
	};
}
 
Example #16
Source File: GoogleConfigPropertySourceLocatorTest.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
	this.gcpConfigProperties = mock(GcpConfigProperties.class);
	when(this.gcpConfigProperties.getName()).thenReturn("test");
	when(this.gcpConfigProperties.isEnabled()).thenReturn(true);
	org.springframework.cloud.gcp.core.Credentials configCredentials =
			mock(org.springframework.cloud.gcp.core.Credentials.class);
	when(this.gcpConfigProperties.getCredentials()).thenReturn(configCredentials);
	when(this.gcpConfigProperties.getProfile()).thenReturn("default");
	this.expectedProperties = new HashMap<>();
	this.expectedProperties.put("property-int", 10);
	this.expectedProperties.put("property-bool", true);
	this.projectIdProvider = () -> "projectid";
	this.credentialsProvider = () -> mock(Credentials.class);

}
 
Example #17
Source File: BigQueryCredentialsSupplier.java    From presto with Apache License 2.0 5 votes vote down vote up
private static Credentials createCredentialsFromFile(String file)
{
    try {
        return GoogleCredentials.fromStream(new FileInputStream(file));
    }
    catch (IOException e) {
        throw new UncheckedIOException("Failed to create Credentials from file", e);
    }
}
 
Example #18
Source File: GcpConfiguration.java    From spydra with Apache License 2.0 5 votes vote down vote up
@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);
  }
}
 
Example #19
Source File: FirestoreDataSink.java    From daq with Apache License 2.0 5 votes vote down vote up
private Credentials getProjectCredentials() throws IOException {
  File credentialFile = new File(System.getenv(ServiceOptions.CREDENTIAL_ENV_NAME));
  if (!credentialFile.exists()) {
    throw new RuntimeException(String.format(CREDENTIAL_ERROR_FORMAT,
        credentialFile.getAbsolutePath(), ServiceOptions.CREDENTIAL_ENV_NAME));
  }
  try (FileInputStream serviceAccount = new FileInputStream(credentialFile)) {
    return GoogleCredentials.fromStream(serviceAccount);
  }
}
 
Example #20
Source File: ExampleUtils.java    From deployment-examples with MIT License 5 votes vote down vote up
private static HttpRequestInitializer chainHttpRequestInitializer(
    Credentials credential, HttpRequestInitializer httpRequestInitializer) {
  if (credential == null) {
    return new ChainingHttpRequestInitializer(
        new NullCredentialInitializer(), httpRequestInitializer);
  } else {
    return new ChainingHttpRequestInitializer(
        new HttpCredentialsAdapter(credential), httpRequestInitializer);
  }
}
 
Example #21
Source File: BigQueryCredentialsSupplier.java    From spark-bigquery-connector with Apache License 2.0 5 votes vote down vote up
public BigQueryCredentialsSupplier(
        Optional<String> accessToken,
        Optional<String> credentialsKey,
        Optional<String> credentialsFile) {
    this.accessToken = accessToken;
    this.credentialsKey = credentialsKey;
    this.credentialsFile = credentialsFile;
    // lazy creation, cache once it's created
    Optional<Credentials> credentialsFromAccessToken = credentialsKey.map(BigQueryCredentialsSupplier::createCredentialsFromAccessToken);
    Optional<Credentials> credentialsFromKey = credentialsKey.map(BigQueryCredentialsSupplier::createCredentialsFromKey);
    Optional<Credentials> credentialsFromFile = credentialsFile.map(BigQueryCredentialsSupplier::createCredentialsFromFile);
    this.credentials = firstPresent(credentialsFromAccessToken, credentialsFromKey, credentialsFromFile)
            .orElse(createDefaultCredentials());
}
 
Example #22
Source File: ApiCatalogImpl.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
/** @inheritDoc */
@Override
public GoogleAdsAllVersions createAllVersionsClient(
    TransportChannelProvider provider, Credentials credentials) {
  Preconditions.checkNotNull(
      provider, "Transport channel provider required to create GoogleAdsAllVersions interface.");
  Preconditions.checkNotNull(
      credentials, "Credentials are required to create GoogleAdsAllVersions interface.");
  return Reflection.newProxy(
      GoogleAdsAllVersions.class,
      new GoogleAdsAllVersionsInvocationHandler(provider, credentials));
}
 
Example #23
Source File: ApiCatalogImpl.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
/** Loads all client factories for Service, given TransportChannelProvider and Credentials. */
private static ImmutableMap<Method, Object> cacheClientFactories(
    TransportChannelProvider provider, Credentials credentials) {
  ImmutableMap.Builder<Method, Object> builder = ImmutableMap.builder();
  for (Method method : GoogleAdsAllVersions.class.getMethods()) {
    builder.put(
        method,
        GoogleAdsVersionFactory.createProxy(method.getReturnType(), provider, credentials));
  }
  return builder.build();
}
 
Example #24
Source File: GoogleAdsVersionFactory.java    From google-ads-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new instance of interfaceSpec, an interface with accessor methods for all services
 * available in an API version.
 *
 * <p>The interfaceSpec class must be annotated with @VersionDescriptor.
 *
 * <p>All methods of interfaceSpec must be annotated with @ServiceClientDescriptor.
 */
public static <T> T createProxy(
    Class<T> interfaceSpec,
    TransportChannelProvider transportChannelProvider,
    Credentials credentials) {
  try {
    return Reflection.newProxy(
        interfaceSpec,
        new VersionDescriptorInvocationHandler(
            interfaceSpec, transportChannelProvider, credentials));
  } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
    throw new IllegalArgumentException("Invalid GoogleAdsVersion configuration", e);
  }
}
 
Example #25
Source File: HttpBlobStore.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
public static HttpBlobStore create(
    DomainSocketAddress domainSocketAddress,
    URI uri,
    int timeoutMillis,
    int remoteMaxConnections,
    @Nullable final Credentials creds)
    throws ConfigurationException, URISyntaxException, SSLException {

  if (KQueue.isAvailable()) {
    return new HttpBlobStore(
        KQueueEventLoopGroup::new,
        KQueueDomainSocketChannel.class,
        uri,
        timeoutMillis,
        remoteMaxConnections,
        creds,
        domainSocketAddress);
  } else if (Epoll.isAvailable()) {
    return new HttpBlobStore(
        EpollEventLoopGroup::new,
        EpollDomainSocketChannel.class,
        uri,
        timeoutMillis,
        remoteMaxConnections,
        creds,
        domainSocketAddress);
  } else {
    throw new ConfigurationException("Unix domain sockets are unsupported on this platform");
  }
}
 
Example #26
Source File: GcpFirestoreEmulatorAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
private Credentials emulatorCredentials() {
	final Map<String, List<String>> headerMap = new HashMap<>();
	headerMap.put("Authorization", Collections.singletonList("Bearer owner"));
	headerMap.put(
			"google-cloud-resource-prefix", Collections.singletonList(ROOT_PATH));

	return new Credentials() {
		@Override
		public String getAuthenticationType() {
			return null;
		}

		@Override
		public Map<String, List<String>> getRequestMetadata(URI uri) {
			return headerMap;
		}

		@Override
		public boolean hasRequestMetadata() {
			return true;
		}

		@Override
		public boolean hasRequestMetadataOnly() {
			return true;
		}

		@Override
		public void refresh() {
			// no-op
		}
	};
}
 
Example #27
Source File: IamAuthorizer.java    From curiostack with MIT License 5 votes vote down vote up
@Inject
public IamAuthorizer(IamPermissionChecker checker, Credentials serverCredentials) {
  checkArgument(
      serverCredentials instanceof ServiceAccountCredentials,
      "IAM authentication only works with service account credentials.");
  this.checker = checker;
  ServiceAccountCredentials creds = (ServiceAccountCredentials) serverCredentials;
  serviceAccount =
      MoreObjects.firstNonNull(creds.getServiceAccountUser(), creds.getClientEmail());
}
 
Example #28
Source File: AccessTokenProvider.java    From curiostack with MIT License 5 votes vote down vote up
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 #29
Source File: HttpBlobStore.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
public static HttpBlobStore create(
    URI uri, int timeoutMillis, int remoteMaxConnections, @Nullable final Credentials creds)
    throws URISyntaxException, SSLException {
  return new HttpBlobStore(
      NioEventLoopGroup::new,
      NioSocketChannel.class,
      uri,
      timeoutMillis,
      remoteMaxConnections,
      creds,
      null);
}
 
Example #30
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);
  }
}