下面列出了io.grpc.netty.shaded.io.grpc.netty.NegotiationType#io.grpc.auth.MoreCallCredentials 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/** 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()));
}
/** 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());
}
/** 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()));
}
/**
* 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();
}
/**
* 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);
}
@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);
}
@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()));
}
@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);
}
/**
* 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();
}
}
/** 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());
}
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));
}
/** 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);
}
/** 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);
}
@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();
}
/**
* 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));
}
/**
* 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));
}
/**
* 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);
}
@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);
}
@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);
}
@Bean
@ConditionalOnMissingBean
public FirestoreGrpc.FirestoreStub firestoreGrpcStub(
@Qualifier("firestoreManagedChannel") ManagedChannel firestoreManagedChannel) throws IOException {
return FirestoreGrpc.newStub(firestoreManagedChannel)
.withCallCredentials(MoreCallCredentials.from(
GcpFirestoreAutoConfiguration.this.credentialsProvider.getCredentials()));
}
/**
* 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;
}
@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;
}
@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));
}
@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);
}
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;
}
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;
}
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;
}
/**
* 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;
}
@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;
}
/** 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);
}