com.google.auth.oauth2.OAuth2Credentials Java Examples

The following examples show how to use com.google.auth.oauth2.OAuth2Credentials. 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: ClientAuthInterceptorTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #3
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #4
Source File: ClientAuthInterceptorTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #5
Source File: JvmAuthTokenProvider.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@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));
        }
      });
}
 
Example #6
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #7
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 #8
Source File: FirebaseApp.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Override
public final synchronized void onChanged(OAuth2Credentials credentials) {
  if (state.get() != State.STARTED) {
    return;
  }

  AccessToken accessToken = credentials.getAccessToken();
  long refreshDelay = getRefreshDelay(accessToken);
  if (refreshDelay > 0) {
    scheduleRefresh(refreshDelay);
  } else {
    logger.warn("Token expiry ({}) is less than 5 minutes in the future. Not "
        + "scheduling a proactive refresh.", accessToken.getExpirationTime());
  }
}
 
Example #9
Source File: FirebaseAppTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testAddCredentialsChangedListenerWithoutInitialToken() throws IOException {
  FirebaseApp firebaseApp = FirebaseApp.initializeApp(getMockCredentialOptions(), "myApp");
  CredentialsChangedListener listener = mock(CredentialsChangedListener.class);
  ImplFirebaseTrampolines.getCredentials(firebaseApp).addChangeListener(listener);
  verify(listener, never()).onChanged(Mockito.any(OAuth2Credentials.class));
}
 
Example #10
Source File: FirebaseAppTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testCredentialsChangedListenerOnTokenChange() throws Exception {
  FirebaseApp firebaseApp = FirebaseApp.initializeApp(getMockCredentialOptions(), "myApp");
  CredentialsChangedListener listener = mock(CredentialsChangedListener.class);
  ImplFirebaseTrampolines.getCredentials(firebaseApp).addChangeListener(listener);

  for (int i = 0; i < 5; i++) {
    TestOnlyImplFirebaseTrampolines.getToken(firebaseApp, true);
    verify(listener, times(i + 1)).onChanged(Mockito.any(OAuth2Credentials.class));
  }
}
 
Example #11
Source File: FirebaseAppTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testCredentialsChangedListenerWithNoRefresh() throws Exception {
  FirebaseApp firebaseApp = FirebaseApp.initializeApp(getMockCredentialOptions(), "myApp");
  CredentialsChangedListener listener = mock(CredentialsChangedListener.class);
  ImplFirebaseTrampolines.getCredentials(firebaseApp).addChangeListener(listener);

  TestOnlyImplFirebaseTrampolines.getToken(firebaseApp, true);
  verify(listener, times(1)).onChanged(Mockito.any(OAuth2Credentials.class));

  reset(listener);
  TestOnlyImplFirebaseTrampolines.getToken(firebaseApp, false);
  verify(listener, never()).onChanged(Mockito.any(OAuth2Credentials.class));
}
 
Example #12
Source File: FirebaseAppTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testProactiveTokenRefresh() throws Exception {
  MockTokenRefresherFactory factory = new MockTokenRefresherFactory();
  FirebaseApp firebaseApp = FirebaseApp.initializeApp(getMockCredentialOptions(), "myApp",
      factory);
  MockTokenRefresher tokenRefresher = factory.instance;
  Assert.assertNotNull(tokenRefresher);

  CredentialsChangedListener listener = mock(CredentialsChangedListener.class);
  ImplFirebaseTrampolines.getCredentials(firebaseApp).addChangeListener(listener);

  firebaseApp.startTokenRefresher();

  // Since there was no token to begin with, the refresher should refresh the credential
  // immediately.
  tokenRefresher.simulateDelay(0);
  verify(listener, times(1)).onChanged(Mockito.any(OAuth2Credentials.class));

  tokenRefresher.simulateDelay(55);
  verify(listener, times(2)).onChanged(Mockito.any(OAuth2Credentials.class));

  tokenRefresher.simulateDelay(20);
  verify(listener, times(2)).onChanged(Mockito.any(OAuth2Credentials.class));

  tokenRefresher.simulateDelay(35);
  verify(listener, times(3)).onChanged(Mockito.any(OAuth2Credentials.class));
}
 
Example #13
Source File: FirebaseAppTest.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testProactiveTokenRefreshWithInitialToken() throws Exception {
  MockTokenRefresherFactory factory = new MockTokenRefresherFactory();
  FirebaseApp firebaseApp = FirebaseApp.initializeApp(getMockCredentialOptions(), "myApp",
      factory);
  MockTokenRefresher tokenRefresher = factory.instance;
  Assert.assertNotNull(tokenRefresher);

  // Get the initial token
  TestOnlyImplFirebaseTrampolines.getToken(firebaseApp, true);

  CredentialsChangedListener listener = mock(CredentialsChangedListener.class);
  ImplFirebaseTrampolines.getCredentials(firebaseApp).addChangeListener(listener);

  firebaseApp.startTokenRefresher();

  // Since there is already a valid token, which won't expire for another hour, the refresher
  // should not refresh the credential at this point in time.
  tokenRefresher.simulateDelay(0);
  verify(listener, never()).onChanged(Mockito.any(OAuth2Credentials.class));

  tokenRefresher.simulateDelay(55);
  verify(listener, times(1)).onChanged(Mockito.any(OAuth2Credentials.class));

  tokenRefresher.simulateDelay(20);
  verify(listener, times(1)).onChanged(Mockito.any(OAuth2Credentials.class));

  tokenRefresher.simulateDelay(35);
  verify(listener, times(2)).onChanged(Mockito.any(OAuth2Credentials.class));
}
 
Example #14
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 #15
Source File: DicomWebClientJetty.java    From healthcare-dicom-dicomweb-adapter with Apache License 2.0 5 votes vote down vote up
public DicomWebClientJetty(
    OAuth2Credentials credentials,
    String stowPath) {
  this.credentials = credentials;
  this.stowPath = StringUtil.trim(stowPath);

  DicomWebValidation.validatePath(this.stowPath, DicomWebValidation.DICOMWEB_STUDIES_VALIDATION);
}
 
Example #16
Source File: JvmAuthTokenProviderTest.java    From firebase-admin-java with Apache License 2.0 4 votes vote down vote up
@Override
public void onChanged(OAuth2Credentials credentials) throws IOException {
  count++;
}
 
Example #17
Source File: HttpTraceConsumer.java    From cloud-trace-java with Apache License 2.0 4 votes vote down vote up
public HttpTraceConsumer(OAuth2Credentials oAuth2Credentials, String hostUrl) {
  this.oAuth2Credentials = oAuth2Credentials;
  this.hostUrl = hostUrl;
}
 
Example #18
Source File: HttpTraceConsumer.java    From cloud-trace-java with Apache License 2.0 4 votes vote down vote up
public HttpTraceConsumer(OAuth2Credentials oAuth2Credentials) {
  this(oAuth2Credentials, "https://cloudtrace.googleapis.com");
}