Search in sources :

Example 51 with AccessToken

use of org.glassfish.jersey.client.oauth1.AccessToken in project styx by spotify.

the class GoogleIdTokenAuthTest method testMockUserCredentials.

@Test
public void testMockUserCredentials() throws IOException, GeneralSecurityException, InterruptedException {
    final MockResponse tokenResponse = new MockResponse().setBody(Utils.getDefaultJsonFactory().toString(ImmutableMap.of("id_token", "test-id-token")));
    metadataServer.enqueue(tokenResponse);
    metadataServer.start();
    final AccessToken accessToken = new AccessToken("test-access-token", Date.from(Instant.now().plus(Duration.ofDays(1))));
    final GoogleCredentials credentials = UserCredentials.newBuilder().setTokenServerUri(URI.create("http://localhost:" + metadataServer.getPort() + "/get-test-token")).setAccessToken(accessToken).setRefreshToken("user-refresh-token").setClientId("user-id").setClientSecret("user-secret").build();
    Assume.assumeThat(credentials, is(instanceOf(UserCredentials.class)));
    final GoogleIdTokenAuth idTokenAuth = GoogleIdTokenAuth.of(credentials);
    final Optional<String> token = idTokenAuth.getToken("http://styx.foo.bar");
    assertThat(token, is(Optional.of("test-id-token")));
    final RecordedRequest recordedRequest = metadataServer.takeRequest();
    final Map<String, String> requestBody = Splitter.on('&').withKeyValueSeparator('=').split(recordedRequest.getBody().readUtf8());
    assertThat(requestBody, is(ImmutableMap.of("grant_type", "refresh_token", "refresh_token", "user-refresh-token", "client_id", "user-id", "client_secret", "user-secret")));
    assertThat(recordedRequest.getPath(), is("/get-test-token"));
    assertThat(recordedRequest.getHeader("Authorization"), is("Bearer test-access-token"));
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) AccessToken(com.google.auth.oauth2.AccessToken) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials) Test(org.junit.Test)

Example 52 with AccessToken

use of org.glassfish.jersey.client.oauth1.AccessToken in project styx by spotify.

the class GoogleIdTokenAuth method getServiceAccountIdTokenUsingAccessToken.

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);
}
Also used : AccessToken(com.google.auth.oauth2.AccessToken) Oauth2(com.google.api.services.oauth2.Oauth2) IOException(java.io.IOException) Tokeninfo(com.google.api.services.oauth2.model.Tokeninfo)

Example 53 with AccessToken

use of org.glassfish.jersey.client.oauth1.AccessToken in project helios by spotify.

the class AuthenticatingHttpConnector method connect.

@Override
public HttpURLConnection connect(final URI uri, final String method, final byte[] entity, final Map<String, List<String>> headers) throws HeliosException {
    final Endpoint endpoint = endpointIterator.next();
    // convert the URI whose hostname portion is a domain name into a URI where the host is an IP
    // as we expect there to be several different IP addresses besides a common domain name
    final URI ipUri;
    try {
        ipUri = toIpUri(endpoint, uri);
    } catch (URISyntaxException e) {
        throw new HeliosException(e);
    }
    try {
        log.debug("connecting to {}", ipUri);
        final Optional<AccessToken> accessTokenOpt = accessTokenSupplier.get();
        if (accessTokenOpt.isPresent()) {
            final String token = accessTokenOpt.get().getTokenValue();
            headers.put("Authorization", singletonList("Bearer " + token));
            log.debug("Add Authorization header with bearer token");
        }
        if (clientCertificatePath.isPresent()) {
            // prioritize using the certificate file if set
            return connectWithCertificateFile(ipUri, method, entity, headers);
        } else if (agentProxy.isPresent() && !identities.isEmpty()) {
            // ssh-agent based authentication
            return connectWithIdentities(identities, ipUri, method, entity, headers);
        } else {
            // no authentication
            return doConnect(ipUri, method, entity, headers);
        }
    } catch (ConnectException | SocketTimeoutException | UnknownHostException e) {
        // UnknownHostException happens if we can't resolve hostname into IP address.
        // UnknownHostException's getMessage method returns just the hostname which is a
        // useless message, so log the exception class name to provide more info.
        log.debug(e.toString());
        throw new HeliosException("Unable to connect to master: " + ipUri, e);
    } catch (IOException e) {
        throw new HeliosException("Unexpected error connecting to " + ipUri, e);
    }
}
Also used : HeliosException(com.spotify.helios.common.HeliosException) SocketTimeoutException(java.net.SocketTimeoutException) UnknownHostException(java.net.UnknownHostException) AccessToken(com.google.auth.oauth2.AccessToken) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) ConnectException(java.net.ConnectException)

Example 54 with AccessToken

use of org.glassfish.jersey.client.oauth1.AccessToken in project helios by spotify.

the class AuthenticatingHttpConnectorTest method createAuthenticatingConnectorWithAccessToken.

private AuthenticatingHttpConnector createAuthenticatingConnectorWithAccessToken(final Optional<AgentProxy> proxy, final List<Identity> identities) {
    final EndpointIterator endpointIterator = EndpointIterator.of(endpoints);
    final AccessToken accessToken = new AccessToken("<token>", null);
    return new AuthenticatingHttpConnector(USER, Suppliers.ofInstance(Optional.of(accessToken)), proxy, Optional.<CertKeyPaths>absent(), endpointIterator, connector, identities);
}
Also used : AccessToken(com.google.auth.oauth2.AccessToken)

Example 55 with AccessToken

use of org.glassfish.jersey.client.oauth1.AccessToken in project helios by spotify.

the class GoogleCredentialsAccessTokenSupplierTest method testGetWithStaticToken.

@Test
public void testGetWithStaticToken() {
    final AccessToken token = new AccessToken("token", null);
    final GoogleCredentialsAccessTokenSupplier supplier = new GoogleCredentialsAccessTokenSupplier(true, token, null);
    assertThat(supplier.get(), equalTo(Optional.of(token)));
}
Also used : AccessToken(com.google.auth.oauth2.AccessToken) Test(org.junit.Test)

Aggregations

AccessToken (com.google.auth.oauth2.AccessToken)71 Test (org.junit.Test)41 GoogleCredentials (com.google.auth.oauth2.GoogleCredentials)29 Date (java.util.Date)22 IOException (java.io.IOException)19 AccessToken (io.vertx.ext.auth.oauth2.AccessToken)16 Client (javax.ws.rs.client.Client)10 AccessToken (org.glassfish.jersey.client.oauth1.AccessToken)10 ConsumerCredentials (org.glassfish.jersey.client.oauth1.ConsumerCredentials)10 JsonObject (io.vertx.core.json.JsonObject)9 URI (java.net.URI)9 Feature (javax.ws.rs.core.Feature)8 JerseyTest (org.glassfish.jersey.test.JerseyTest)8 MockHttpTransport (com.google.api.client.testing.http.MockHttpTransport)6 InputStreamReader (java.io.InputStreamReader)6 Instant (java.time.Instant)6 WebTarget (javax.ws.rs.client.WebTarget)6 LoggingFeature (org.glassfish.jersey.logging.LoggingFeature)6 OAuth2Credentials (com.google.auth.oauth2.OAuth2Credentials)5 OAuth2TokenImpl (io.vertx.ext.auth.oauth2.impl.OAuth2TokenImpl)5