Java Code Examples for org.apache.cxf.jaxrs.client.WebClient#header()

The following examples show how to use org.apache.cxf.jaxrs.client.WebClient#header() . 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: RestRequestByCxf.java    From activiti-in-action-codes with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    // 创建client对象
    WebClient client = WebClient.create(REST_URI);

    // Basic Auth身份认证
    String auth = "Basic " + Base64Utility.encode("kermit:kermit".getBytes());
    client.header("Authorization", auth);

    // 获取响应内容
    Response response = client.get();
    InputStream stream = (InputStream) response.getEntity();

    // 转换并输出响应结果
    StringWriter writer = new StringWriter();
    IOUtils.copy(stream, writer, "UTF-8");
    String respText = writer.toString();
    System.out.println(respText);
}
 
Example 2
Source File: TestService.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testHomeJSON() {
    if (!waitForWADL()) {
        return;
    }

    WebClient client = WebClient.create(ENDPOINT_ADDRESS);

    client.header("Authorization", "Basic YWRtaW46YWRtaW4=");
    client.type("application/json");
    client.accept("application/json");

    client.path("home");

    String response = readReource("json/response-home.json");

    String webRespose = client.get(String.class);
    assertEquals(response, webRespose);
}
 
Example 3
Source File: JAXRSSamlTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testInvalidSAMLTokenAsHeader() throws Exception {
    String address = "https://localhost:" + PORT + "/samlheader/bookstore/books/123";

    JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
    bean.setAddress(address);

    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = JAXRSSamlTest.class.getResource("client.xml");
    Bus springBus = bf.createBus(busFile.toString());
    bean.setBus(springBus);

    WebClient wc = bean.createWebClient();
    wc.header("Authorization", "SAML invalid_grant");
    Response r = wc.get();
    assertEquals(401, r.getStatus());
}
 
Example 4
Source File: TestService.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetDecisionByAttributesXML() {
    if (!waitForWADL()) {
        return;
    }

    WebClient client = WebClient.create(ENDPOINT_ADDRESS);

    client.header("Authorization", "Basic YWRtaW46YWRtaW4=");
    client.type("application/xml");
    client.accept("application/xml");

    client.path("by-attrib");

    String request = readReource("xml/request-by-attrib-1.xml");
    String response = readReource("xml/response-by-attrib-1.xml");

    String webRespose = client.post(request, String.class);

    assertEquals(response, webRespose);
}
 
Example 5
Source File: JAXRSClientServerBookTest.java    From cxf with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetBookByHeaderPerRequestInjectedFault() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore2/bookheaders/injected";
    WebClient wc = WebClient.create(address);
    wc.accept("application/xml");
    wc.header("BOOK", "2", "3");
    Response r = wc.get();
    assertEquals(400, r.getStatus());
    assertEquals("Param setter: 3 header values are required", r.readEntity(String.class));
}
 
Example 6
Source File: TestService.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetDecisionByAttributesBooleanXML() {
    if (!waitForWADL()) {
        return;
    }

    WebClient client = WebClient.create(ENDPOINT_ADDRESS);

    client.header("Authorization", "Basic YWRtaW46YWRtaW4=");
    client.type("application/xml");
    client.accept("application/xml");

    client.path("by-attrib-boolean");

    String request = readReource("xml/request-by-attrib-bool-1.xml");
    String response = readReource("xml/response-by-attrib-bool-1.xml");

    String webRespose = client.post(request, String.class);

    assertEquals(response, webRespose);
}
 
Example 7
Source File: TestService.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetDecisionByAttributesBooleanJSON() {
    if (!waitForWADL()) {
        return;
    }

    WebClient client = WebClient.create(ENDPOINT_ADDRESS);

    client.header("Authorization", "Basic YWRtaW46YWRtaW4=");
    client.type("application/json");
    client.accept("application/json");

    client.path("by-attrib-boolean");

    String request = readReource("json/request-by-attrib-bool-1.json");
    String response = readReource("json/response-by-attrib-bool-1.json");

    String webRespose = client.post(request, String.class);
    assertEquals(response, webRespose);
}
 
Example 8
Source File: TestService.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testEntitledAttributesXML() {
    if (!waitForWADL()) {
        return;
    }

    WebClient client = WebClient.create(ENDPOINT_ADDRESS);

    client.header("Authorization", "Basic YWRtaW46YWRtaW4=");
    client.type("application/xml");
    client.accept("application/xml");

    client.path("entitled-attribs");

    String request = readReource("xml/request-entitled-attribs-1.xml");
    String response = readReource("xml/response-entitled-attribs-1.xml");

    String webRespose = client.post(request, String.class);
    assertEquals(response, webRespose);
}
 
Example 9
Source File: TestService.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testAllEntitlementsXML() {
    if (!waitForWADL()) {
        return;
    }

    WebClient client = WebClient.create(ENDPOINT_ADDRESS);

    client.header("Authorization", "Basic YWRtaW46YWRtaW4=");
    client.type("application/xml");
    client.accept("application/xml");

    client.path("entitlements-all");

    String request = readReource("xml/request-all-entitlements-1.xml");
    String response = readReource("xml/response-all-entitlements-1.xml");

    String webRespose = client.post(request, String.class);
    assertEquals(response, webRespose);
}
 
Example 10
Source File: JAXRSJmsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutBookOneWayWithWebClient() throws Exception {
    // setup the the client
    String endpointAddressUrlEncoded = "jms:jndi:dynamicQueues/test.jmstransport.text"
         + "?replyToName=dynamicQueues/test.jmstransport.response"
         + "&jndiInitialContextFactory=org.apache.activemq.jndi.ActiveMQInitialContextFactory"
         + "&jndiURL=tcp://localhost:" + JMS_PORT;

    WebClient client = WebClient.create(endpointAddressUrlEncoded);
    WebClient.getConfig(client).getRequestContext()
        .put(org.apache.cxf.message.Message.REQUEST_URI, "/bookstore/oneway");
    client.header("OnewayRequest", "true");
    Response r = client.type("application/xml").put(new Book("OneWay From WebClient", 129L));
    assertEquals(202, r.getStatus());
    assertFalse(r.hasEntity());

    Context ctx = getContext();
    ConnectionFactory factory = (ConnectionFactory)ctx.lookup("ConnectionFactory");

    Destination replyToDestination = (Destination)ctx.lookup("dynamicQueues/test.jmstransport.response");

    Connection connection = null;
    try {
        connection = factory.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        checkBookInResponse(session, replyToDestination, 129L, "OneWay From WebClient");
        session.close();
    } finally {
        close(connection);
    }
}
 
Example 11
Source File: JAXRSClientServerBookTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetBookByHeaderPerRequestInjected() throws Exception {
    String address = "http://localhost:" + PORT + "/bookstore2/bookheaders/injected";
    WebClient wc = WebClient.create(address);
    wc.accept("application/xml");
    wc.header("BOOK", "1", "2", "3");
    Book b = wc.get(Book.class);
    assertEquals(123L, b.getId());
}
 
Example 12
Source File: HaHotCheckTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private void testResourcePost(String resourcePath, boolean force, int code) {
    WebClient resource = client().path(resourcePath)
            .accept(MediaType.APPLICATION_JSON_TYPE);
    if (force) {
        resource.header(HaHotCheckResourceFilter.SKIP_CHECK_HEADER, "true");
    }
    Response response = resource.post(null);
    assertEquals(response.getStatus(), code);
}
 
Example 13
Source File: HaHotCheckTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private void testResourceFetch(String resourcePath, boolean force, int code) {
    WebClient resource = client().path(resourcePath)
            .accept(MediaType.APPLICATION_JSON_TYPE);
    if (force) {
        resource.header(HaHotCheckResourceFilter.SKIP_CHECK_HEADER, "true");
    }
    Response response = resource
            .get();
    assertEquals(response.getStatus(), code);
}
 
Example 14
Source File: JAXRSHTTPSignatureTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testHeaderTrailingWhitespace() throws Exception {

    URL busFile = JAXRSHTTPSignatureTest.class.getResource("client.xml");

    CreateSignatureInterceptor signatureFilter = new CreateSignatureInterceptor();
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", this.getClass()),
                  "password".toCharArray());
    PrivateKey privateKey = (PrivateKey)keyStore.getKey("alice", "password".toCharArray());
    assertNotNull(privateKey);

    List<String> headerList = Arrays.asList("custom", "(request-target)");
    MessageSigner messageSigner = new MessageSigner(keyid -> privateKey, "alice-key-id", headerList);
    signatureFilter.setMessageSigner(messageSigner);

    String address = "http://localhost:" + PORT + "/httpsig/bookstore/books";
    WebClient client =
        WebClient.create(address, Collections.singletonList(signatureFilter), busFile.toString());
    client.type("application/xml").accept("application/xml");

    client.header("custom", " someval    ");

    Response response = client.post(new Book("CXF", 126L));
    assertEquals(200, response.getStatus());

    Book returnedBook = response.readEntity(Book.class);
    assertEquals(126L, returnedBook.getId());
}
 
Example 15
Source File: OIDCNegativeTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testUserInfoRefreshToken() throws Exception {
    URL busFile = UserInfoTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Authorization Code
    String code = OAuth2TestUtils.getAuthorizationCode(client, "openid");
    assertNotNull(code);

    // Now get the access token
    client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                              "consumer-id", "this-is-a-secret", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    ClientAccessToken accessToken =
        OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code);
    assertNotNull(accessToken.getTokenKey());
    String oldAccessToken = accessToken.getTokenKey();
    assertTrue(accessToken.getApprovedScope().contains("openid"));

    String idToken = accessToken.getParameters().get("id_token");
    assertNotNull(idToken);

    // Refresh the access token
    client.type("application/x-www-form-urlencoded").accept("application/json");

    Form form = new Form();
    form.param("grant_type", "refresh_token");
    form.param("refresh_token", accessToken.getRefreshToken());
    form.param("client_id", "consumer-id");
    form.param("scope", "openid");
    Response response = client.post(form);

    accessToken = response.readEntity(ClientAccessToken.class);
    assertNotNull(accessToken.getTokenKey());
    assertNotNull(accessToken.getRefreshToken());
    accessToken.getParameters().get("id_token");
    assertNotNull(idToken);
    String newAccessToken = accessToken.getTokenKey();

    // Now test the UserInfoService.

    // The old Access Token should fail
    String userInfoAddress = "https://localhost:" + port + "/ui/plain/userinfo";
    WebClient userInfoClient = WebClient.create(userInfoAddress, OAuth2TestUtils.setupProviders(),
                                                busFile.toString());
    userInfoClient.accept("application/json");
    userInfoClient.header("Authorization", "Bearer " + oldAccessToken);

    Response serviceResponse = userInfoClient.get();
    assertEquals(serviceResponse.getStatus(), 401);

    // The refreshed Access Token should work
    userInfoClient.replaceHeader("Authorization", "Bearer " + newAccessToken);
    serviceResponse = userInfoClient.get();
    assertEquals(serviceResponse.getStatus(), 200);

    UserInfo userInfo = serviceResponse.readEntity(UserInfo.class);
    assertNotNull(userInfo);

    assertEquals("alice", userInfo.getSubject());
    assertEquals("consumer-id", userInfo.getAudience());
}
 
Example 16
Source File: UserInfoTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testSignedUserInfo() throws Exception {
    URL busFile = UserInfoTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/oidc";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());

    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Authorization Code
    String code = OAuth2TestUtils.getAuthorizationCode(client, "openid");
    assertNotNull(code);

    // Now get the access token
    client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                              "consumer-id", "this-is-a-secret", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    ClientAccessToken accessToken =
        OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code);
    assertNotNull(accessToken.getTokenKey());
    assertTrue(accessToken.getApprovedScope().contains("openid"));

    String idToken = accessToken.getParameters().get("id_token");
    assertNotNull(idToken);
    validateIdToken(idToken, null);

    // Now invoke on the UserInfo service with the access token
    String userInfoAddress = "https://localhost:" + port + "/services/signed/userinfo";
    WebClient userInfoClient = WebClient.create(userInfoAddress, OAuth2TestUtils.setupProviders(),
                                                busFile.toString());
    userInfoClient.accept("application/jwt");
    userInfoClient.header("Authorization", "Bearer " + accessToken.getTokenKey());

    Response serviceResponse = userInfoClient.get();
    assertEquals(serviceResponse.getStatus(), 200);

    String token = serviceResponse.readEntity(String.class);
    assertNotNull(token);

    JwsJwtCompactConsumer jwtConsumer = new JwsJwtCompactConsumer(token);
    JwtToken jwt = jwtConsumer.getJwtToken();

    assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
    assertEquals("consumer-id", jwt.getClaim(JwtConstants.CLAIM_AUDIENCE));

    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", this.getClass()),
                  "password".toCharArray());
    Certificate cert = keystore.getCertificate("alice");
    assertNotNull(cert);

    assertTrue(jwtConsumer.verifySignatureWith((X509Certificate)cert,
                                                      SignatureAlgorithm.RS256));
}
 
Example 17
Source File: UserInfoTest.java    From cxf with Apache License 2.0 4 votes vote down vote up
@org.junit.Test
public void testEncryptedUserInfo() throws Exception {
    URL busFile = UserInfoTest.class.getResource("client.xml");

    String address = "https://localhost:" + port + "/services/oidc";
    WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                                        "alice", "security", busFile.toString());

    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    // Get Authorization Code
    String code = OAuth2TestUtils.getAuthorizationCode(client, "openid");
    assertNotNull(code);

    // Now get the access token
    client = WebClient.create(address, OAuth2TestUtils.setupProviders(),
                              "consumer-id", "this-is-a-secret", busFile.toString());
    // Save the Cookie for the second request...
    WebClient.getConfig(client).getRequestContext().put(
        org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE);

    ClientAccessToken accessToken =
        OAuth2TestUtils.getAccessTokenWithAuthorizationCode(client, code);
    assertNotNull(accessToken.getTokenKey());
    assertTrue(accessToken.getApprovedScope().contains("openid"));

    String idToken = accessToken.getParameters().get("id_token");
    assertNotNull(idToken);
    validateIdToken(idToken, null);

    // Now invoke on the UserInfo service with the access token
    String userInfoAddress = "https://localhost:" + port + "/services/encrypted/userinfo";
    WebClient userInfoClient = WebClient.create(userInfoAddress, OAuth2TestUtils.setupProviders(),
                                                busFile.toString());
    userInfoClient.accept("application/jwt");
    userInfoClient.header("Authorization", "Bearer " + accessToken.getTokenKey());

    Response serviceResponse = userInfoClient.get();
    assertEquals(200, serviceResponse.getStatus());

    String token = serviceResponse.readEntity(String.class);
    assertNotNull(token);

    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(ClassLoaderUtils.getResourceAsStream("keys/alice.jks", this.getClass()),
                  "password".toCharArray());

    JweJwtCompactConsumer jwtConsumer = new JweJwtCompactConsumer(token);
    PrivateKey privateKey = (PrivateKey)keystore.getKey("alice", "password".toCharArray());
    JwtToken jwt = jwtConsumer.decryptWith(privateKey);

    assertEquals("alice", jwt.getClaim(JwtConstants.CLAIM_SUBJECT));
    assertEquals("consumer-id", jwt.getClaim(JwtConstants.CLAIM_AUDIENCE));
}
 
Example 18
Source File: RestRequestTandem.java    From activiti-in-action-codes with Apache License 2.0 4 votes vote down vote up
private static WebClient createClient(String uri) {
    WebClient client = WebClient.create(BASE_REST_URI + uri);
    String auth = "Basic " + Base64Utility.encode("kermit:kermit".getBytes());
    client.header("Authorization", auth);
    return client;
}
 
Example 19
Source File: RestRequestForDiagramViewer.java    From activiti-in-action-codes with Apache License 2.0 4 votes vote down vote up
private static WebClient createClient(String uri) {
    WebClient client = WebClient.create(BASE_REST_URI + uri);
    String auth = "Basic " + Base64Utility.encode("kermit:000000".getBytes());
    client.header("Authorization", auth);
    return client;
}
 
Example 20
Source File: LoadBalancerRegisterService.java    From microservice-with-jwt-and-microprofile with Apache License 2.0 4 votes vote down vote up
@PostConstruct
public void setup() {
    // sanity checks and adjustements
    Objects.requireNonNull(hostUrl,
            "Host URL required. For example: http://localhost:53302 " +
                    "One node of the Tribestream API Gateway cluster is enough. No need to register to all nodes.");
    Objects.requireNonNull(serverUrl,
            "Server URL required so the Tribestream API Gateway can forward traffic to us. For example: http://localhost:8080");
    Objects.requireNonNull(connectionId,
            "Connection ID required so we can add ourselves to the load balancer. For example: api-twitter");
    Objects.requireNonNull(signaturesKeyId, "Key ID for HTTP Signatures authentication is required");
    Objects.requireNonNull(signaturesKey, "Key value for HTTP Signatures authentication is required. Can be a plain String" +
            " if using an HMAC for example. But can also be a PEM if using RSA for instance");
    Objects.requireNonNull(signaturesAlgorithm, "Algorithm for HTTP Signatures authentication is required");

    if (unregisterOnShutdown == null) {
        LOGGER.info("unregisterOnShutdown not set. Adjusting to true.");
        unregisterOnShutdown = true;
    }
    if (active == null) {
        LOGGER.info("active not set. Adjusting to true so the current host is automatically active for the " +
                "API Connection load balancer.");
        active = true;
    }
    if (acceptAllCertificates == null) {
        LOGGER.info("acceptAllCertificates not set. Adjusting to false. The remote certificate " +
                "must be in your trust store");
        acceptAllCertificates = false;
    }
    if (weight == null) {
        LOGGER.info("weight not set. Adjusting to 1. If all registered hosts have a weight of 1, they" +
                " will all receive the same traffic.");
        weight = 1;
    }
    if (signaturesSignedHeaders == null) {
        LOGGER.info("signaturesSignedHeaders not set. Adjusting to '(request-target) date'.");
        signaturesSignedHeaders = "(request-target) date";
    }
    if (signaturesHeader == null) {
        LOGGER.info("signaturesHeader not set. Adjusting to 'Authorization'.");
        signaturesHeader = "Authorization";
    }
    if (registerEndpoint == null) {
        LOGGER.info("registerEndpoint not set. Adjusting to '/tag/api/http/{connectionId}/hosts/register'.");
        registerEndpoint = "/tag/api/http/{connectionId}/hosts/register";
    }

    if (unregisterOnShutdown) {
        if (unregisterEndpoint == null) {
            LOGGER.info("unregisterOnShutdown not set. Adjusting to '/tag/api/http/{connectionId}/hosts/unregister'.");
            unregisterEndpoint = "/tag/api/http/{connectionId}/hosts/unregister";
        }
    }

    // only use plain tomee dependencies here (aka johnzon if really needed and a plain Http URL Connection so
    // we can extract this into a lib anyone can pull into a tomee to connect to TAG.

    final String payload = toJson();
    final Map<String, String> headers = new HashMap<String, String>() {{
        put("Date", new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US) {{
            setTimeZone(TimeZone.getTimeZone("GMT"));
        }}.format(new Date()));
        put("Digest", toDigest(payload, "SHA-256"));
    }};
    final String signature = toSignature(headers);

    final WebClient webClient = clientFor().path(registerEndpoint, connectionId)
            .accept(APPLICATION_JSON_TYPE)
            .type(MediaType.APPLICATION_JSON_TYPE)
            .header(signaturesHeader, signature);

    for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
        webClient.header(headerEntry.getKey(), headerEntry.getValue());
    }

    final Response response = webClient.post(payload);

    if (response.getStatus() != Response.Status.OK.getStatusCode()) {
        // maybe also add the Entity string itself
        throw new IllegalStateException("Could not auto register host to the API Gateway. Status is " + response.getStatus());
    }

    LOGGER.info("Successfully registered into the load balancer group for API Connection " + connectionId);
}