下面列出了io.netty.channel.epoll.EpollDomainSocketChannel#com.google.auth.Credentials 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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;
}
@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;
}
@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());
}
@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);
}
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);
}
/**
* 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());
}
/**
* 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);
}
/**
* 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());
}
/**
* 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);
}
/**
* 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());
}
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();
}
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);
}
}
/**
* 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;
}
@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;
};
}
@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);
}
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();
}
static String calculateBillingProjectId(Optional<String> configParentProjectId, Credentials credentials) {
// 1. Get from configuration
if (configParentProjectId.isPresent()) {
return configParentProjectId.get();
}
// 2. Get from the provided credentials, but only ServiceAccountCredentials contains the project id.
// All other credentials types (User, AppEngine, GCE, CloudShell, etc.) take it from the environment
if (credentials instanceof ServiceAccountCredentials) {
return ((ServiceAccountCredentials) credentials).getProjectId();
}
// 3. No configuration was provided, so get the default from the environment
return BigQueryOptions.getDefaultProjectId();
}
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());
}
private static Credentials createCredentialsFromKey(String key) {
try {
return GoogleCredentials.fromStream(new ByteArrayInputStream(Base64.decodeBase64(key)));
} catch (IOException e) {
throw new UncheckedIOException("Failed to create Credentials from key", e);
}
}
public static Credentials createDefaultCredentials() {
try {
return GoogleCredentials.getApplicationDefault();
} catch (IOException e) {
throw new UncheckedIOException("Failed to create default Credentials", e);
}
}
@Nullable
private static Class<? extends Credentials> loadGoogleCredentialsClass() {
Class<?> rawGoogleCredentialsClass;
try {
// Can't use a loader as it disables ProGuard's reference detection and would fail to rename
// this reference. Unfortunately this will initialize the class.
rawGoogleCredentialsClass = Class.forName("com.google.auth.oauth2.GoogleCredentials");
} catch (ClassNotFoundException ex) {
log.log(Level.FINE, "Failed to load GoogleCredentials", ex);
return null;
}
return rawGoogleCredentialsClass.asSubclass(Credentials.class);
}
public JwtHelper(Class<?> rawServiceAccountClass, ClassLoader loader)
throws ClassNotFoundException, NoSuchMethodException {
serviceAccountClass = rawServiceAccountClass.asSubclass(Credentials.class);
getScopes = serviceAccountClass.getMethod("getScopes");
getClientId = serviceAccountClass.getMethod("getClientId");
getClientEmail = serviceAccountClass.getMethod("getClientEmail");
getPrivateKey = serviceAccountClass.getMethod("getPrivateKey");
getPrivateKeyId = serviceAccountClass.getMethod("getPrivateKeyId");
Class<? extends Credentials> jwtClass = Class.forName(
"com.google.auth.oauth2.ServiceAccountJwtAccessCredentials", false, loader)
.asSubclass(Credentials.class);
jwtConstructor
= jwtClass.getConstructor(String.class, String.class, PrivateKey.class, String.class);
}
/**
* 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;
}
public BigQueryCredentialsSupplier(Optional<String> credentialsKey, Optional<String> credentialsFile)
{
requireNonNull(credentialsKey, "credentialsKey is null");
requireNonNull(credentialsFile, "credentialsFile is null");
// lazy creation, cache once it's created
this.credentialsCreator = Suppliers.memoize(() -> {
Optional<Credentials> credentialsFromKey = credentialsKey.map(BigQueryCredentialsSupplier::createCredentialsFromKey);
Optional<Credentials> credentialsFromFile = credentialsFile.map(BigQueryCredentialsSupplier::createCredentialsFromFile);
return Stream.of(credentialsFromKey, credentialsFromFile)
.flatMap(Streams::stream)
.findFirst();
});
}
private static Credentials createCredentialsFromKey(String key)
{
try {
return GoogleCredentials.fromStream(new ByteArrayInputStream(Base64.decodeBase64(key)));
}
catch (IOException e) {
throw new UncheckedIOException("Failed to create Credentials from key", e);
}
}
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);
}
}
static String calculateBillingProjectId(Optional<String> configParentProjectId, Optional<Credentials> credentials)
{
// 1. Get from configuration
if (configParentProjectId.isPresent()) {
return configParentProjectId.get();
}
// 2. Get from the provided credentials, but only ServiceAccountCredentials contains the project id.
// All other credentials types (User, AppEngine, GCE, CloudShell, etc.) take it from the environment
if (credentials.isPresent() && credentials.get() instanceof ServiceAccountCredentials) {
return ((ServiceAccountCredentials) credentials.get()).getProjectId();
}
// 3. No configuration was provided, so get the default from the environment
return BigQueryOptions.getDefaultProjectId();
}
@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;
}
PubSubSource(PubSubDeserializationSchema<OUT> deserializationSchema,
PubSubSubscriberFactory pubSubSubscriberFactory,
Credentials credentials,
int maxMessagesToAcknowledge,
AcknowledgeOnCheckpointFactory acknowledgeOnCheckpointFactory) {
this.deserializationSchema = deserializationSchema;
this.pubSubSubscriberFactory = pubSubSubscriberFactory;
this.credentials = credentials;
this.maxMessagesToAcknowledge = maxMessagesToAcknowledge;
this.acknowledgeOnCheckpointFactory = acknowledgeOnCheckpointFactory;
}
@Override
public PubSubSubscriber getSubscriber(Credentials credentials) throws IOException {
ManagedChannel managedChannel = NettyChannelBuilder.forTarget(hostAndPort)
.usePlaintext() // This is 'Ok' because this is ONLY used for testing.
.build();
PullRequest pullRequest = PullRequest.newBuilder()
.setMaxMessages(maxMessagesPerPull)
.setReturnImmediately(false)
.setSubscription(projectSubscriptionName)
.build();
SubscriberGrpc.SubscriberBlockingStub stub = SubscriberGrpc.newBlockingStub(managedChannel);
return new BlockingGrpcPubSubSubscriber(projectSubscriptionName, managedChannel, stub, pullRequest, retries, timeout);
}