io.grpc.auth.MoreCallCredentials Java Examples

The following examples show how to use io.grpc.auth.MoreCallCredentials. 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 vote down vote up
/** 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: ComputeEngineChannelBuilder.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
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 #3
Source File: AbstractInteropTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/** Test JWT-based auth. */
public void jwtTokenCreds(InputStream serviceAccountJson) throws Exception {
  final SimpleRequest request = SimpleRequest.newBuilder()
      .setResponseSize(314159)
      .setPayload(Payload.newBuilder()
          .setBody(ByteString.copyFrom(new byte[271828])))
      .setFillUsername(true)
      .build();

  ServiceAccountCredentials credentials = (ServiceAccountCredentials)
      GoogleCredentials.fromStream(serviceAccountJson);
  TestServiceGrpc.TestServiceBlockingStub stub = blockingStub
      .withCallCredentials(MoreCallCredentials.from(credentials));
  SimpleResponse response = stub.unaryCall(request);
  assertEquals(credentials.getClientEmail(), response.getUsername());
  assertEquals(314159, response.getPayload().getBody().size());
}
 
Example #4
Source File: AbstractInteropTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/** 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 #5
Source File: StackdriverSenderFactory.java    From micronaut-gcp with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #6
Source File: GrpcClient.java    From cloud-spanner-r2dbc with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the Cloud Spanner gRPC async stub.
 *
 * @param credentials the Google Cloud Platform credentials used to authenticate with Spanner.
 */
public GrpcClient(GoogleCredentials credentials) {
  // Create blocking and async stubs using the channel
  CallCredentials callCredentials = MoreCallCredentials.from(credentials);

  // Create a channel
  this.channel = ManagedChannelBuilder
      .forTarget(GRPC_TARGET)
      .userAgent(USER_AGENT_LIBRARY_NAME + "/" + PACKAGE_VERSION)
      .build();

  // Async stub for general Spanner SQL queries
  this.spanner = SpannerGrpc.newStub(this.channel)
      .withCallCredentials(callCredentials);

  // Async stub for DDL queries
  this.databaseAdmin = DatabaseAdminGrpc.newStub(this.channel)
      .withCallCredentials(callCredentials);

  this.operations = OperationsGrpc.newStub(this.channel).withCallCredentials(callCredentials);
}
 
Example #7
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 #8
Source File: AbstractInteropTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/** Test JWT-based auth. */
public void jwtTokenCreds(InputStream serviceAccountJson) throws Exception {
  final SimpleRequest request = SimpleRequest.newBuilder()
      .setResponseSize(314159)
      .setPayload(Payload.newBuilder()
          .setBody(ByteString.copyFrom(new byte[271828])))
      .setFillUsername(true)
      .build();

  ServiceAccountCredentials credentials = (ServiceAccountCredentials)
      GoogleCredentials.fromStream(serviceAccountJson);
  TestServiceGrpc.TestServiceBlockingStub stub = blockingStub
      .withCallCredentials(MoreCallCredentials.from(credentials));
  SimpleResponse response = stub.unaryCall(request);
  assertEquals(credentials.getClientEmail(), response.getUsername());
  assertEquals(314159, response.getPayload().getBody().size());
}
 
Example #9
Source File: TraceSampleApplicationTests.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
@Before
public void setupTraceClient() throws IOException {
	this.url = String.format("http://localhost:%d/", this.port);

	// Create a new RestTemplate here because the auto-wired instance has built-in instrumentation
	// which interferes with us setting the 'x-cloud-trace-context' header.
	this.testRestTemplate = new TestRestTemplate();

	this.logClient = LoggingOptions.newBuilder()
			.setProjectId(this.projectIdProvider.getProjectId())
			.setCredentials(this.credentialsProvider.getCredentials())
			.build()
			.getService();

	ManagedChannel channel = ManagedChannelBuilder
			.forTarget("dns:///cloudtrace.googleapis.com")
			.build();

	this.traceServiceStub = TraceServiceGrpc.newBlockingStub(channel)
			.withCallCredentials(MoreCallCredentials.from(this.credentialsProvider.getCredentials()));
}
 
Example #10
Source File: GoogleAuthClient.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #11
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 #12
Source File: ControllerGrpcAuthFocusedTest.java    From pravega with Apache License 2.0 5 votes vote down vote up
private ControllerServiceBlockingStub prepareBlockingCallStub(String username, String password) {
    Exceptions.checkNotNullOrEmpty(username, "username");
    Exceptions.checkNotNullOrEmpty(password, "password");

    ControllerServiceBlockingStub stub =
            ControllerServiceGrpc.newBlockingStub(inProcessChannel);

    // Set call credentials
    Credentials credentials = new DefaultCredentials(password, username);
    if (credentials != null) {
        PravegaCredentialsWrapper wrapper = new PravegaCredentialsWrapper(credentials);
        stub = stub.withCallCredentials(MoreCallCredentials.from(wrapper));
    }
    return stub;
}
 
Example #13
Source File: GoogleAuthUtils.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link CallCredentials} object.
 *
 * @throws IOException in case the call credentials can't be constructed.
 */
public static CallCredentials newCallCredentials(AuthAndTLSOptions options) throws IOException {
  Credentials creds = newCredentials(options);
  if (creds != null) {
    return MoreCallCredentials.from(creds);
  }
  return null;
}
 
Example #14
Source File: ControllerGrpcAuthFocusedTest.java    From pravega with Apache License 2.0 5 votes vote down vote up
private ControllerServiceStub prepareNonBlockingCallStub(String username, String password) {
    Exceptions.checkNotNullOrEmpty(username, "username");
    Exceptions.checkNotNullOrEmpty(password, "password");

    ControllerServiceGrpc.ControllerServiceStub stub = ControllerServiceGrpc.newStub(inProcessChannel);

    // Set call credentials
    Credentials credentials = new DefaultCredentials(password, username);
    if (credentials != null) {
        PravegaCredentialsWrapper wrapper = new PravegaCredentialsWrapper(credentials);
        stub = stub.withCallCredentials(MoreCallCredentials.from(wrapper));
    }
    return stub;
}
 
Example #15
Source File: ControllerImpl.java    From pravega with Apache License 2.0 5 votes vote down vote up
private ControllerServiceStub getClientWithCredentials(ControllerImplConfig config) {
    ControllerServiceStub client = ControllerServiceGrpc.newStub(this.channel);
    try {
        Credentials credentials = config.getClientConfig().getCredentials();
        if (credentials != null) {
            PravegaCredentialsWrapper wrapper = new PravegaCredentialsWrapper(credentials);
            client = client.withCallCredentials(MoreCallCredentials.from(wrapper));
        }
    } catch (Exception e) {
        log.error("Error while setting credentials to controller client", e);
        closeChannel();
        throw e;
    }
    return client;
}
 
Example #16
Source File: GoogleAuthUtils.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link CallCredentials} object.
 *
 * @throws IOException in case the call credentials can't be constructed.
 */
public static CallCredentials newCallCredentials(AuthAndTLSOptions options) throws IOException {
  Credentials creds = newCredentials(options);
  if (creds != null) {
    return MoreCallCredentials.from(creds);
  }
  return null;
}
 
Example #17
Source File: GoogleAuthUtils.java    From bazel with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public static CallCredentials newCallCredentials(
    @Nullable InputStream credentialsFile, List<String> authScope) throws IOException {
  Credentials creds = newCredentials(credentialsFile, authScope);
  if (creds != null) {
    return MoreCallCredentials.from(creds);
  }
  return null;
}
 
Example #18
Source File: AbstractInteropTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/** 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 #19
Source File: AbstractInteropTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
/** 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 #20
Source File: ITStackdriverSender.java    From zipkin-gcp with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void setUp() throws IOException {
  // Application Default credential is configured using the GOOGLE_APPLICATION_CREDENTIALS env var
  // See: https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application

  String credentialsPath = System.getenv("GOOGLE_APPLICATION_CREDENTIALS");
  assumeThat(credentialsPath).isNotBlank();
  assumeThat(new File(credentialsPath)).exists();
  assumeThatCode(GoogleCredentials::getApplicationDefault).doesNotThrowAnyException();

  credentials = GoogleCredentials.getApplicationDefault()
          .createScoped(Collections.singletonList("https://www.googleapis.com/auth/trace.append"));

  // Setup the sender to authenticate the Google Stackdriver service
  sender = StackdriverSender.newBuilder()
          .projectId(projectId)
          .callOptions(CallOptions.DEFAULT.withCallCredentials(MoreCallCredentials.from(credentials)))
          .build();

  reporter =
      AsyncReporter.builder(sender)
          .messageTimeout(0, TimeUnit.MILLISECONDS) // don't spawn a thread
          .build(StackdriverEncoder.V2);

  traceServiceGrpcV1 = TraceServiceGrpc.newBlockingStub(sender.channel)
          .withCallCredentials(MoreCallCredentials.from(credentials.createScoped("https://www.googleapis.com/auth/cloud-platform")));

  senderNoPermission = StackdriverSender.newBuilder()
          .projectId(projectId)
          .build();

  reporterNoPermission =
          AsyncReporter.builder(senderNoPermission)
                  .messageTimeout(0, TimeUnit.MILLISECONDS)
                  .build(StackdriverEncoder.V2);
}
 
Example #21
Source File: ITZipkinStackdriverStorage.java    From zipkin-gcp with Apache License 2.0 5 votes vote down vote up
@BeforeEach
public void init() throws IOException {
  // Application Default credential is configured using the GOOGLE_APPLICATION_CREDENTIALS env var
  // See: https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application

  String credentialsPath = System.getenv("GOOGLE_APPLICATION_CREDENTIALS");
  assumeThat(credentialsPath).isNotBlank();
  assumeThat(new File(credentialsPath)).exists();
  assumeThatCode(GoogleCredentials::getApplicationDefault).doesNotThrowAnyException();

  TestPropertyValues.of(
      "zipkin.storage.type:stackdriver",
      "zipkin.storage.stackdriver.project-id:" + projectId).applyTo(context);
  context.register(
      PropertyPlaceholderAutoConfiguration.class,
      ZipkinStackdriverStorageModule.class);
  context.refresh();
  storage = context.getBean(StackdriverStorage.class);
  storageProperties = context.getBean(ZipkinStackdriverStorageProperties.class);

  GoogleCredentials credentials = GoogleCredentials.getApplicationDefault()
	.createScoped("https://www.googleapis.com/auth/cloud-platform");

  channel = ManagedChannelBuilder.forTarget("cloudtrace.googleapis.com")
          .build();
  traceServiceGrpcV1 = TraceServiceGrpc.newBlockingStub(channel)
          .withCallCredentials(MoreCallCredentials.from(credentials));

}
 
Example #22
Source File: GoogleAuthUtils.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
public static CallCredentials newCallCredentials(
    @Nullable InputStream credentialsFile, List<String> authScope) throws IOException {
  Credentials creds = newCredentials(credentialsFile, authScope);
  if (creds != null) {
    return MoreCallCredentials.from(creds);
  }
  return null;
}
 
Example #23
Source File: AbstractInteropTest.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
/** 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 #24
Source File: GcpFirestoreAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public FirestoreGrpc.FirestoreStub firestoreGrpcStub(
		@Qualifier("firestoreManagedChannel") ManagedChannel firestoreManagedChannel) throws IOException {
	return FirestoreGrpc.newStub(firestoreManagedChannel)
			.withCallCredentials(MoreCallCredentials.from(
					GcpFirestoreAutoConfiguration.this.credentialsProvider.getCredentials()));
}
 
Example #25
Source File: GcpFirestoreEmulatorAutoConfiguration.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean
public FirestoreGrpc.FirestoreStub firestoreGrpcStub() throws IOException {
	ManagedChannel channel = ManagedChannelBuilder
			.forTarget(GcpFirestoreEmulatorAutoConfiguration.this.hostPort)
			.usePlaintext()
			.build();

	return FirestoreGrpc.newStub(channel)
			.withCallCredentials(MoreCallCredentials.from(emulatorCredentials()))
			.withExecutor(Runnable::run);
}
 
Example #26
Source File: FirestoreIntegrationTestsConfiguration.java    From spring-cloud-gcp with Apache License 2.0 5 votes vote down vote up
@Bean
FirestoreGrpc.FirestoreStub firestoreStub()  throws IOException {
	GoogleCredentials credentials = GoogleCredentials.getApplicationDefault();
	CallCredentials callCredentials = MoreCallCredentials.from(credentials);

	// Create a channel
	ManagedChannel channel = ManagedChannelBuilder
			.forTarget("dns:///firestore.googleapis.com:443")
			.build();
	return FirestoreGrpc.newStub(channel).withCallCredentials(callCredentials);
}
 
Example #27
Source File: AssistantClient.java    From google-assistant-java-demo with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get CallCredentials from OAuthCredentials
 *
 * @param oAuthCredentials the credentials from the AuthenticationHelper
 * @return the CallCredentials for the GRPC requests
 */
private CallCredentials getCallCredentials(OAuthCredentials oAuthCredentials) {

    AccessToken accessToken = new AccessToken(
            oAuthCredentials.getAccessToken(),
            new Date(oAuthCredentials.getExpirationTime())
    );

    OAuth2Credentials oAuth2Credentials = new OAuth2Credentials(accessToken);

    // Create an instance of {@link io.grpc.CallCredentials}
    return MoreCallCredentials.from(oAuth2Credentials);
}
 
Example #28
Source File: EmbeddedAssistant.java    From sample-googleassistant with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes the Assistant.
 */
public void connect() {
    mAssistantThread = new HandlerThread("assistantThread");
    mAssistantThread.start();
    mAssistantHandler = new Handler(mAssistantThread.getLooper());

    ManagedChannel channel = ManagedChannelBuilder.forTarget(ASSISTANT_API_ENDPOINT).build();
    mAssistantService = EmbeddedAssistantGrpc.newStub(channel)
            .withCallCredentials(MoreCallCredentials.from(mUserCredentials));
}
 
Example #29
Source File: GoogleRpcContext.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
/**
 * Build the HomeGraph stub for making rpc requests to google.
 */
private void setupStub() {
   ManagedChannel channel = ManagedChannelBuilder.forTarget("homegraph.googleapis.com").build();

   this.blockingStub = HomeGraphApiServiceGrpc.newBlockingStub(channel)
         // See https://grpc.io/docs/guides/auth.html#authenticate-with-google-3.
         .withCallCredentials(MoreCallCredentials.from(this.creds));
}
 
Example #30
Source File: GoogleDefaultChannelBuilder.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
@Override
public ManagedChannel build() {
  @Nullable CallCredentials credentials = null;
  Status status = Status.OK;
  try {
    credentials = MoreCallCredentials.from(GoogleCredentials.getApplicationDefault());
  } catch (IOException e) {
    status =
        Status.UNAUTHENTICATED
            .withDescription("Failed to get Google default credentials")
            .withCause(e);
  }
  return delegate().intercept(new GoogleDefaultInterceptor(credentials, status)).build();
}