com.google.auth.oauth2.AccessToken Java Examples

The following examples show how to use com.google.auth.oauth2.AccessToken. 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: AbstractAccessTokenProvider.java    From curiostack with MIT License 6 votes vote down vote up
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));
          });
}
 
Example #3
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 #4
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #5
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 #6
Source File: FirebaseApp.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #7
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #8
Source File: GoogleDriveStorageService.java    From production-ready-microservices-starter with MIT License 6 votes vote down vote up
private String getAccessToken() {

        GoogleCredentials credentials = null;
        try {
            credentials = GoogleCredentials.fromStream(new FileInputStream(googleDriveServiceAccountCredentialsFilePath));
            credentials = credentials.createScoped(GOOGLE_DRIVE_APIS_SCOPES);
            credentials.refreshIfExpired();
        } catch (IOException ex) {
            throw new IORuntimeException("Could not create GoogleCredentials.", ex);
        }

        AccessToken token = credentials.getAccessToken();
        return token.getTokenValue();
    }
 
Example #9
Source File: FirestoreProtoClient.java    From startup-os with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #10
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #11
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #12
Source File: JvmAuthTokenProvider.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@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());
  }
}
 
Example #13
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 #14
Source File: JvmAuthTokenProviderTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #15
Source File: FirebaseAuthIT.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@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();
  }
}
 
Example #16
Source File: FirebaseOptionsTest.java    From firebase-admin-java with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #17
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 #18
Source File: SpeechService.java    From black-mirror with MIT License 6 votes vote down vote up
@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));
    }
}
 
Example #19
Source File: SelfAwareConditions.java    From Saiy-PS with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example #20
Source File: GoogleIdTokenAuth.java    From styx with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #21
Source File: SpeechService.java    From android-docs-samples with Apache License 2.0 6 votes vote down vote up
@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));
    }
}
 
Example #22
Source File: ContainerRegistryAuthSupplier.java    From docker-client with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #23
Source File: ContainerRegistryAuthSupplier.java    From docker-client with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #24
Source File: ContainerRegistryAuthSupplier.java    From docker-client with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #25
Source File: GoogleCredentialsAccessTokenSupplier.java    From helios with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #26
Source File: AuthenticatingHttpConnector.java    From helios with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #27
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 #28
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 #29
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #30
Source File: GoogleAuthLibraryCallCredentialsTest.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@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());
}