下面列出了io.grpc.internal.DnsNameResolverProvider#com.google.auth.oauth2.AccessToken 实例代码,或者点击链接到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()));
}
/** 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
public void testWithOAuth2Credential() {
final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
final OAuth2Credentials oAuth2Credentials = new OAuth2Credentials() {
@Override
public AccessToken refreshAccessToken() throws IOException {
return token;
}
};
interceptor = new ClientAuthInterceptor(oAuth2Credentials, executor);
ClientCall<String, Integer> interceptedCall =
interceptor.interceptCall(descriptor, CallOptions.DEFAULT, channel);
Metadata headers = new Metadata();
interceptedCall.start(listener, headers);
assertEquals(listener, call.responseListener);
assertEquals(headers, call.headers);
Iterable<String> authorization = headers.getAll(AUTHORIZATION);
Assert.assertArrayEquals(new String[]{"Bearer allyourbase"},
Iterables.toArray(authorization, String.class));
}
@Test
public void oauth2Credential() {
final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
final OAuth2Credentials credentials = new OAuth2Credentials() {
@Override
public AccessToken refreshAccessToken() throws IOException {
return token;
}
};
GoogleAuthLibraryCallCredentials callCredentials =
new GoogleAuthLibraryCallCredentials(credentials);
callCredentials.applyRequestMetadata(
new RequestInfoImpl(SecurityLevel.NONE), executor, applier);
assertEquals(1, runPendingRunnables());
verify(applier).apply(headersCaptor.capture());
Metadata headers = headersCaptor.getValue();
Iterable<String> authorization = headers.getAll(AUTHORIZATION);
assertArrayEquals(new String[]{"Bearer allyourbase"},
Iterables.toArray(authorization, String.class));
}
@Test
public void googleCredential_privacyAndIntegrityAllowed() {
final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
final Credentials credentials = GoogleCredentials.create(token);
GoogleAuthLibraryCallCredentials callCredentials =
new GoogleAuthLibraryCallCredentials(credentials);
callCredentials.applyRequestMetadata(
new RequestInfoImpl(SecurityLevel.PRIVACY_AND_INTEGRITY), executor, applier);
runPendingRunnables();
verify(applier).apply(headersCaptor.capture());
Metadata headers = headersCaptor.getValue();
Iterable<String> authorization = headers.getAll(AUTHORIZATION);
assertArrayEquals(new String[]{"Bearer allyourbase"},
Iterables.toArray(authorization, String.class));
}
@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());
}
@Test
public void serviceAccountToJwt() throws Exception {
KeyPair pair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
@SuppressWarnings("deprecation")
ServiceAccountCredentials credentials = new ServiceAccountCredentials(
null, "[email protected]", pair.getPrivate(), null, null) {
@Override
public AccessToken refreshAccessToken() {
throw new AssertionError();
}
};
GoogleAuthLibraryCallCredentials callCredentials =
new GoogleAuthLibraryCallCredentials(credentials);
callCredentials.applyRequestMetadata(new RequestInfoImpl(), executor, applier);
assertEquals(0, runPendingRunnables());
verify(applier).apply(headersCaptor.capture());
Metadata headers = headersCaptor.getValue();
String[] authorization = Iterables.toArray(headers.getAll(AUTHORIZATION), String.class);
assertEquals(1, authorization.length);
assertTrue(authorization[0], authorization[0].startsWith("Bearer "));
// JWT is reasonably long. Normal tokens aren't.
assertTrue(authorization[0], authorization[0].length() > 300);
}
@Test
public void serviceAccountWithScopeNotToJwt() throws Exception {
final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
KeyPair pair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
@SuppressWarnings("deprecation")
ServiceAccountCredentials credentials = new ServiceAccountCredentials(
null, "[email protected]", pair.getPrivate(), null, Arrays.asList("somescope")) {
@Override
public AccessToken refreshAccessToken() {
return token;
}
};
GoogleAuthLibraryCallCredentials callCredentials =
new GoogleAuthLibraryCallCredentials(credentials);
callCredentials.applyRequestMetadata(new RequestInfoImpl(), executor, applier);
assertEquals(1, runPendingRunnables());
verify(applier).apply(headersCaptor.capture());
Metadata headers = headersCaptor.getValue();
Iterable<String> authorization = headers.getAll(AUTHORIZATION);
assertArrayEquals(new String[]{"Bearer allyourbase"},
Iterables.toArray(authorization, String.class));
}
public FirestoreProtoClient(String project, String token) {
GoogleCredentials credentials = GoogleCredentials.create(new AccessToken(token, null));
FirebaseOptions options =
new FirebaseOptions.Builder().setCredentials(credentials).setProjectId(project).build();
try {
FirebaseApp.initializeApp(options);
} catch (IllegalStateException e) {
if (e.getMessage().contains("already exists")) {
// Firestore is probably already initialized - do nothing
} else {
throw e;
}
}
client = FirestoreClient.getFirestore();
storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();
}
/**
* Starts the TokenRefresher if not already started. Starts listening to credentials changed
* events, and schedules refresh events every time the OAuth2 token changes. If no active
* token is present, or if the available token is set to expire soon, this will also schedule
* a refresh event to be executed immediately.
*
* <p>This operation is idempotent. Calling it multiple times, or calling it after the
* refresher has been stopped has no effect.
*/
final synchronized void start() {
// Allow starting only from the ready state.
if (!state.compareAndSet(State.READY, State.STARTED)) {
return;
}
logger.debug("Starting the proactive token refresher");
credentials.addChangeListener(this);
AccessToken accessToken = credentials.getAccessToken();
long refreshDelay;
if (accessToken != null) {
// If the token is about to expire (i.e. expires in less than 5 minutes), schedule a
// refresh event with 0 delay. Otherwise schedule a refresh event at the regular token
// expiry time, minus 5 minutes.
refreshDelay = Math.max(getRefreshDelay(accessToken), 0L);
} else {
// If there is no token fetched so far, fetch one immediately.
refreshDelay = 0L;
}
scheduleRefresh(refreshDelay);
}
@Override
public void getToken(boolean forceRefresh, final GetTokenCompletionListener listener) {
try {
if (forceRefresh) {
credentials.refresh();
}
// The typical way to use a GoogleCredentials instance is to call its getRequestMetadata(),
// and include the metadata in your request. Since we are accessing the token directly via
// getAccessToken(), we must first call getRequestMetadata() to ensure the token is available
// (refreshed if necessary).
credentials.getRequestMetadata();
AccessToken accessToken = credentials.getAccessToken();
listener.onSuccess(wrapOAuthToken(accessToken, authVariable));
} catch (Exception e) {
listener.onError(e.toString());
}
}
@Override
public void onChanged(OAuth2Credentials credentials) throws IOException {
// When this event fires, it is guaranteed that credentials.getAccessToken() will return a
// valid OAuth2 token.
final AccessToken accessToken = credentials.getAccessToken();
// Notify the TokenChangeListener on database's thread pool to make sure that
// all database work happens on database worker threads.
executor.execute(
new Runnable() {
@Override
public void run() {
listener.onTokenChange(wrapOAuthToken(accessToken, authVariable));
}
});
}
@Test
public void testGetTokenError() throws InterruptedException {
MockGoogleCredentials credentials = new MockGoogleCredentials("mock-token") {
@Override
public AccessToken refreshAccessToken() throws IOException {
throw new RuntimeException("Test error");
}
};
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(credentials)
.build();
FirebaseApp app = FirebaseApp.initializeApp(options);
JvmAuthTokenProvider provider = new JvmAuthTokenProvider(app, DIRECT_EXECUTOR);
TestGetTokenListener listener = new TestGetTokenListener();
provider.getToken(true, listener);
assertEquals("java.lang.RuntimeException: Test error", listener.get());
}
@Test
public void testCustomTokenWithIAM() throws Exception {
FirebaseApp masterApp = IntegrationTestUtils.ensureDefaultApp();
GoogleCredentials credentials = ImplFirebaseTrampolines.getCredentials(masterApp);
AccessToken token = credentials.getAccessToken();
if (token == null) {
token = credentials.refreshAccessToken();
}
FirebaseOptions options = new FirebaseOptions.Builder()
.setCredentials(GoogleCredentials.create(token))
.setServiceAccountId(((ServiceAccountSigner) credentials).getAccount())
.setProjectId(IntegrationTestUtils.getProjectId())
.build();
FirebaseApp customApp = FirebaseApp.initializeApp(options, "tempApp");
try {
FirebaseAuth auth = FirebaseAuth.getInstance(customApp);
String customToken = auth.createCustomTokenAsync("user1").get();
String idToken = signInWithCustomToken(customToken);
FirebaseToken decoded = auth.verifyIdTokenAsync(idToken).get();
assertEquals("user1", decoded.getUid());
} finally {
customApp.delete();
}
}
@Test
public void createOptionsWithCustomFirebaseCredential() {
FirebaseOptions firebaseOptions =
new FirebaseOptions.Builder()
.setCredentials(new GoogleCredentials() {
@Override
public AccessToken refreshAccessToken() {
return null;
}
})
.build();
assertNotNull(firebaseOptions.getJsonFactory());
assertNotNull(firebaseOptions.getHttpTransport());
assertNull(firebaseOptions.getDatabaseUrl());
assertNull(firebaseOptions.getStorageBucket());
GoogleCredentials credentials = firebaseOptions.getCredentials();
assertNotNull(credentials);
}
private CompletableFuture<AccessToken> refresh(Type type) {
return fetchToken(type)
.handle(
(msg, t) -> {
if (t != null) {
throw new IllegalStateException("Failed to refresh GCP access token.", t);
}
final TokenResponse response;
try {
response = OBJECT_MAPPER.readValue(msg.content().array(), TokenResponse.class);
} catch (IOException e) {
throw new UncheckedIOException("Error parsing token refresh response.", e);
}
long expiresAtMilliseconds =
clock.millis() + TimeUnit.SECONDS.toMillis(response.expiresIn());
return new AccessToken(
type == Type.ID_TOKEN ? response.idToken() : response.accessToken(),
new Date(expiresAtMilliseconds));
});
}
@Override
protected void onPostExecute(AccessToken accessToken) {
mAccessTokenTask = null;
final ManagedChannel channel = new OkHttpChannelProvider()
.builderForAddress(HOSTNAME, PORT)
.nameResolverFactory(new DnsNameResolverProvider())
.intercept(new GoogleCredentialsInterceptor(new GoogleCredentials(accessToken)
.createScoped(SCOPE)))
.build();
mApi = SpeechGrpc.newStub(channel);
// Schedule access token refresh before it expires
if (mHandler != null) {
mHandler.postDelayed(mFetchAccessTokenRunnable,
Math.max(accessToken.getExpirationTime().getTime()
- System.currentTimeMillis()
- ACCESS_TOKEN_FETCH_MARGIN, ACCESS_TOKEN_EXPIRATION_TOLERANCE));
}
}
/**
* Utility method to construct the {@link RecognitionGoogleCloud} instance
*
* @param recognitionListener the {@link RecognitionListener}
* @return the {@link RecognitionGoogleCloud} instance
*/
public RecognitionGoogleCloud getGoogleCloudRecognition(@NonNull final RecognitionMic recogMic,
@NonNull final SaiyRecognitionListener recognitionListener) {
if (DEBUG) {
MyLog.i(CLS_NAME, "getGoogleCloudRecognition");
}
if (servingRemote()) {
return new RecognitionGoogleCloud(mContext, recognitionListener,
getCallback().getParcel().getVRLanguageGoogle(),
new AccessToken(getCallback().getParcel().getGOOGLE_CLOUD_ACCESS_TOKEN(),
new Date(System.currentTimeMillis()
+ getCallback().getParcel().getGOOGLE_CLOUD_ACCESS_EXPIRY())),
recogMic);
} else {
return new RecognitionGoogleCloud(mContext, recognitionListener,
VRLanguageGoogle.getLanguage(getVRLocale()), GoogleConfiguration.ACCESS_TOKEN, recogMic);
}
}
private String getServiceAccountIdTokenUsingAccessToken(GoogleCredentials credentials, String targetAudience)
throws IOException {
final Oauth2 oauth2 = new Oauth2.Builder(httpTransport, JSON_FACTORY, null)
.build();
final AccessToken accessToken = accessToken(withScopes(credentials,
ImmutableList.of("https://www.googleapis.com/auth/userinfo.email")));
final Tokeninfo info = oauth2.tokeninfo()
.setAccessToken(accessToken.getTokenValue())
.execute();
final String principal = info.getEmail();
if (principal == null) {
throw new IOException("Unable to look up principal email, credentials missing email scope?");
}
if (!SERVICE_ACCOUNT_PATTERN.matcher(principal).matches()) {
throw new IOException("Principal is not a service account, unable to acquire id token: " + principal);
}
return getServiceAccountIdTokenUsingAccessToken(credentials, principal, targetAudience);
}
@Override
protected void onPostExecute(AccessToken accessToken) {
mAccessTokenTask = null;
final ManagedChannel channel = new OkHttpChannelProvider()
.builderForAddress(HOSTNAME, PORT)
.nameResolverFactory(new DnsNameResolverProvider())
.intercept(new GoogleCredentialsInterceptor(new GoogleCredentials(accessToken)
.createScoped(SCOPE)))
.build();
mApi = SpeechGrpc.newStub(channel);
// Schedule access token refresh before it expires
if (mHandler != null) {
mHandler.postDelayed(mFetchAccessTokenRunnable,
Math.max(accessToken.getExpirationTime().getTime()
- System.currentTimeMillis()
- ACCESS_TOKEN_FETCH_MARGIN, ACCESS_TOKEN_EXPIRATION_TOLERANCE));
}
}
private boolean needsRefresh(final AccessToken accessToken) {
if (accessToken == null) {
// has not yet been fetched
return true;
}
final Date expirationTime = credentials.getAccessToken().getExpirationTime();
// Don't refresh if expiration time hasn't been provided.
if (expirationTime == null) {
return false;
}
// refresh the token if it expires "soon"
final long expiresIn = expirationTime.getTime() - clock.millis();
return expiresIn <= minimumExpiryMillis;
}
@Override
public RegistryAuth authFor(final String imageName) throws DockerException {
final String[] imageParts = imageName.split("/", 2);
if (imageParts.length < 2 || !GCR_REGISTRIES.contains(imageParts[0])) {
// not an image on GCR
return null;
}
final AccessToken accessToken;
try {
accessToken = getAccessToken();
} catch (IOException e) {
throw new DockerException(e);
}
return authForAccessToken(accessToken);
}
@Override
public RegistryConfigs authForBuild() throws DockerException {
final AccessToken accessToken;
try {
accessToken = getAccessToken();
} catch (IOException e) {
// do not fail as the GCR access token may not be necessary for building the image currently
// being built
log.warn("unable to get access token for Google Container Registry, "
+ "configuration for building image will not contain RegistryAuth for GCR",
e);
return RegistryConfigs.empty();
}
final Map<String, RegistryAuth> configs = new HashMap<>(GCR_REGISTRIES.size());
for (String serverName : GCR_REGISTRIES) {
configs.put(serverName, authForAccessToken(accessToken));
}
return RegistryConfigs.create(configs);
}
@Override
public Optional<AccessToken> get() {
Optional<AccessToken> tokenOpt = Optional.absent();
if (enabled) {
if (staticToken != null) {
tokenOpt = Optional.of(staticToken);
} else {
try {
synchronized (lock) {
if (credentials == null) {
credentials = getCredentialsWithScopes(tokenScopes);
}
credentials.refreshIfExpired();
}
tokenOpt = Optional.of(credentials.getAccessToken());
} catch (IOException | RuntimeException e) {
LOG.debug("Exception (possibly benign) while loading Google Credentials", e);
return Optional.absent();
}
}
}
return tokenOpt;
}
@VisibleForTesting
AuthenticatingHttpConnector(final String user,
final Supplier<Optional<AccessToken>> accessTokenSupplier,
final Optional<AgentProxy> agentProxyOpt,
final Optional<CertKeyPaths> clientCertificatePath,
final EndpointIterator endpointIterator,
final DefaultHttpConnector delegate,
final List<Identity> identities) {
this.user = user;
this.accessTokenSupplier = accessTokenSupplier;
this.agentProxy = agentProxyOpt;
this.clientCertificatePath = clientCertificatePath;
this.endpointIterator = endpointIterator;
this.delegate = delegate;
this.identities = identities;
}
@Test
public void testWithOAuth2Credential() {
final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
final OAuth2Credentials oAuth2Credentials = new OAuth2Credentials() {
@Override
public AccessToken refreshAccessToken() throws IOException {
return token;
}
};
interceptor = new ClientAuthInterceptor(oAuth2Credentials, executor);
ClientCall<String, Integer> interceptedCall =
interceptor.interceptCall(descriptor, CallOptions.DEFAULT, channel);
Metadata headers = new Metadata();
interceptedCall.start(listener, headers);
assertEquals(listener, call.responseListener);
assertEquals(headers, call.headers);
Iterable<String> authorization = headers.getAll(AUTHORIZATION);
Assert.assertArrayEquals(new String[]{"Bearer allyourbase"},
Iterables.toArray(authorization, String.class));
}
@Test
public void oauth2Credential() {
final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
OAuth2Credentials credentials = new OAuth2Credentials() {
@Override
public AccessToken refreshAccessToken() throws IOException {
return token;
}
};
GoogleAuthLibraryCallCredentials callCredentials =
new GoogleAuthLibraryCallCredentials(credentials);
callCredentials.applyRequestMetadata(
new RequestInfoImpl(SecurityLevel.NONE), executor, applier);
assertEquals(1, runPendingRunnables());
verify(applier).apply(headersCaptor.capture());
Metadata headers = headersCaptor.getValue();
Iterable<String> authorization = headers.getAll(AUTHORIZATION);
assertArrayEquals(new String[]{"Bearer allyourbase"},
Iterables.toArray(authorization, String.class));
}
@Test
public void googleCredential_privacyAndIntegrityAllowed() {
final AccessToken token = new AccessToken("allyourbase", new Date(Long.MAX_VALUE));
final Credentials credentials = GoogleCredentials.create(token);
GoogleAuthLibraryCallCredentials callCredentials =
new GoogleAuthLibraryCallCredentials(credentials);
callCredentials.applyRequestMetadata(
new RequestInfoImpl(SecurityLevel.PRIVACY_AND_INTEGRITY), executor, applier);
runPendingRunnables();
verify(applier).apply(headersCaptor.capture());
Metadata headers = headersCaptor.getValue();
Iterable<String> authorization = headers.getAll(AUTHORIZATION);
assertArrayEquals(new String[]{"Bearer allyourbase"},
Iterables.toArray(authorization, String.class));
}
@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());
}
public static AccessToken submitDirectAuth(BrokerServerInfo serverInfo, String owner, Iterable<String> scopes, String target) {
BrokerGateway gateway = new BrokerGateway(serverInfo);
gateway.setSPNEGOToken();
GetAccessTokenRequest request = GetAccessTokenRequest.newBuilder()
.addAllScopes(scopes)
.setOwner(owner)
.setTarget(target)
.build();
GetAccessTokenResponse response = gateway.getStub().getAccessToken(request);
gateway.getManagedChannel().shutdown();
String tokenString = response.getAccessToken();
long expiresAt = response.getExpiresAt();
return new AccessToken(tokenString, new Date(expiresAt));
}