Search in sources :

Example 26 with AccessToken

use of org.glassfish.jersey.client.oauth1.AccessToken in project artifact-registry-maven-tools by GoogleCloudPlatform.

the class ArtifactRegistryWagonTest method testAuthenticatedGet.

@Test
public void testAuthenticatedGet() throws Exception {
    MockHttpTransport transport = new MockHttpTransport.Builder().setLowLevelHttpResponse(new MockLowLevelHttpResponse().setContent("test content")).build();
    ArtifactRegistryWagon wagon = new ArtifactRegistryWagon();
    wagon.setCredentialProvider(() -> GoogleCredentials.create(new AccessToken("test-access-token", Date.from(Instant.now().plusSeconds(1000)))));
    wagon.setHttpTransportFactory(() -> transport);
    wagon.connect(new Repository("my-repo", REPO_URL));
    File f = FileTestUtils.createUniqueFile("my/artifact/dir", "test");
    wagon.get("my/resource", f);
    assertFileContains(f, "test content");
    String authHeader = transport.getLowLevelHttpRequest().getFirstHeaderValue("Authorization");
    Assert.assertEquals("Bearer test-access-token", authHeader);
    Assert.assertEquals("https://maven.pkg.dev/my-project/my-repo/my/resource", transport.getLowLevelHttpRequest().getUrl());
}
Also used : Repository(org.apache.maven.wagon.repository.Repository) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) MockLowLevelHttpResponse(com.google.api.client.testing.http.MockLowLevelHttpResponse) AccessToken(com.google.auth.oauth2.AccessToken) File(java.io.File) Test(org.junit.Test)

Example 27 with AccessToken

use of org.glassfish.jersey.client.oauth1.AccessToken in project artifact-registry-maven-tools by GoogleCloudPlatform.

the class ArtifactRegistryWagonTest method testHeadNotFound.

@Test
public void testHeadNotFound() throws Exception {
    MockHttpTransport transport = failingTransportWithStatus(HttpStatusCodes.STATUS_CODE_NOT_FOUND);
    ArtifactRegistryWagon wagon = new ArtifactRegistryWagon();
    wagon.setCredentialProvider(() -> GoogleCredentials.create(new AccessToken("test-access-token", Date.from(Instant.now().plusSeconds(1000)))));
    wagon.setHttpTransportFactory(() -> transport);
    wagon.connect(new Repository("my-repo", REPO_URL));
    Assert.assertFalse(wagon.resourceExists("my/resource"));
}
Also used : Repository(org.apache.maven.wagon.repository.Repository) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) AccessToken(com.google.auth.oauth2.AccessToken) Test(org.junit.Test)

Example 28 with AccessToken

use of org.glassfish.jersey.client.oauth1.AccessToken in project jersey by eclipse-ee4j.

the class App method main.

/**
 * Main method that creates a {@link Client client} and initializes the OAuth support with
 * configuration needed to connect to the Twitter and retrieve statuses.
 * <p/>
 * Execute this method to demo
 *
 * @param args Command line arguments.
 * @throws Exception Thrown when error occurs.
 */
public static void main(final String[] args) throws Exception {
    // retrieve consumer key/secret and token/secret from the property file
    // or system properties
    loadSettings();
    final ConsumerCredentials consumerCredentials = new ConsumerCredentials(PROPERTIES.getProperty(PROPERTY_CONSUMER_KEY), PROPERTIES.getProperty(PROPERTY_CONSUMER_SECRET));
    final Feature filterFeature;
    if (PROPERTIES.getProperty(PROPERTY_TOKEN) == null) {
        // we do not have Access Token yet. Let's perfom the Authorization Flow first,
        // let the user approve our app and get Access Token.
        final OAuth1AuthorizationFlow authFlow = OAuth1ClientSupport.builder(consumerCredentials).authorizationFlow("https://api.twitter.com/oauth/request_token", "https://api.twitter.com/oauth/access_token", "https://api.twitter.com/oauth/authorize").build();
        final String authorizationUri = authFlow.start();
        System.out.println("Enter the following URI into a web browser and authorize me:");
        System.out.println(authorizationUri);
        System.out.print("Enter the authorization code: ");
        final String verifier;
        try {
            verifier = IN.readLine();
        } catch (final IOException ex) {
            throw new RuntimeException(ex);
        }
        final AccessToken accessToken = authFlow.finish(verifier);
        // store access token for next application execution
        PROPERTIES.setProperty(PROPERTY_TOKEN, accessToken.getToken());
        PROPERTIES.setProperty(PROPERTY_TOKEN_SECRET, accessToken.getAccessTokenSecret());
        // get the feature that will configure the client with consumer credentials and
        // received access token
        filterFeature = authFlow.getOAuth1Feature();
    } else {
        final AccessToken storedToken = new AccessToken(PROPERTIES.getProperty(PROPERTY_TOKEN), PROPERTIES.getProperty(PROPERTY_TOKEN_SECRET));
        // build a new feature from the stored consumer credentials and access token
        filterFeature = OAuth1ClientSupport.builder(consumerCredentials).feature().accessToken(storedToken).build();
    }
    // create a new Jersey client and register filter feature that will add OAuth signatures and
    // JacksonFeature that will process returned JSON data.
    final Client client = ClientBuilder.newBuilder().register(filterFeature).register(JacksonFeature.class).build();
    // make requests to protected resources
    // (no need to care about the OAuth signatures)
    final Response response = client.target(FRIENDS_TIMELINE_URI).request().get();
    if (response.getStatus() != 200) {
        String errorEntity = null;
        if (response.hasEntity()) {
            errorEntity = response.readEntity(String.class);
        }
        throw new RuntimeException("Request to Twitter was not successful. Response code: " + response.getStatus() + ", reason: " + response.getStatusInfo().getReasonPhrase() + ", entity: " + errorEntity);
    }
    // persist the current consumer key/secret and token/secret for future use
    storeSettings();
    final List<Status> statuses = response.readEntity(new GenericType<List<Status>>() {
    });
    System.out.println("Tweets:\n");
    for (final Status s : statuses) {
        System.out.println(s.getText());
        System.out.println("[posted by " + s.getUser().getName() + " at " + s.getCreatedAt() + "]");
    }
}
Also used : OAuth1AuthorizationFlow(org.glassfish.jersey.client.oauth1.OAuth1AuthorizationFlow) ConsumerCredentials(org.glassfish.jersey.client.oauth1.ConsumerCredentials) IOException(java.io.IOException) Feature(javax.ws.rs.core.Feature) JacksonFeature(org.glassfish.jersey.jackson.JacksonFeature) Response(javax.ws.rs.core.Response) JacksonFeature(org.glassfish.jersey.jackson.JacksonFeature) AccessToken(org.glassfish.jersey.client.oauth1.AccessToken) List(java.util.List) Client(javax.ws.rs.client.Client)

Example 29 with AccessToken

use of org.glassfish.jersey.client.oauth1.AccessToken in project jersey by eclipse-ee4j.

the class OAuthClientServerTest method testRequestSigning.

/**
 * Tests {@link org.glassfish.jersey.client.oauth1.OAuth1ClientFilter} already configured with Access Token for signature
 * purposes only.
 */
@Test
public void testRequestSigning() {
    final Feature filterFeature = OAuth1ClientSupport.builder(new ConsumerCredentials(CONSUMER_KEY, SECRET_CONSUMER_KEY)).feature().accessToken(new AccessToken(PROMETHEUS_TOKEN, PROMETHEUS_SECRET)).build();
    final Client client = ClientBuilder.newBuilder().register(filterFeature).build();
    final URI resourceUri = UriBuilder.fromUri(getBaseUri()).path("resource").build();
    final WebTarget target = client.target(resourceUri);
    Response response;
    for (int i = 0; i < 15; i++) {
        System.out.println("request: " + i);
        response = target.request().get();
        assertEquals(200, response.getStatus());
        assertEquals("prometheus", response.readEntity(String.class));
        i++;
        response = target.path("admin").request().get();
        assertEquals(200, response.getStatus());
        assertEquals(true, response.readEntity(boolean.class));
    }
}
Also used : Response(javax.ws.rs.core.Response) ConsumerCredentials(org.glassfish.jersey.client.oauth1.ConsumerCredentials) AccessToken(org.glassfish.jersey.client.oauth1.AccessToken) WebTarget(javax.ws.rs.client.WebTarget) Client(javax.ws.rs.client.Client) Feature(javax.ws.rs.core.Feature) OAuth1ServerFeature(org.glassfish.jersey.server.oauth1.OAuth1ServerFeature) LoggingFeature(org.glassfish.jersey.logging.LoggingFeature) URI(java.net.URI) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Example 30 with AccessToken

use of org.glassfish.jersey.client.oauth1.AccessToken in project jersey by eclipse-ee4j.

the class OauthClientAuthorizationFlowTest method testOAuthClientFlow.

@Test
public void testOAuthClientFlow() throws Exception {
    final String uri = getBaseUri().toString();
    final OAuth1AuthorizationFlow authFlow = OAuth1ClientSupport.builder(new ConsumerCredentials("dpf43f3p2l4k3l03", "kd94hf93k423kf44")).timestamp("1191242090").nonce("hsu94j3884jdopsl").signatureMethod("PLAINTEXT").authorizationFlow(uri + "request_token", uri + "access_token", uri + "authorize").enableLogging().build();
    // Check we have correct authorization URI.
    final String authorizationUri = authFlow.start();
    assertThat(authorizationUri, containsString("authorize?oauth_token=hh5s93j4hdidpola"));
    // For the purpose of the test I need parameters (and there is no way how to do it now).
    final Field paramField = authFlow.getClass().getDeclaredField("parameters");
    paramField.setAccessible(true);
    final OAuth1Parameters params = (OAuth1Parameters) paramField.get(authFlow);
    // Update parameters.
    params.timestamp("1191242092").nonce("dji430splmx33448");
    final AccessToken accessToken = authFlow.finish();
    assertThat(accessToken, equalTo(new AccessToken("nnch734d00sl2jdk", "pfkkdhi9sl3r4s00")));
    // Update parameters before creating a feature (i.e. changing signature method).
    params.nonce("kllo9940pd9333jh").signatureMethod("HMAC-SHA1").timestamp("1191242096");
    // Check Authorized Client.
    final Client flowClient = authFlow.getAuthorizedClient().register(LoggingFeature.class);
    String responseEntity = flowClient.target(uri).path("/photos").queryParam("file", "vacation.jpg").queryParam("size", "original").request().get(String.class);
    assertThat("Flow Authorized Client", responseEntity, equalTo("PHOTO"));
    // Check Feature.
    final Client featureClient = ClientBuilder.newClient().register(authFlow.getOAuth1Feature()).register(LoggingFeature.class);
    responseEntity = featureClient.target(uri).path("/photos").queryParam("file", "vacation.jpg").queryParam("size", "original").request().get(String.class);
    assertThat("Feature Client", responseEntity, equalTo("PHOTO"));
}
Also used : OAuth1AuthorizationFlow(org.glassfish.jersey.client.oauth1.OAuth1AuthorizationFlow) Field(java.lang.reflect.Field) OAuth1Parameters(org.glassfish.jersey.oauth1.signature.OAuth1Parameters) ConsumerCredentials(org.glassfish.jersey.client.oauth1.ConsumerCredentials) AccessToken(org.glassfish.jersey.client.oauth1.AccessToken) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Client(javax.ws.rs.client.Client) JerseyTest(org.glassfish.jersey.test.JerseyTest) Test(org.junit.Test)

Aggregations

AccessToken (com.google.auth.oauth2.AccessToken)69 Test (org.junit.Test)40 GoogleCredentials (com.google.auth.oauth2.GoogleCredentials)28 Date (java.util.Date)22 IOException (java.io.IOException)18 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