Search in sources :

Example 16 with ClientRequestContext

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

the class SpecExamplesTest method interceptorBasicTest.

@Test
public void interceptorBasicTest() {
    URI uri = URI.create("https://www.example.com/foo?param=value&pet=dog");
    String method = "POST";
    MessageSigner messageSigner = new MessageSigner(keyProvider, "Test", Arrays.asList("(request-target)", "host", "Date"));
    CreateSignatureInterceptor interceptor = new CreateSignatureInterceptor();
    interceptor.setMessageSigner(messageSigner);
    Map<String, List<String>> headers = createMockHeaders();
    MultivaluedMap<String, Object> requestHeaders = new MultivaluedHashMap<>();
    MultivaluedMap<String, String> requestStringHeaders = new MultivaluedHashMap<>();
    headers.forEach((header, value) -> {
        requestHeaders.add(header, value.get(0));
        requestStringHeaders.add(header, value.get(0));
    });
    final Message message = new MessageImpl();
    doInPhaseInterceptor(message, () -> {
        ClientRequestContext requestContext = getClientRequestContextMock(uri, method, requestHeaders);
        interceptor.filter(requestContext);
        String signatureHeader = (String) requestHeaders.get("Signature").get(0);
        requestStringHeaders.add("Signature", signatureHeader);
        String expectedHeader = "keyId=\"Test\",algorithm=\"rsa-sha256\"," + "headers=\"(request-target) host date\",signature=\"qdx+H7PHHDZgy4" + "y/Ahn9Tny9V3GP6YgBPyUXMmoxWtLbHpUnXS2mg2+SbrQDMCJypxBLSPQR2aAjn" + "7ndmw2iicw3HMbe8VfEdKFYRqzic+efkb3nndiv/x1xSHDJWeSWkx3ButlYSuBs" + "kLu6kd9Fswtemr3lgdDEmn04swr2Os0=\"";
        assertEquals(signatureHeader, expectedHeader);
        // Verify that the request signature can be verified by the filter
        MessageVerifier messageVerifier = new MessageVerifier(keyId -> publicKey);
        messageVerifier.setAddDefaultRequiredHeaders(false);
        messageVerifier.setSecurityProvider(new MockSecurityProvider());
        messageVerifier.setAlgorithmProvider(new MockAlgorithmProvider());
        VerifySignatureFilter verifySignatureFilter = new VerifySignatureFilter();
        verifySignatureFilter.setMessageVerifier(messageVerifier);
        ContainerRequestContext containerRequestContext = getContainerRequestContextMock(uri, method, requestStringHeaders);
        verifySignatureFilter.filter(containerRequestContext);
    });
}
Also used : ClientRequestContext(javax.ws.rs.client.ClientRequestContext) MockAlgorithmProvider(org.apache.cxf.rs.security.httpsignature.provider.MockAlgorithmProvider) Message(org.apache.cxf.message.Message) ContainerRequestContext(javax.ws.rs.container.ContainerRequestContext) VerifySignatureFilter(org.apache.cxf.rs.security.httpsignature.filters.VerifySignatureFilter) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) CreateSignatureInterceptor(org.apache.cxf.rs.security.httpsignature.filters.CreateSignatureInterceptor) MockSecurityProvider(org.apache.cxf.rs.security.httpsignature.provider.MockSecurityProvider) MessageImpl(org.apache.cxf.message.MessageImpl) Test(org.junit.Test)

Example 17 with ClientRequestContext

use of javax.ws.rs.client.ClientRequestContext in project openremote by openremote.

the class QueryParameterInjectorFilter method filter.

@SuppressWarnings("unchecked")
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
    MultivaluedMap<String, String> queryParameters = (MultivaluedMap<String, String>) requestContext.getProperty(QUERY_PARAMETERS_PROPERTY);
    String dynamicValue = requestContext.getProperty(DYNAMIC_VALUE_PROPERTY) != null ? (String) requestContext.getProperty(DYNAMIC_VALUE_PROPERTY) : "";
    if (queryParameters == null) {
        return;
    }
    UriBuilder uriBuilder = UriBuilder.fromUri(requestContext.getUri());
    queryParameters.forEach((name, values) -> {
        Object[] formattedValues = values.stream().map(v -> {
            v = v.replaceAll(Protocol.DYNAMIC_VALUE_PLACEHOLDER_REGEXP, dynamicValue);
            Matcher matcher = DYNAMIC_TIME_PATTERN.matcher(v);
            if (matcher.find()) {
                long millisToAdd = 0L;
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
                if (matcher.groupCount() > 0) {
                    dateTimeFormatter = DateTimeFormatter.ofPattern(matcher.group(1));
                }
                if (matcher.groupCount() == 2) {
                    millisToAdd = Long.parseLong(matcher.group(2));
                }
                v = v.replaceAll(Protocol.DYNAMIC_TIME_PLACEHOLDER_REGEXP, dateTimeFormatter.format(Instant.now().plusMillis(millisToAdd).atZone(ZoneId.systemDefault())));
            }
            return v;
        }).toArray();
        uriBuilder.queryParam(name, formattedValues);
    });
    requestContext.setUri(uriBuilder.build());
}
Also used : MultivaluedMap(javax.ws.rs.core.MultivaluedMap) ClientRequestContext(javax.ws.rs.client.ClientRequestContext) Matcher(java.util.regex.Matcher) Provider(javax.ws.rs.ext.Provider) Protocol(org.openremote.model.asset.agent.Protocol) DateTimeFormatter(java.time.format.DateTimeFormatter) UriBuilder(javax.ws.rs.core.UriBuilder) IOException(java.io.IOException) Pattern(java.util.regex.Pattern) ClientRequestFilter(javax.ws.rs.client.ClientRequestFilter) Instant(java.time.Instant) ZoneId(java.time.ZoneId) Matcher(java.util.regex.Matcher) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) UriBuilder(javax.ws.rs.core.UriBuilder) DateTimeFormatter(java.time.format.DateTimeFormatter)

Example 18 with ClientRequestContext

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

the class AwsAuthFeature method filter.

@Override
public synchronized void filter(ClientRequestContext requestContext) throws IOException {
    MultivaluedMap<String, String> headers = requestContext.getStringHeaders();
    Context filterContext = new Context();
    filterContext.method = requestContext.getMethod();
    filterContext.query = requestContext.getUri().getQuery();
    filterContext.timestamp = headers.getFirst("X-Amz-Date");
    filterContext.date = filterContext.timestamp.split("T")[0];
    filterContext.host = requestContext.getUri().getHost();
    filterContext.region = filterContext.host.split("\\.")[1];
    filterContext.serviceName = filterContext.host.split("\\.")[0];
    filterContext.payload = requestContext.getEntity().toString().trim();
    filterContext.xAmzContentSha256 = requestContext.getHeaderString("X-Amz-Content-Sha256");
    filterContext.xAmzTarget = requestContext.getHeaderString("X-Amz-Target");
    filterContext.contentType = requestContext.getHeaderString("Content-Type");
    try {
        requestContext.getHeaders().putSingle("Authorization", generateAwsAuthSignature(filterContext));
    } catch (Exception ex) {
        LOGGER.log(Level.WARNING, "Failed to create Authorization header", ex);
    }
}
Also used : ClientRequestContext(javax.ws.rs.client.ClientRequestContext) IOException(java.io.IOException)

Example 19 with ClientRequestContext

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

the class JerseyClientTest method testTargetConfigUpdate.

@Test
public void testTargetConfigUpdate() {
    final JerseyWebTarget target = client.target("http://jersey.java.net/examples");
    target.getConfiguration().register(new ClientRequestFilter() {

        @Override
        public void filter(ClientRequestContext clientRequestContext) throws IOException {
            throw new UnsupportedOperationException("Not supported yet");
        }
    });
    assertEquals(1, target.getConfiguration().getInstances().size());
}
Also used : ClientRequestFilter(javax.ws.rs.client.ClientRequestFilter) ClientRequestContext(javax.ws.rs.client.ClientRequestContext) IOException(java.io.IOException) Test(org.junit.Test)

Example 20 with ClientRequestContext

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

the class JerseyInvocationTest method testNullResponseType.

@Test
public void testNullResponseType() throws Exception {
    final Client client = ClientBuilder.newClient();
    client.register(new ClientRequestFilter() {

        @Override
        public void filter(final ClientRequestContext requestContext) throws IOException {
            requestContext.abortWith(Response.ok().build());
        }
    });
    final WebTarget target = client.target("http://localhost:8080/mypath");
    final Class<Response> responseType = null;
    final String[] methods = new String[] { "GET", "PUT", "POST", "DELETE", "OPTIONS" };
    for (final String method : methods) {
        final Invocation.Builder request = target.request();
        try {
            request.method(method, responseType);
            fail("IllegalArgumentException expected.");
        } catch (final IllegalArgumentException iae) {
        // OK.
        }
        final Invocation build = "PUT".equals(method) ? request.build(method, Entity.entity("", MediaType.TEXT_PLAIN_TYPE)) : request.build(method);
        try {
            build.submit(responseType);
            fail("IllegalArgumentException expected.");
        } catch (final IllegalArgumentException iae) {
        // OK.
        }
        try {
            build.invoke(responseType);
            fail("IllegalArgumentException expected.");
        } catch (final IllegalArgumentException iae) {
        // OK.
        }
        try {
            request.async().method(method, responseType);
            fail("IllegalArgumentException expected.");
        } catch (final IllegalArgumentException iae) {
        // OK.
        }
    }
}
Also used : ClientRequestFilter(javax.ws.rs.client.ClientRequestFilter) ClientRequestContext(javax.ws.rs.client.ClientRequestContext) Invocation(javax.ws.rs.client.Invocation) IOException(java.io.IOException) Response(javax.ws.rs.core.Response) WebTarget(javax.ws.rs.client.WebTarget) Client(javax.ws.rs.client.Client) Test(org.junit.Test)

Aggregations

ClientRequestContext (javax.ws.rs.client.ClientRequestContext)30 Test (org.junit.Test)15 ClientResponseContext (javax.ws.rs.client.ClientResponseContext)11 Response (javax.ws.rs.core.Response)10 IOException (java.io.IOException)9 ClientRequestFilter (javax.ws.rs.client.ClientRequestFilter)8 ClientResponseFilter (javax.ws.rs.client.ClientResponseFilter)7 WebTarget (javax.ws.rs.client.WebTarget)7 Test (org.junit.jupiter.api.Test)7 URI (java.net.URI)6 Client (javax.ws.rs.client.Client)4 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)4 Message (org.apache.cxf.message.Message)4 MessageImpl (org.apache.cxf.message.MessageImpl)4 JerseyTest (org.glassfish.jersey.test.JerseyTest)4 ProcessingException (javax.ws.rs.ProcessingException)3 ContainerRequestContext (javax.ws.rs.container.ContainerRequestContext)3 CreateSignatureInterceptor (org.apache.cxf.rs.security.httpsignature.filters.CreateSignatureInterceptor)3 VerifySignatureFilter (org.apache.cxf.rs.security.httpsignature.filters.VerifySignatureFilter)3 MockAlgorithmProvider (org.apache.cxf.rs.security.httpsignature.provider.MockAlgorithmProvider)3