Java Code Examples for org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder

The following examples show how to use org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder. These examples are extracted from open source projects. 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 Project: oxAuth   Source File: TokenRestWebServiceEmbeddedTest.java    License: MIT License 7 votes vote down vote up
@Parameters({"tokenPath", "userId", "userSecret", "audience"})
@Test
public void requestAccessTokenWithClientSecretJwtFail(final String tokenPath, final String userId,
                                                      final String userSecret, final String audience) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + tokenPath).request();
    request.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);

    TokenRequest tokenRequest = new TokenRequest(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS);
    tokenRequest.setUsername(userId);
    tokenRequest.setPassword(userSecret);
    tokenRequest.setScope("email read_stream manage_pages");

    tokenRequest.setAuthPassword("INVALID_SECRET");
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_JWT);
    tokenRequest.setAudience(audience);

    Response response = request
            .post(Entity.form(new MultivaluedHashMap<String, String>(tokenRequest.getParameters())));
    String entity = response.readEntity(String.class);

    showResponse("requestAccessTokenWithClientSecretJwt Fail", response, entity);

    assertEquals(response.getStatus(), 401, "Unexpected response code.");
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has("error"), "The error type is null");
        assertTrue(jsonObj.has("error_description"), "The error description is null");
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example 2
Source Project: quarkus   Source File: RestClientProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@BuildStep
@Record(ExecutionTime.STATIC_INIT)
void setup(BuildProducer<FeatureBuildItem> feature,
        BuildProducer<AdditionalBeanBuildItem> additionalBeans,
        BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
        RestClientRecorder restClientRecorder) {

    feature.produce(new FeatureBuildItem(Feature.REST_CLIENT));

    restClientRecorder.setRestClientBuilderResolver();

    additionalBeans.produce(new AdditionalBeanBuildItem(RestClient.class));

    reflectiveClass.produce(new ReflectiveClassBuildItem(false, false,
            DefaultResponseExceptionMapper.class.getName(),
            AsyncInterceptorRxInvokerProvider.class.getName(),
            ResteasyProviderFactoryImpl.class.getName(),
            ProxyBuilderImpl.class.getName(),
            ClientRequestFilter[].class.getName(),
            ClientResponseFilter[].class.getName(),
            javax.ws.rs.ext.ReaderInterceptor[].class.getName()));

    reflectiveClass.produce(new ReflectiveClassBuildItem(true, false,
            ResteasyClientBuilder.class.getName()));
}
 
Example 3
Source Project: robozonky   Source File: ProxyFactory.java    License: Apache License 2.0 6 votes vote down vote up
public static ResteasyClient newResteasyClient() {
    LOGGER.debug("Creating RESTEasy client.");
    final Settings settings = Settings.INSTANCE;
    final long socketTimeout = settings.getSocketTimeout()
        .toMillis();
    LOGGER.debug("Set socket timeout to {} ms.", socketTimeout);
    final long connectionTimeout = settings.getConnectionTimeout()
        .toMillis();
    LOGGER.debug("Set connection timeout to {} ms.", connectionTimeout);
    final ResteasyClientBuilder builder = ((ResteasyClientBuilder) ClientBuilder.newBuilder())
        .useAsyncHttpEngine()
        .readTimeout(socketTimeout, TimeUnit.MILLISECONDS)
        .connectTimeout(connectionTimeout, TimeUnit.MILLISECONDS);
    /*
     * setup HTTP proxy when required (see
     * http://docs.jboss.org/resteasy/docs/4.0.0.Final/userguide/html/RESTEasy_Client_Framework.html#http_proxy)
     */
    settings.getHttpsProxyHostname()
        .ifPresent(host -> {
            final int port = settings.getHttpsProxyPort();
            builder.property("org.jboss.resteasy.jaxrs.client.proxy.host", host)
                .property("org.jboss.resteasy.jaxrs.client.proxy.port", port);
            LOGGER.debug("Set HTTP proxy to {}:{}.", host, port);
        });
    return builder.build();
}
 
Example 4
Source Project: java-jaxrs   Source File: RestEasyITest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * A substitution for {@link #testAsyncError()}. It test that span is reported.
 */
@Test
public void testAsyncErrorTestSpanReported() {
    // disable retry otherwise there can be 2 spans
    CloseableHttpClient build = HttpClientBuilder.create().disableAutomaticRetries().build();
    Client client = new ResteasyClientBuilder().httpEngine(new ApacheHttpClient4Engine(build)).build();
    try (Response response = client.target(url("/asyncError"))
        .request()
        .get()) {
        response.readEntity(String.class);
    } catch (Exception ex) {
        // client throws an exception if async request fails
    } finally {
          client.close();
    }
    await().until(finishedSpansSizeEquals(1));

    List<MockSpan> mockSpans = mockTracer.finishedSpans();
    Assert.assertEquals(1, mockSpans.size());
    assertOnErrors(mockSpans);
}
 
Example 5
Source Project: thorntail   Source File: ZipkinJAXRSTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSpanLogging() throws Exception {
    ResteasyClient client = (ResteasyClient) ResteasyClientBuilder.newClient();
    client.register(ClientRequestInterceptor.class);
    client.register(ClientResponseInterceptor.class);

    Response response = client.target("http://localhost:8080").request(MediaType.TEXT_PLAIN).get();
    Assert.assertEquals(200, response.getStatus());

    // check log file for span reporting & the specified service name
    // the default zipkin fraction logs to system out

    List<String> logContent = Files.readAllLines(Paths.get(LOG_FILE));
    boolean spanPresent = logContent.stream().anyMatch(line -> line.contains(SPAN_COLLECTOR));
    Assert.assertTrue("Span logging missing from log file", spanPresent);

    boolean serviceNamePresent = logContent.stream().anyMatch(line -> line.contains(SERVICE_NAME));
    Assert.assertTrue("Service name " + SERVICE_NAME + " missing from log file", serviceNamePresent);
}
 
Example 6
Source Project: oxAuth   Source File: UmaScopeWSTest.java    License: MIT License 6 votes vote down vote up
@Parameters({ "umaScopePath" })
@Test
public void scopePresence(final String umaScopePath) throws Exception {
	String path = umaScopePath + "/" + "modify";
	System.out.println("Path: " + path);

	Builder request = ResteasyClientBuilder.newClient().target(url.toString() + path).request();
	request.header("Accept", UmaConstants.JSON_MEDIA_TYPE);
	Response response = request.get();
	String entity = response.readEntity(String.class);

	BaseTest.showResponse("UMA : UmaScopeWSTest.scopePresence() : ", response, entity);

	assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "Unexpected response code.");

	final UmaScopeDescription scope = TUma.readJsonValue(entity, UmaScopeDescription.class);

	UmaTestUtil.assert_(scope);
}
 
Example 7
Source Project: tutorials   Source File: RestEasyClientLiveTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testUpdateMovie() {

    final ResteasyClient client = new ResteasyClientBuilder().build();
    final ResteasyWebTarget target = client.target(FULL_PATH);
    final ServicesInterface proxy = target.proxy(ServicesInterface.class);

    Response moviesResponse = proxy.addMovie(batmanMovie);
    moviesResponse.close();
    batmanMovie.setTitle("Batman Begins");
    moviesResponse = proxy.updateMovie(batmanMovie);

    if (moviesResponse.getStatus() != Response.Status.OK.getStatusCode()) {
        System.out.println("Failed : HTTP error code : " + moviesResponse.getStatus());
    }

    moviesResponse.close();
    System.out.println("Response Code: " + moviesResponse.getStatus());
}
 
Example 8
Source Project: oxAuth   Source File: TRegisterResource.java    License: MIT License 6 votes vote down vote up
public List<String> getResourceList(final Token p_pat, String p_umaRegisterResourcePath) {
	final List<String> result = new ArrayList<String>();

	try {
		Builder request = ResteasyClientBuilder.newClient().target(baseUri.toString() + p_umaRegisterResourcePath)
				.request();
		request.header("Accept", UmaConstants.JSON_MEDIA_TYPE);
		request.header("Authorization", "Bearer " + p_pat.getAccessToken());
		Response response = request.get();
		String entity = response.readEntity(String.class);

		BaseTest.showResponse("UMA : TRegisterResource.getResourceList() : ", response, entity);

		assertEquals(response.getStatus(), 200, "Unexpected response code.");

		List<String> list = TUma.readJsonValue(entity, List.class);
		if (list != null) {
			result.addAll(list);
		}
	} catch (Exception e) {
		e.printStackTrace();
		fail();
	}
	return result;
}
 
Example 9
Source Project: maven-framework-project   Source File: EncryptedServiceTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testEncryptedGet() throws Exception {
	// LOADING THE CERTIFICATE
	X509Certificate myX509Certificate = 							PemUtils.decodeCertificate(
			Thread
			.currentThread().getContextClassLoader()
			.getResourceAsStream("democert.pem"));
	// LOADING THE KEY
	PrivateKey myPrivateKey = PemUtils.decodePrivateKey(Thread
			.currentThread().getContextClassLoader()
			.getResourceAsStream("demokey.pem"));
	// CREATING A CLIENT FOR THE WEB SERVICE
	Client client = new ResteasyClientBuilder().build();
	WebTarget target = client								.target(
     		"http://localhost:8080/encryption-1.0/services/encrypted"
	);
	// RETRIEVING THE RESULT OF METHOD EXECUTION
	EnvelopedInput<?> input = 	target.request().
					get(EnvelopedInput.class);
	Assert.assertEquals("Hello world",
			input.getEntity(String.class, 
			myPrivateKey, myX509Certificate));
	client.close();

}
 
Example 10
Source Project: oxAuth   Source File: RegistrationRestWebServiceEmbeddedTest.java    License: MIT License 6 votes vote down vote up
@Parameters({"registerPath"})
@Test
public void failRegistration_whenRedirectUriIsNotSetForResponseTypeCode(final String registerPath) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();

    String registerRequestContent = null;
    try {
        RegisterRequest registerRequest = new RegisterRequest(null, null, null);
        registerRequest.setResponseTypes(Lists.newArrayList(ResponseType.CODE));

        registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }

    Response response = request.post(Entity.json(registerRequestContent));
    String entity = response.readEntity(String.class);

    showResponse("requestClientRegistrationFail 1", response, entity);

    assertEquals(response.getStatus(), 400, "Unexpected response code. " + entity);
    TestUtil.assertErrorResponse(entity);
}
 
Example 11
Source Project: keycloak   Source File: LoginPageTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void acceptLanguageHeader() {
    ProfileAssume.assumeCommunity();
    
    CloseableHttpClient httpClient = (CloseableHttpClient) new HttpClientBuilder().build();
    ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient);
    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();

    loginPage.open();
    Response response = client.target(driver.getCurrentUrl()).request().acceptLanguage("de").get();
    Assert.assertTrue(response.readEntity(String.class).contains("Anmeldung bei test"));

    response = client.target(driver.getCurrentUrl()).request().acceptLanguage("en").get();
    Assert.assertTrue(response.readEntity(String.class).contains("Log in to test"));

    client.close();
}
 
Example 12
Source Project: oxAuth   Source File: UserInfoRestWebServiceEmbeddedTest.java    License: MIT License 6 votes vote down vote up
@Parameters({"userInfoPath"})
@Test
public void requestUserInfoInvalidToken(final String userInfoPath) throws Exception {
    UserInfoRequest userInfoRequest = new UserInfoRequest("INVALID_ACCESS_TOKEN");
    userInfoRequest.setAuthorizationMethod(AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER);

    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + userInfoPath).request();
    Response response = request
            .post(Entity.form(new MultivaluedHashMap<String, String>(userInfoRequest.getParameters())));
    String entity = response.readEntity(String.class);

    showResponse("requestUserInfoInvalidToken", response, entity);

    assertEquals(response.getStatus(), 401, "Unexpected response code.");
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has("error"), "The error type is null");
        assertTrue(jsonObj.has("error_description"), "The error description is null");
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example 13
Source Project: keycloak   Source File: DemoServletsAdapterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNullBearerTokenCustomErrorPage() {
    Client client = new ResteasyClientBuilder().httpEngine(new FollowRedirectsEngine()).build();
    WebTarget target = client.target(customerDbErrorPage.toString());

    Response response = target.request().get();

    assertEquals(401, response.getStatus());
    String errorPageResponse = response.readEntity(String.class);
    assertThat(errorPageResponse, containsString("Error Page"));
    assertThat(errorPageResponse, containsString(OIDCAuthenticationError.Reason.NO_BEARER_TOKEN.toString()));
    response.close();

    response = target.request().header(HttpHeaders.AUTHORIZATION, "Bearer null").get();

    assertEquals(401, response.getStatus());
    errorPageResponse = response.readEntity(String.class);
    assertThat(errorPageResponse, containsString("Error Page"));
    assertThat(errorPageResponse, containsString(OIDCAuthenticationError.Reason.INVALID_TOKEN.toString()));
    response.close();
    
    client.close();
}
 
Example 14
Source Project: oxAuth   Source File: RegistrationRestWebServiceEmbeddedTest.java    License: MIT License 6 votes vote down vote up
@Parameters({"registerPath"})
@Test
public void requestClientRegistrationFail3(final String registerPath) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();

    String registerRequestContent = null;
    try {

        RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
                Arrays.asList("https://client.example.com/cb#fail_fragment"));

        registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage());
    }

    Response response = request.post(Entity.json(registerRequestContent));
    String entity = response.readEntity(String.class);

    showResponse("requestClientRegistrationFail3", response, entity);

    assertEquals(response.getStatus(), 400, "Unexpected response code. " + entity);
    TestUtil.assertErrorResponse(entity);
}
 
Example 15
Source Project: oxAuth   Source File: TRegisterResource.java    License: MIT License 6 votes vote down vote up
public void deleteResource(final Token p_pat, String p_umaRegisterResourcePath, String p_id) {
	String path = p_umaRegisterResourcePath + "/" + p_id + "/";
	try {

		Builder request = ResteasyClientBuilder.newClient().target(baseUri.toString() + path).request();
		// request.addHeader("Accept",
		// UmaConstants.RESOURCE_SET_STATUS_MEDIA_TYPE);
		request.header("Authorization", "Bearer " + p_pat.getAccessToken());

		Response response = request.delete();
		String entity = response.readEntity(String.class);

		BaseTest.showResponse("UMA : TRegisterResource.deleteResource() : ", response, entity);

		assertEquals(response.getStatus(), Response.Status.NO_CONTENT.getStatusCode(), "Unexpected response code.");
	} catch (Exception e) {
		e.printStackTrace();
		fail();
	}
}
 
Example 16
Source Project: oxAuth   Source File: UserAuthenticationFilterEmbeddedTest.java    License: MIT License 5 votes vote down vote up
@Parameters({"registerPath", "redirectUris"})
@Test
public void dynamicClientRegistration(final String registerPath, final String redirectUris) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();

    List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE, ResponseType.TOKEN, ResponseType.ID_TOKEN);

    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setResponseTypes(responseTypes);
    registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");

    List<GrantType> grantTypes = Arrays.asList(
            GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS
    );
    registerRequest.setGrantTypes(grantTypes);

    String registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());

    Response response = request.post(Entity.json(registerRequestContent));
    String entity = response.readEntity(String.class);

    showResponse("dynamicClientRegistration", response, entity);

    assertEquals(response.getStatus(), 200, "Unexpected response code. " + entity);
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        final RegisterResponse registerResponse = RegisterResponse.valueOf(entity);
        ClientTestUtil.assert_(registerResponse);

        clientId = registerResponse.getClientId();
        clientSecret = registerResponse.getClientSecret();
    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example 17
Source Project: sunbird-lms-service   Source File: KeyCloakConnectionProvider.java    License: MIT License 5 votes vote down vote up
/**
 * Method to initializate the Keycloak connection
 *
 * @return Keycloak connection
 */
public static Keycloak initialiseConnection() throws Exception {
  ProjectLogger.log("key cloak instance is creation started.");
  keycloak = initialiseEnvConnection();
  if (keycloak != null) {
    return keycloak;
  }
  KeycloakBuilder keycloakBuilder =
      KeycloakBuilder.builder()
          .serverUrl(cache.getProperty(JsonKey.SSO_URL))
          .realm(cache.getProperty(JsonKey.SSO_REALM))
          .username(cache.getProperty(JsonKey.SSO_USERNAME))
          .password(cache.getProperty(JsonKey.SSO_PASSWORD))
          .clientId(cache.getProperty(JsonKey.SSO_CLIENT_ID))
          .resteasyClient(
              new ResteasyClientBuilder()
                  .connectionPoolSize(Integer.parseInt(cache.getProperty(JsonKey.SSO_POOL_SIZE)))
                  .build());
  if (cache.getProperty(JsonKey.SSO_CLIENT_SECRET) != null
      && !(cache.getProperty(JsonKey.SSO_CLIENT_SECRET).equals(JsonKey.SSO_CLIENT_SECRET))) {
    keycloakBuilder.clientSecret(cache.getProperty(JsonKey.SSO_CLIENT_SECRET));
  }
  SSO_URL = cache.getProperty(JsonKey.SSO_URL);
  SSO_REALM = cache.getProperty(JsonKey.SSO_REALM);
  CLIENT_ID = cache.getProperty(JsonKey.SSO_CLIENT_ID);
  keycloak = keycloakBuilder.build();

  ProjectLogger.log("key cloak instance is created successfully.");
  return keycloak;
}
 
Example 18
Source Project: oxAuth   Source File: AuthorizationCodeFlowEmbeddedTest.java    License: MIT License 5 votes vote down vote up
@Parameters({"tokenPath"})
@Test(dependsOnMethods = {"dynamicClientRegistration", "revokeTokensStep2n3"})
public void revokeTokensStep4(final String tokenPath) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + tokenPath).request();

    TokenRequest tokenRequest = new TokenRequest(GrantType.REFRESH_TOKEN);
    tokenRequest.setRefreshToken(refreshToken1);
    tokenRequest.setScope("email read_stream manage_pages");
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);

    request.header("Authorization", "Basic " + tokenRequest.getEncodedCredentials());

    Response response = request
            .post(Entity.form(new MultivaluedHashMap<String, String>(tokenRequest.getParameters())));
    String entity = response.readEntity(String.class);

    showResponse("revokeTokensStep4", response, entity);

    assertEquals(response.getStatus(), 400, "Unexpected response code.");
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has("error"), "The error type is null");
        assertTrue(jsonObj.has("error_description"), "The error description is null");
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example 19
Source Project: oxAuth   Source File: OpenIDRequestObjectWithESAlgEmbeddedTest.java    License: MIT License 5 votes vote down vote up
@Parameters({ "registerPath", "redirectUris", "clientJwksUri" })
@Test
public void requestParameterMethodES384Step1(final String registerPath, final String redirectUris,
		final String jwksUri) throws Exception {

	Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();

	String registerRequestContent = null;
	try {
		List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN);

		RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
				StringUtils.spaceSeparatedToList(redirectUris));
		registerRequest.setJwksUri(jwksUri);
		registerRequest.setResponseTypes(responseTypes);
		registerRequest.setRequestObjectSigningAlg(SignatureAlgorithm.ES384);
		registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");

		registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());
	} catch (JSONException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

	Response response = request.post(Entity.json(registerRequestContent));
	String entity = response.readEntity(String.class);

	showResponse("requestParameterMethodES384Step1", response, entity);

	ResponseAsserter responseAsserter = ResponseAsserter.of(response.getStatus(), entity);
	responseAsserter.assertRegisterResponse();
	clientId2 = responseAsserter.getJson().getJson().getString(RegisterResponseParam.CLIENT_ID.toString());
}
 
Example 20
/**
 * Fail 2: Call to Token Endpoint with Auth Method
 * <code>client_secret_post</code> should fail.
 */
@Parameters({"tokenPath", "userId", "userSecret"})
@Test(dependsOnMethods = "tokenEndpointAuthMethodPrivateKeyJwtStep2")
public void tokenEndpointAuthMethodPrivateKeyJwtFail2(final String tokenPath, final String userId,
                                                      final String userSecret) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + tokenPath).request();

    TokenRequest tokenRequest = new TokenRequest(GrantType.RESOURCE_OWNER_PASSWORD_CREDENTIALS);
    tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST);
    tokenRequest.setUsername(userId);
    tokenRequest.setPassword(userSecret);
    tokenRequest.setScope("email read_stream manage_pages");
    tokenRequest.setAuthUsername(clientId5);
    tokenRequest.setAuthPassword(clientSecret5);

    request.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);

    Response response = request
            .post(Entity.form(new MultivaluedHashMap<String, String>(tokenRequest.getParameters())));

    String entity = response.readEntity(String.class);

    showResponse("tokenEndpointAuthMethodPrivateKeyJwtFail2", response, entity);

    assertEquals(response.getStatus(), 401, "Unexpected response code.");
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has("error"), "The error type is null");
        assertTrue(jsonObj.has("error_description"), "The error description is null");
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example 21
Source Project: keycloak   Source File: AdminClientUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static Keycloak createAdminClient(boolean ignoreUnknownProperties, String authServerContextRoot, String realmName, String username, String password, String clientId, String clientSecret) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException {
    ResteasyClientBuilder resteasyClientBuilder = new ResteasyClientBuilder();

    if ("true".equals(System.getProperty("auth.server.ssl.required"))) {
        File trustore = new File(PROJECT_BUILD_DIRECTORY, "dependency/keystore/keycloak.truststore");
        resteasyClientBuilder.sslContext(getSSLContextWithTrustore(trustore, "secret"));

        System.setProperty("javax.net.ssl.trustStore", trustore.getAbsolutePath());
    }

    // We need to ignore unknown JSON properties e.g. in the adapter configuration representation
    // during adapter backward compatibility testing
    if (ignoreUnknownProperties) {
        // We need to use anonymous class to avoid the following error from RESTEasy:
        // Provider class org.jboss.resteasy.plugins.providers.jackson.ResteasyJackson2Provider is already registered.  2nd registration is being ignored.
        ResteasyJackson2Provider jacksonProvider = new ResteasyJackson2Provider() {};
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        jacksonProvider.setMapper(objectMapper);
        resteasyClientBuilder.register(jacksonProvider, 100);
    }

    resteasyClientBuilder
        .hostnameVerification(ResteasyClientBuilder.HostnameVerificationPolicy.WILDCARD)
        .connectionPoolSize(10)
        .httpEngine(getCustomClientHttpEngine(resteasyClientBuilder, 1));
    
    return KeycloakBuilder.builder()
            .serverUrl(authServerContextRoot + "/auth")
            .realm(realmName)
            .username(username)
            .password(password)
            .clientId(clientId)
            .clientSecret(clientSecret)
            .resteasyClient(resteasyClientBuilder.build()).build();
}
 
Example 22
Source Project: java-jaxrs   Source File: RestEasyClientITest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Client getClient() {
    return new ResteasyClientBuilder()
        /**
         * To avoid  RESTEASY004655 "connection is still allocated" in {@link #testAsyncMultipleRequests()}
         */
        .connectionPoolSize(150)
        .executorService(new TracedExecutorService(Executors.newFixedThreadPool(8), mockTracer))
        .build();
}
 
Example 23
public ClientBuilder configure(ClientBuilder clientBuilder, ExecutorService executorService) {
  ResteasyClientBuilder resteasyClientBuilder = (ResteasyClientBuilder)clientBuilder;
  Tracer tracer = CDI.current().select(Tracer.class).get();
  return resteasyClientBuilder.executorService(new TracedExecutorService(executorService, tracer))
    .register(new Builder(tracer)
        .withTraceSerialization(false)
        .build());
}
 
Example 24
Source Project: oxAuth   Source File: TokenRestWebServiceEmbeddedTest.java    License: MIT License 5 votes vote down vote up
@Parameters({"tokenPath", "redirectUri"})
@Test(dependsOnMethods = "dynamicClientRegistration")
public void requestAccessToken(final String tokenPath, final String redirectUri) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + tokenPath).request();

    TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
    tokenRequest.setCode("6f6f3f01-a034-4336-bf31-2e74868e5838");
    tokenRequest.setRedirectUri(redirectUri);
    tokenRequest.setAuthUsername(clientId);
    tokenRequest.setAuthPassword(clientSecret);

    request.header("Authorization", "Basic " + tokenRequest.getEncodedCredentials());
    request.header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);

    Response response = request
            .post(Entity.form(new MultivaluedHashMap<String, String>(tokenRequest.getParameters())));
    String entity = response.readEntity(String.class);

    showResponse("requestAccessToken", response, entity);

    assertEquals(response.getStatus(), 400, "Unexpected response code.");
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has("error"), "The error type is null");
        assertTrue(jsonObj.has("error_description"), "The error description is null");
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example 25
private static FederatedUserService buildClient(String uri) {

        ResteasyClient client = new ResteasyClientBuilder().disableTrustManager().build();
        ResteasyWebTarget target =  client.target(uri);

        return target
                .proxyBuilder(FederatedUserService.class)
                .classloader(FederatedUserService.class.getClassLoader())
                .build();
    }
 
Example 26
Source Project: nexus-public   Source File: NexusITSupport.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * The jax-rs clients require ObjectMapper customizations to work with ComponentXO.
 */
private Customizer getObjectMapperCustomizer(final TestSuiteObjectMapperResolver testSuiteObjectMapperResolver) {
  return builder -> {
    ResteasyProviderFactory providerFactory = new LocalResteasyProviderFactory(
        ResteasyProviderFactory.newInstance());
    providerFactory.registerProviderInstance(testSuiteObjectMapperResolver, null, 1000, false);

    ResteasyClientBuilder resteasyClientBuilder = (ResteasyClientBuilder) builder;
    resteasyClientBuilder.providerFactory(providerFactory);
    RegisterBuiltin.register(providerFactory);
  };
}
 
Example 27
Source Project: nexus-public   Source File: NexusITSupport.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * The jax-rs clients require ObjectMapper customizations to work with ComponentXO.
 */
private Customizer getObjectMapperCustomizer(final TestSuiteObjectMapperResolver testSuiteObjectMapperResolver) {
  return builder -> {
    ResteasyProviderFactory providerFactory = new LocalResteasyProviderFactory(
        ResteasyProviderFactory.newInstance());
    providerFactory.registerProviderInstance(testSuiteObjectMapperResolver, null, 1000, false);

    ResteasyClientBuilder resteasyClientBuilder = (ResteasyClientBuilder) builder;
    resteasyClientBuilder.providerFactory(providerFactory);
    RegisterBuiltin.register(providerFactory);
  };
}
 
Example 28
@Override
public Client create(final RestClientConfiguration configuration) {
  checkNotNull(configuration);

  try (TcclBlock tccl = TcclBlock.begin(ResteasyClientBuilder.class)) {
    HttpContext httpContext = new BasicHttpContext();
    if (configuration.getUseTrustStore()) {
        httpContext.setAttribute(SSLContextSelector.USE_TRUST_STORE, true);
    }
    HttpClient client;
    if (configuration.getHttpClient() != null) {
      client = checkNotNull(configuration.getHttpClient().get());
    }
    else {
      client = httpClient.get();
    }
    ClientHttpEngine httpEngine = new ApacheHttpClient4Engine(client, httpContext);

    ResteasyClientBuilder builder = new ResteasyClientBuilder().httpEngine(httpEngine);

    if (configuration.getCustomizer() != null) {
      configuration.getCustomizer().apply(builder);
    }

    return builder.build();
  }
}
 
Example 29
/**
 * Register a client with Token Endpoint Auth Method
 * <code>client_secret_post</code>.
 */
@Parameters({"registerPath", "redirectUris"})
@Test
public void tokenEndpointAuthMethodClientSecretPostStep1(final String registerPath, final String redirectUris)
        throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();

    RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
            StringUtils.spaceSeparatedToList(redirectUris));
    registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_POST);
    registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");

    String registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());

    Response response = request.post(Entity.json(registerRequestContent));
    String entity = response.readEntity(String.class);

    showResponse("tokenEndpointAuthMethodClientSecretPostStep1", response, entity);

    assertEquals(response.getStatus(), 200, "Unexpected response code. " + entity);
    assertNotNull(entity, "Unexpected result: " + entity);
    try {
        JSONObject jsonObj = new JSONObject(entity);
        assertTrue(jsonObj.has(RegisterResponseParam.CLIENT_ID.toString()));
        assertTrue(jsonObj.has(CLIENT_SECRET.toString()));
        assertTrue(jsonObj.has(RegisterResponseParam.REGISTRATION_ACCESS_TOKEN.toString()));
        assertTrue(jsonObj.has(REGISTRATION_CLIENT_URI.toString()));
        assertTrue(jsonObj.has(CLIENT_ID_ISSUED_AT.toString()));
        assertTrue(jsonObj.has(CLIENT_SECRET_EXPIRES_AT.toString()));

        clientId3 = jsonObj.getString(RegisterResponseParam.CLIENT_ID.toString());
        clientSecret3 = jsonObj.getString(RegisterResponseParam.CLIENT_SECRET.toString());
        registrationAccessToken3 = jsonObj.getString(RegisterResponseParam.REGISTRATION_ACCESS_TOKEN.toString());
        registrationClientUri3 = jsonObj.getString(RegisterResponseParam.REGISTRATION_CLIENT_URI.toString());
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example 30
Source Project: oxAuth   Source File: OpenIDRequestObjectWithESAlgEmbeddedTest.java    License: MIT License 5 votes vote down vote up
@Parameters({ "registerPath", "redirectUris", "clientJwksUri" })
@Test
public void requestParameterMethodES256Step1(final String registerPath, final String redirectUris,
        final String jwksUri) throws Exception {
	Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath).request();

	String registerRequestContent = null;
	try {
		List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN);

		RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app",
				StringUtils.spaceSeparatedToList(redirectUris));
		registerRequest.setJwksUri(jwksUri);
		registerRequest.setResponseTypes(responseTypes);
		registerRequest.setRequestObjectSigningAlg(SignatureAlgorithm.ES256);
		registerRequest.addCustomAttribute("oxAuthTrustedClient", "true");

		registerRequestContent = ServerUtil.toPrettyJson(registerRequest.getJSONParameters());
	} catch (JSONException e) {
		fail(e.getMessage(), e);
	}

	Response response = request.post(Entity.json(registerRequestContent));
	String entity = response.readEntity(String.class);

	showResponse("requestParameterMethodES256Step1", response, entity);

	ResponseAsserter responseAsserter = ResponseAsserter.of(response.getStatus(), entity);
	responseAsserter.assertRegisterResponse();
	clientId1 = responseAsserter.getJson().getJson().getString(RegisterResponseParam.CLIENT_ID.toString());
}