Search in sources :

Example 1 with ClientRequestFilter

use of javax.ws.rs.client.ClientRequestFilter in project jersey by jersey.

the class OAuth2Test method testFlow.

private void testFlow(final boolean isArray) {
    ClientIdentifier clientId = new ClientIdentifier(CLIENT_PUBLIC, CLIENT_SECRET);
    final String authUri = UriBuilder.fromUri(getBaseUri()).path("oauth").path("authorization").build().toString();
    final String accessTokenUri = UriBuilder.fromUri(getBaseUri()).path("oauth").path("access-token").build().toString();
    final String refreshTokenUri = UriBuilder.fromUri(getBaseUri()).path("oauth").path("refresh-token").build().toString();
    final String state = STATE;
    final Client client = ClientBuilder.newClient();
    if (isArray) {
        client.register(new ClientRequestFilter() {

            @Override
            public void filter(final ClientRequestContext requestContext) throws IOException {
                requestContext.getHeaders().putSingle("isArray", true);
            }
        });
    }
    final OAuth2CodeGrantFlow.Builder builder = OAuth2ClientSupport.authorizationCodeGrantFlowBuilder(clientId, authUri, accessTokenUri);
    final OAuth2CodeGrantFlow flow = builder.client(client).refreshTokenUri(refreshTokenUri).property(OAuth2CodeGrantFlow.Phase.AUTHORIZATION, "readOnly", "true").property(OAuth2CodeGrantFlow.Phase.AUTHORIZATION, OAuth2Parameters.STATE, state).scope("contact").build();
    final String finalAuthorizationUri = flow.start();
    final Response response = ClientBuilder.newClient().target(finalAuthorizationUri).request().get();
    assertEquals(200, response.getStatus());
    final String code = response.readEntity(String.class);
    assertEquals(CODE, code);
    final TokenResult result = flow.finish(code, state);
    assertEquals("access-token-aab999f", result.getAccessToken());
    assertEquals(new Long(3600), result.getExpiresIn());
    assertEquals("access-token", result.getTokenType());
    final TokenResult refreshResult = flow.refreshAccessToken(result.getRefreshToken());
    assertEquals("access-token-new", refreshResult.getAccessToken());
    assertEquals(new Long(3600), refreshResult.getExpiresIn());
    assertEquals("access-token", refreshResult.getTokenType());
    if (isArray) {
        final Collection<String> array = (Collection<String>) refreshResult.getAllProperties().get("access_token");
        assertThat(array.size(), is(1));
        assertThat(array, hasItem("access-token-new"));
    }
}
Also used : ClientRequestFilter(javax.ws.rs.client.ClientRequestFilter) ClientRequestContext(javax.ws.rs.client.ClientRequestContext) ClientIdentifier(org.glassfish.jersey.client.oauth2.ClientIdentifier) TokenResult(org.glassfish.jersey.client.oauth2.TokenResult) OAuth2CodeGrantFlow(org.glassfish.jersey.client.oauth2.OAuth2CodeGrantFlow) IOException(java.io.IOException) Response(javax.ws.rs.core.Response) Collection(java.util.Collection) Client(javax.ws.rs.client.Client)

Example 2 with ClientRequestFilter

use of javax.ws.rs.client.ClientRequestFilter in project brave by openzipkin.

the class ITTracingFeature_Client method currentSpanVisibleToUserFilters.

@Test
public void currentSpanVisibleToUserFilters() throws Exception {
    server.enqueue(new MockResponse());
    closeClient(client);
    client = new ResteasyClientBuilder().asyncExecutor(httpTracing.tracing().currentTraceContext().executorService(executor)).register(TracingFeature.create(httpTracing)).register((ClientRequestFilter) requestContext -> requestContext.getHeaders().putSingle("my-id", currentTraceContext.get().traceIdString())).build();
    get(client, "/foo");
    RecordedRequest request = server.takeRequest();
    assertThat(request.getHeader("x-b3-traceId")).isEqualTo(request.getHeader("my-id"));
    takeSpan();
}
Also used : AssumptionViolatedException(org.junit.AssumptionViolatedException) ITHttpAsyncClient(brave.test.http.ITHttpAsyncClient) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Client(javax.ws.rs.client.Client) Span(zipkin2.Span) Test(org.junit.Test) ClientRequestFilter(javax.ws.rs.client.ClientRequestFilter) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) Entity(javax.ws.rs.client.Entity) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) Ignore(org.junit.Ignore) MockResponse(okhttp3.mockwebserver.MockResponse) ExecutorService(java.util.concurrent.ExecutorService) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) ResteasyClientBuilder(org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder) Test(org.junit.Test)

Example 3 with ClientRequestFilter

use of javax.ws.rs.client.ClientRequestFilter in project keycloak by keycloak.

the class AbstractAdvancedBrokerTest method testRetrieveToken.

/**
 * Refers to in old test suite: org.keycloak.testsuite.broker.AbstractKeycloakIdentityProviderTest#testTokenStorageAndRetrievalByApplication
 */
@Test
public void testRetrieveToken() throws Exception {
    updateExecutions(AbstractBrokerTest::enableRequirePassword);
    updateExecutions(AbstractBrokerTest::disableUpdateProfileOnFirstLogin);
    IdentityProviderRepresentation idpRep = identityProviderResource.toRepresentation();
    idpRep.setStoreToken(true);
    identityProviderResource.update(idpRep);
    driver.navigate().to(getAccountUrl(getConsumerRoot(), bc.consumerRealmName()));
    logInWithBroker(bc);
    updatePasswordPage.updatePasswords("password", "password");
    waitForAccountManagementTitle();
    accountUpdateProfilePage.assertCurrent();
    String username = bc.getUserLogin();
    testingClient.server(bc.consumerRealmName()).run(grantReadTokenRole(username));
    OAuthClient.AccessTokenResponse accessTokenResponse = oauth.realm(bc.consumerRealmName()).clientId("broker-app").doGrantAccessTokenRequest("broker-app-secret", bc.getUserLogin(), bc.getUserPassword());
    AtomicReference<String> accessToken = (AtomicReference<String>) new AtomicReference<>(accessTokenResponse.getAccessToken());
    Client client = javax.ws.rs.client.ClientBuilder.newBuilder().register((ClientRequestFilter) request -> request.getHeaders().add(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken.get())).build();
    try {
        WebTarget target = client.target(Urls.identityProviderRetrieveToken(URI.create(getConsumerRoot() + "/auth"), bc.getIDPAlias(), bc.consumerRealmName()));
        try (Response response = target.request().get()) {
            assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
            assertNotNull(response.readEntity(String.class));
        }
        testingClient.server(bc.consumerRealmName()).run(revokeReadTokenRole(username));
        accessTokenResponse = oauth.realm(bc.consumerRealmName()).clientId("broker-app").doGrantAccessTokenRequest("broker-app-secret", bc.getUserLogin(), bc.getUserPassword());
        accessToken.set(accessTokenResponse.getAccessToken());
        try (Response response = target.request().get()) {
            assertEquals(Response.Status.FORBIDDEN.getStatusCode(), response.getStatus());
        }
    } finally {
        client.close();
    }
}
Also used : ClientRequestFilter(javax.ws.rs.client.ClientRequestFilter) Response(javax.ws.rs.core.Response) OAuthClient(org.keycloak.testsuite.util.OAuthClient) IdentityProviderRepresentation(org.keycloak.representations.idm.IdentityProviderRepresentation) AtomicReference(java.util.concurrent.atomic.AtomicReference) WebTarget(javax.ws.rs.client.WebTarget) OAuthClient(org.keycloak.testsuite.util.OAuthClient) Client(javax.ws.rs.client.Client) Test(org.junit.Test)

Example 4 with ClientRequestFilter

use of javax.ws.rs.client.ClientRequestFilter in project Payara by payara.

the class PersonControllerClientHelper method getPersonControllerClient.

public static PersonControllerClient getPersonControllerClient(URL deploymentUrl, String username, String password) {
    try {
        RestClientBuilder builder = RestClientBuilder.newBuilder();
        builder.register((ClientRequestFilter) context -> {
            context.getHeaders().add("username", DEFAULT_USER);
            context.getHeaders().add("password", DEFAULT_PASSWORD);
        });
        PersonControllerClient client = builder.baseUrl(new URL(deploymentUrl.toURI().toString() + "resources/")).build(PersonControllerClient.class);
        return client;
    } catch (URISyntaxException | MalformedURLException ex) {
        throw new IllegalStateException(ex);
    }
}
Also used : DEFAULT_PASSWORD(fish.payara.samples.dynamic.roles.common.AuthoritiesConstants.DEFAULT_PASSWORD) MalformedURLException(java.net.MalformedURLException) URL(java.net.URL) URISyntaxException(java.net.URISyntaxException) DEFAULT_USER(fish.payara.samples.dynamic.roles.common.AuthoritiesConstants.DEFAULT_USER) ClientRequestFilter(javax.ws.rs.client.ClientRequestFilter) RestClientBuilder(org.eclipse.microprofile.rest.client.RestClientBuilder) MalformedURLException(java.net.MalformedURLException) RestClientBuilder(org.eclipse.microprofile.rest.client.RestClientBuilder) URISyntaxException(java.net.URISyntaxException) URL(java.net.URL)

Example 5 with ClientRequestFilter

use of javax.ws.rs.client.ClientRequestFilter in project cxf by apache.

the class ClientRequestFilterInterceptor method handleMessage.

public void handleMessage(Message outMessage) throws Fault {
    ClientProviderFactory pf = ClientProviderFactory.getInstance(outMessage);
    if (pf == null) {
        return;
    }
    // create an empty proxy output stream that the filter can interact with
    // and save a reference for later
    ProxyOutputStream pos = new ProxyOutputStream();
    outMessage.setContent(OutputStream.class, pos);
    outMessage.setContent(ProxyOutputStream.class, pos);
    List<ProviderInfo<ClientRequestFilter>> filters = pf.getClientRequestFilters();
    if (!filters.isEmpty()) {
        final Exchange exchange = outMessage.getExchange();
        final ClientRequestContext context = new ClientRequestContextImpl(outMessage, false);
        for (ProviderInfo<ClientRequestFilter> filter : filters) {
            InjectionUtils.injectContexts(filter.getProvider(), filter, outMessage);
            try {
                filter.getProvider().filter(context);
                @SuppressWarnings("unchecked") Map<String, List<Object>> headers = CastUtils.cast((Map<String, List<Object>>) outMessage.get(Message.PROTOCOL_HEADERS));
                HttpUtils.convertHeaderValuesToString(headers, false);
                Response response = outMessage.getExchange().get(Response.class);
                if (response != null) {
                    outMessage.getInterceptorChain().abort();
                    Message inMessage = new MessageImpl();
                    inMessage.setExchange(exchange);
                    inMessage.put(Message.RESPONSE_CODE, response.getStatus());
                    inMessage.put(Message.PROTOCOL_HEADERS, response.getMetadata());
                    exchange.setInMessage(inMessage);
                    MessageObserver observer = exchange.get(MessageObserver.class);
                    observer.onMessage(inMessage);
                    return;
                }
            } catch (IOException ex) {
                throw new ProcessingException(ex);
            }
        }
    }
}
Also used : ClientRequestContext(javax.ws.rs.client.ClientRequestContext) ClientRequestFilter(javax.ws.rs.client.ClientRequestFilter) MessageObserver(org.apache.cxf.transport.MessageObserver) Message(org.apache.cxf.message.Message) IOException(java.io.IOException) ClientProviderFactory(org.apache.cxf.jaxrs.client.ClientProviderFactory) Exchange(org.apache.cxf.message.Exchange) Response(javax.ws.rs.core.Response) ProviderInfo(org.apache.cxf.jaxrs.model.ProviderInfo) ProxyOutputStream(org.apache.cxf.transport.http.ProxyOutputStream) List(java.util.List) MessageImpl(org.apache.cxf.message.MessageImpl) ProcessingException(javax.ws.rs.ProcessingException)

Aggregations

ClientRequestFilter (javax.ws.rs.client.ClientRequestFilter)16 Client (javax.ws.rs.client.Client)9 ClientRequestContext (javax.ws.rs.client.ClientRequestContext)9 Response (javax.ws.rs.core.Response)9 Test (org.junit.Test)8 IOException (java.io.IOException)7 WebTarget (javax.ws.rs.client.WebTarget)7 ClientBuilder (javax.ws.rs.client.ClientBuilder)4 ClientResponseFilter (javax.ws.rs.client.ClientResponseFilter)4 Invocation (javax.ws.rs.client.Invocation)3 WebClient (org.apache.cxf.jaxrs.client.WebClient)3 Collections (java.util.Collections)2 List (java.util.List)2 ExecutorService (java.util.concurrent.ExecutorService)2 HostnameVerifier (javax.net.ssl.HostnameVerifier)2 SSLContext (javax.net.ssl.SSLContext)2 ClientResponseContext (javax.ws.rs.client.ClientResponseContext)2 Entity (javax.ws.rs.client.Entity)2 HttpHeaders (javax.ws.rs.core.HttpHeaders)2 ITHttpAsyncClient (brave.test.http.ITHttpAsyncClient)1