下面列出了javax.validation.constraints.AssertTrue#com.google.auth.oauth2.GoogleCredentials 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static CloudHealthcare createClient() throws IOException {
// Use Application Default Credentials (ADC) to authenticate the requests
// For more information see https://cloud.google.com/docs/authentication/production
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));
// Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
HttpRequestInitializer requestInitializer =
request -> {
new HttpCredentialsAdapter(credential).initialize(request);
request.setConnectTimeout(60000); // 1 minute connect timeout
request.setReadTimeout(60000); // 1 minute read timeout
};
// Build the client for interacting with the service.
return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
.setApplicationName("your-application-name")
.build();
}
@Provides
@Singleton
static FirebaseApp firebaseApp(FirebaseAuthConfig config) {
final FirebaseOptions options;
try {
options =
new FirebaseOptions.Builder()
.setCredentials(
GoogleCredentials.fromStream(
new ByteArrayInputStream(
Base64.getDecoder().decode(config.getServiceAccountBase64()))))
.setDatabaseUrl("https://" + config.getProjectId() + ".firebaseio.com")
.build();
} catch (IOException e) {
throw new UncheckedIOException("Could not read certificate.", e);
}
return FirebaseApp.initializeApp(options);
}
private static CloudHealthcare createClient() throws IOException {
// Use Application Default Credentials (ADC) to authenticate the requests
// For more information see https://cloud.google.com/docs/authentication/production
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));
// Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
HttpRequestInitializer requestInitializer =
request -> {
new HttpCredentialsAdapter(credential).initialize(request);
request.setConnectTimeout(60000); // 1 minute connect timeout
request.setReadTimeout(60000); // 1 minute read timeout
};
// Build the client for interacting with the service.
return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
.setApplicationName("your-application-name")
.build();
}
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);
}
}
private static CloudHealthcare createClient() throws IOException {
// Use Application Default Credentials (ADC) to authenticate the requests
// For more information see https://cloud.google.com/docs/authentication/production
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));
// Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
HttpRequestInitializer requestInitializer =
request -> {
new HttpCredentialsAdapter(credential).initialize(request);
request.setConnectTimeout(60000); // 1 minute connect timeout
request.setReadTimeout(60000); // 1 minute read timeout
};
// Build the client for interacting with the service.
return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
.setApplicationName("your-application-name")
.build();
}
public ContainerRegistryAuthSupplier build() {
final GoogleCredentials credentials = this.credentials.createScoped(scopes);
// log some sort of identifier for the credentials, which requires looking at the
// instance type
if (credentials instanceof ServiceAccountCredentials) {
final String clientEmail = ((ServiceAccountCredentials) credentials).getClientEmail();
log.info("loaded credentials for service account with clientEmail={}", clientEmail);
} else if (credentials instanceof UserCredentials) {
final String clientId = ((UserCredentials) credentials).getClientId();
log.info("loaded credentials for user account with clientId={}", clientId);
}
final Clock clock = Clock.systemDefaultZone();
final DefaultCredentialRefresher refresher = new DefaultCredentialRefresher();
return new ContainerRegistryAuthSupplier(credentials, clock, minimumExpiryMillis, refresher);
}
private static CloudHealthcare createClient() throws IOException {
// Use Application Default Credentials (ADC) to authenticate the requests
// For more information see https://cloud.google.com/docs/authentication/production
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));
// Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
HttpRequestInitializer requestInitializer =
request -> {
new HttpCredentialsAdapter(credential).initialize(request);
request.setConnectTimeout(60000); // 1 minute connect timeout
request.setReadTimeout(60000); // 1 minute read timeout
};
// Build the client for interacting with the service.
return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
.setApplicationName("your-application-name")
.build();
}
private static CloudHealthcare createClient() throws IOException {
// Use Application Default Credentials (ADC) to authenticate the requests
// For more information see https://cloud.google.com/docs/authentication/production
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));
// Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
HttpRequestInitializer requestInitializer =
request -> {
new HttpCredentialsAdapter(credential).initialize(request);
request.setConnectTimeout(60000); // 1 minute connect timeout
request.setReadTimeout(60000); // 1 minute read timeout
};
// Build the client for interacting with the service.
return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
.setApplicationName("your-application-name")
.build();
}
/** Delete this device from Cloud IoT. */
public static void deleteDevice(
String deviceId, String projectId, String cloudRegion, String registryName)
throws GeneralSecurityException, IOException {
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
final CloudIot service =
new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
.setApplicationName(APP_NAME)
.build();
final String devicePath =
String.format(
"projects/%s/locations/%s/registries/%s/devices/%s",
projectId, cloudRegion, registryName, deviceId);
System.out.println("Deleting device " + devicePath);
service.projects().locations().registries().devices().delete(devicePath).execute();
}
@Test
public void testUserAgentConfig()
throws IOException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
GrpcClient grpcClient = new GrpcClient(GoogleCredentials.getApplicationDefault());
Channel channel = grpcClient.getSpanner().getChannel();
Class innerChannelWrapperClass = Class.forName("io.grpc.internal.ForwardingManagedChannel");
Class channelImplClass = Class.forName("io.grpc.internal.ManagedChannelImpl");
Field deletegateField = innerChannelWrapperClass.getDeclaredField("delegate");
deletegateField.setAccessible(true);
Field userAgentField = channelImplClass.getDeclaredField("userAgent");
userAgentField.setAccessible(true);
assertTrue(Pattern.matches("cloud-spanner-r2dbc/[0-9A-Za-z._-]+",
(String) userAgentField.get(deletegateField.get(channel))));
}
/**
* Builds {@link GoogleCredentials} using the provided credentials path and credentials JSON.
*
* <p>{@code credentialsPath} and {@code credentialsJson} are mutually exclusive.
* So if both are provided (are non-{@code null}), this is an error.
*
* <p>If either @code credentialsPath} or {@code credentialsJson} is provided,
* it's used to construct the credentials.
*
* <p>If none are provided, the default GCP SDK credentials acquisition mechanism is used.
*
* @param credentialsPath the credential path, can be {@code null}.
* @param credentialsJson the credential JSON string, can be {@code null}.
* @return a {@link GoogleCredentials} constructed based on the input.
* @throws IOException if some error getting the credentials happen.
* @throws IllegalArgumentException
* if both {@code credentialsPath} and {@code credentialsJson} are non-{@code null}.
*/
public static GoogleCredentials build(final String credentialsPath,
final String credentialsJson) throws IOException, IllegalArgumentException {
if (credentialsPath != null && credentialsJson != null) {
throw new IllegalArgumentException("Both credentialsPath and credentialsJson cannot be non-null.");
}
if (credentialsPath != null) {
log.debug("Using provided credentials path");
return getCredentialsFromPath(credentialsPath);
}
if (credentialsJson != null) {
log.debug("Using provided credentials JSON");
return getCredentialsFromJson(credentialsJson);
}
log.debug("Using default credentials");
return GoogleCredentials.getApplicationDefault();
}
private static CloudHealthcare createClient() throws IOException {
// Use Application Default Credentials (ADC) to authenticate the requests
// For more information see https://cloud.google.com/docs/authentication/production
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));
// Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
HttpRequestInitializer requestInitializer =
request -> {
new HttpCredentialsAdapter(credential).initialize(request);
request.setConnectTimeout(60000); // 1 minute connect timeout
request.setReadTimeout(60000); // 1 minute read timeout
};
// Build the client for interacting with the service.
return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
.setApplicationName("your-application-name")
.build();
}
private static Iam initService() throws GeneralSecurityException, IOException {
// Use the Application Default Credentials strategy for authentication. For more info, see:
// https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
// Initialize the IAM service, which can be used to send requests to the IAM API.
Iam service =
new Iam.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(),
new HttpCredentialsAdapter(credential))
.setApplicationName("service-account-keys")
.build();
return service;
}
private static CloudHealthcare createClient() throws IOException {
// Use Application Default Credentials (ADC) to authenticate the requests
// For more information see https://cloud.google.com/docs/authentication/production
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));
// Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
HttpRequestInitializer requestInitializer =
request -> {
new HttpCredentialsAdapter(credential).initialize(request);
request.setConnectTimeout(60000); // 1 minute connect timeout
request.setReadTimeout(60000); // 1 minute read timeout
};
// Build the client for interacting with the service.
return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
.setApplicationName("your-application-name")
.build();
}
private static CloudHealthcare createClient() throws IOException {
// Use Application Default Credentials (ADC) to authenticate the requests
// For more information see https://cloud.google.com/docs/authentication/production
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));
// Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
HttpRequestInitializer requestInitializer =
request -> {
new HttpCredentialsAdapter(credential).initialize(request);
request.setConnectTimeout(60000); // 1 minute connect timeout
request.setReadTimeout(60000); // 1 minute read timeout
};
// Build the client for interacting with the service.
return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
.setApplicationName("your-application-name")
.build();
}
/** 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());
}
@Test
public void testDefaultingToApplicationDefault() throws Exception {
final TestRunner runner = TestRunners.newTestRunner(MockCredentialsServiceProcessor.class);
final GCPCredentialsControllerService serviceImpl = new GCPCredentialsControllerService();
runner.addControllerService("gcpCredentialsProvider", serviceImpl);
runner.enableControllerService(serviceImpl);
runner.assertValid(serviceImpl);
final GCPCredentialsService service = (GCPCredentialsService) runner.getProcessContext()
.getControllerServiceLookup().getControllerService("gcpCredentialsProvider");
assertNotNull(service);
final GoogleCredentials credentials = service.getGoogleCredentials();
assertNotNull(credentials);
}
private static CloudHealthcare createClient() throws IOException {
// Use Application Default Credentials (ADC) to authenticate the requests
// For more information see https://cloud.google.com/docs/authentication/production
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));
// Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
HttpRequestInitializer requestInitializer =
request -> {
new HttpCredentialsAdapter(credential).initialize(request);
request.setConnectTimeout(60000); // 1 minute connect timeout
request.setReadTimeout(60000); // 1 minute read timeout
};
// Build the client for interacting with the service.
return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
.setApplicationName("your-application-name")
.build();
}
private static CloudHealthcare createClient() throws IOException {
// Use Application Default Credentials (ADC) to authenticate the requests
// For more information see https://cloud.google.com/docs/authentication/production
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));
// Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
HttpRequestInitializer requestInitializer =
request -> {
new HttpCredentialsAdapter(credential).initialize(request);
request.setConnectTimeout(60000); // 1 minute connect timeout
request.setReadTimeout(60000); // 1 minute read timeout
};
// Build the client for interacting with the service.
return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
.setApplicationName("your-application-name")
.build();
}
/**
* Ensures initialization of Google Application Default Credentials. Any test that depends on
* ADC should consider this as a fixture, and invoke it before hand. Since ADC are initialized
* once per JVM, this makes sure that all dependent tests get the same ADC instance, and
* can reliably reason about the tokens minted using it.
*/
public static synchronized GoogleCredentials getApplicationDefaultCredentials()
throws IOException {
if (defaultCredentials != null) {
return defaultCredentials;
}
final MockTokenServerTransport transport = new MockTokenServerTransport(
"https://accounts.google.com/o/oauth2/token");
transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), TEST_ADC_ACCESS_TOKEN);
File serviceAccount = new File("src/test/resources/service_accounts", "editor.json");
Map<String, String> environmentVariables =
ImmutableMap.<String, String>builder()
.put("GOOGLE_APPLICATION_CREDENTIALS", serviceAccount.getAbsolutePath())
.build();
setEnvironmentVariables(environmentVariables);
defaultCredentials = GoogleCredentials.getApplicationDefault(new HttpTransportFactory() {
@Override
public HttpTransport create() {
return transport;
}
});
return defaultCredentials;
}
@Test
public void testStorageOptionsConfiguration() throws Exception {
reset(storage);
final TestRunner runner = buildNewRunner(getProcessor());
final AbstractGCSProcessor processor = getProcessor();
final GoogleCredentials mockCredentials = mock(GoogleCredentials.class);
final StorageOptions options = processor.getServiceOptions(runner.getProcessContext(),
mockCredentials);
assertEquals("Project IDs should match",
PROJECT_ID, options.getProjectId());
assertEquals("Retry counts should match",
RETRIES.intValue(), options.getRetrySettings().getMaxAttempts());
assertSame("Credentials should be configured correctly",
mockCredentials, options.getCredentials());
}
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;
}
private GoogleCredentials resolveGoogleCredentials(final AbstractOperationRequest operationRequest) {
final String dataKey = "gcp";
final String namespace = operationRequest.resolveKubernetesNamespace();
final String secretName = operationRequest.resolveSecretName();
try {
Optional<byte[]> gcpCredentials = new SecretReader(coreV1ApiProvider).read(namespace,
secretName,
dataKey);
if (!gcpCredentials.isPresent()) {
throw new GCPModuleException(format("GCP credentials from Kubernetes namespace %s from secret %s under key %s were not set.",
namespace,
secretName,
dataKey));
}
return GoogleCredentials.fromStream(new ByteArrayInputStream(gcpCredentials.get()))
.createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));
} catch (final Exception ex) {
throw new GCPModuleException(format("Unable to resolve data for key %s on secret %s", dataKey, secretName), ex);
}
}
private static CloudHealthcare createClient() throws IOException {
// Use Application Default Credentials (ADC) to authenticate the requests
// For more information see https://cloud.google.com/docs/authentication/production
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));
// Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
HttpRequestInitializer requestInitializer =
request -> {
new HttpCredentialsAdapter(credential).initialize(request);
request.setConnectTimeout(60000); // 1 minute connect timeout
request.setReadTimeout(60000); // 1 minute read timeout
};
// Build the client for interacting with the service.
return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
.setApplicationName("your-application-name")
.build();
}
private void initializeCloudIoT() {
projectPath = "projects/" + projectId + "/locations/" + cloudRegion;
try {
System.err.println("Initializing with default credentials...");
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
cloudIotService =
new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
.setApplicationName("com.google.iot.bos")
.build();
cloudIotRegistries = cloudIotService.projects().locations().registries();
System.err.println("Created service for project " + projectPath);
} catch (Exception e) {
throw new RuntimeException("While initializing Cloud IoT project " + projectPath, e);
}
}
private static CloudHealthcare createClient() throws IOException {
// Use Application Default Credentials (ADC) to authenticate the requests
// For more information see https://cloud.google.com/docs/authentication/production
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));
// Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
HttpRequestInitializer requestInitializer =
request -> {
new HttpCredentialsAdapter(credential).initialize(request);
request.setConnectTimeout(60000); // 1 minute connect timeout
request.setReadTimeout(60000); // 1 minute read timeout
};
// Build the client for interacting with the service.
return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
.setApplicationName("your-application-name")
.build();
}
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();
}
private static CloudHealthcare createClient() throws IOException {
// Use Application Default Credentials (ADC) to authenticate the requests
// For more information see https://cloud.google.com/docs/authentication/production
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault()
.createScoped(Collections.singleton(CloudHealthcareScopes.CLOUD_PLATFORM));
// Create a HttpRequestInitializer, which will provide a baseline configuration to all requests.
HttpRequestInitializer requestInitializer =
request -> {
new HttpCredentialsAdapter(credential).initialize(request);
request.setConnectTimeout(60000); // 1 minute connect timeout
request.setReadTimeout(60000); // 1 minute read timeout
};
// Build the client for interacting with the service.
return new CloudHealthcare.Builder(HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
.setApplicationName("your-application-name")
.build();
}
@Test
public void testDefaultingToApplicationDefault() throws Exception {
final TestRunner runner = TestRunners.newTestRunner(MockCredentialsServiceProcessor.class);
final GCPCredentialsControllerService serviceImpl = new GCPCredentialsControllerService();
runner.addControllerService("gcpCredentialsProvider", serviceImpl);
runner.enableControllerService(serviceImpl);
runner.assertValid(serviceImpl);
final GCPCredentialsService service = (GCPCredentialsService) runner.getProcessContext()
.getControllerServiceLookup().getControllerService("gcpCredentialsProvider");
assertNotNull(service);
final GoogleCredentials credentials = service.getGoogleCredentials();
assertNotNull(credentials);
}
@Test
public void testBiqQueryOptionsConfiguration() throws Exception {
reset(bq);
final TestRunner runner = buildNewRunner(getProcessor());
final AbstractBigQueryProcessor processor = getProcessor();
final GoogleCredentials mockCredentials = mock(GoogleCredentials.class);
final BigQueryOptions options = processor.getServiceOptions(runner.getProcessContext(),
mockCredentials);
assertEquals("Project IDs should match",
PROJECT_ID, options.getProjectId());
assertEquals("Retry counts should match",
RETRIES.intValue(), options.getRetrySettings().getMaxAttempts());
assertSame("Credentials should be configured correctly",
mockCredentials, options.getCredentials());
}