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

The following examples show how to use org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder. 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: UserInfoRestWebServiceEmbeddedTest.java    From oxAuth with 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 #2
Source File: DemoServletsAdapterTest.java    From keycloak with 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 #3
Source File: LoginPageTest.java    From keycloak with 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 #4
Source File: RestClientProcessor.java    From quarkus with 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 #5
Source File: ProxyFactory.java    From robozonky with 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 #6
Source File: RestEasyITest.java    From java-jaxrs with 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 #7
Source File: RegistrationRestWebServiceEmbeddedTest.java    From oxAuth with 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 #8
Source File: TokenRestWebServiceEmbeddedTest.java    From oxAuth with MIT License 6 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 #9
Source File: ZipkinJAXRSTest.java    From thorntail with 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 #10
Source File: EncryptedServiceTest.java    From maven-framework-project with 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 #11
Source File: TRegisterResource.java    From oxAuth with 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 #12
Source File: UmaScopeWSTest.java    From oxAuth with 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 #13
Source File: TRegisterResource.java    From oxAuth with 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 #14
Source File: RestEasyClientLiveTest.java    From tutorials with 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 #15
Source File: RegistrationRestWebServiceEmbeddedTest.java    From oxAuth with 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 #16
Source File: OpenIDRequestObjectWithRSAlgEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Parameters({ "registerPath", "redirectUris", "clientJwksUri" })
@Test
public void requestParameterMethodRS256Step1(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.RS256);
		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("requestParameterMethodRS256Step1", response, entity);

	ResponseAsserter responseAsserter = ResponseAsserter.of(response.getStatus(), entity);
	responseAsserter.assertRegisterResponse();
	clientId1 = responseAsserter.getJson().getJson().getString(RegisterResponseParam.CLIENT_ID.toString());
}
 
Example #17
Source File: TokenEndpointAuthMethodRestrictionEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * Fail 1: Call to Token Endpoint with Auth Method
 * <code>client_secret_basic</code> should fail.
 */
@Parameters({"tokenPath", "userId", "userSecret"})
@Test(dependsOnMethods = "tokenEndpointAuthMethodClientSecretJwtStep2")
public void tokenEndpointAuthMethodClientSecretJwtFail1(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_BASIC);
    tokenRequest.setUsername(userId);
    tokenRequest.setPassword(userSecret);
    tokenRequest.setScope("email read_stream manage_pages");
    tokenRequest.setAuthUsername(clientId4);
    tokenRequest.setAuthPassword(clientSecret4);

    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("tokenEndpointAuthMethodClientSecretJwtFail1", 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 #18
Source File: ClientFactory.java    From oxAuth with MIT License 5 votes vote down vote up
public IntrospectionService createIntrospectionService(String p_url, ClientHttpEngine engine) {
    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
    ResteasyWebTarget target = client.target(UriBuilder.fromPath(p_url));
    IntrospectionService proxy = target.proxy(IntrospectionService.class);

    return proxy;
}
 
Example #19
Source File: EndSessionUtils.java    From oxAuth with MIT License 5 votes vote down vote up
public static void callRpWithBackchannelUri(final String backchannelLogoutUri, String logoutToken) {
    javax.ws.rs.client.Client client = new ResteasyClientBuilder().httpEngine(ClientFactory.instance().createEngine(true)).build();
    WebTarget target = client.target(backchannelLogoutUri);

    log.debug("Calling RP with backchannel, backchannel_logout_uri: " + backchannelLogoutUri);
    try (Response response = target.request().post(Entity.form(new Form("logout_token", logoutToken)))) {
        log.debug("Backchannel RP response, status: " + response.getStatus() + ", backchannel_logout_uri" + backchannelLogoutUri);
    } catch (Exception e) {
        log.error("Failed to call backchannel_logout_uri" + backchannelLogoutUri + ", message: " + e.getMessage(), e);
    }
}
 
Example #20
Source File: FidoU2fClientFactory.java    From oxAuth with MIT License 5 votes vote down vote up
public U2fConfigurationService createMetaDataConfigurationService(String u2fMetaDataUri) {
    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
    ResteasyWebTarget target = client.target(UriBuilder.fromPath(u2fMetaDataUri));
    U2fConfigurationService proxy = target.proxy(U2fConfigurationService.class);

    return proxy;
}
 
Example #21
Source File: FidoU2fClientFactory.java    From oxAuth with MIT License 5 votes vote down vote up
public AuthenticationRequestService createAuthenticationRequestService(U2fConfiguration metadataConfiguration) {
    ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
    ResteasyWebTarget target = client.target(UriBuilder.fromPath(metadataConfiguration.getAuthenticationEndpoint()));
    AuthenticationRequestService proxy = target.proxy(AuthenticationRequestService.class);

    return proxy;
}
 
Example #22
Source File: RestEasyClientLiveTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void testMovieByImdbId() {

    final String transformerImdbId = "tt0418279";

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

    final Response moviesResponse = proxy.addMovie(transformerMovie);
    moviesResponse.close();

    final Movie movies = proxy.movieByImdbId(transformerImdbId);
    System.out.println(movies);
}
 
Example #23
Source File: TokenEndpointAuthMethodRestrictionEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * Read client to check whether it is using the default Token Endpoint Auth
 * Method <code>client_secret_basic</code>.
 */
@Parameters({"registerPath"})
@Test(dependsOnMethods = "omittedTokenEndpointAuthMethodStep1")
public void omittedTokenEndpointAuthMethodStep2(final String registerPath) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath + "?"
            + registrationClientUri1.substring(registrationClientUri1.indexOf("?") + 1)).request();
    request.header("Authorization", "Bearer " + registrationAccessToken1);

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

    showResponse("omittedTokenEndpointAuthMethodStep2", 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(CLIENT_ID_ISSUED_AT.toString()));
        assertTrue(jsonObj.has(CLIENT_SECRET_EXPIRES_AT.toString()));

        // Registered Metadata
        assertTrue(jsonObj.has(TOKEN_ENDPOINT_AUTH_METHOD.toString()));
        assertEquals(jsonObj.getString(TOKEN_ENDPOINT_AUTH_METHOD.toString()),
                AuthenticationMethod.CLIENT_SECRET_BASIC.toString());
        assertTrue(jsonObj.has(APPLICATION_TYPE.toString()));
        assertTrue(jsonObj.has(RESPONSE_TYPES.toString()));
        assertTrue(jsonObj.has(REDIRECT_URIS.toString()));
        assertTrue(jsonObj.has(APPLICATION_TYPE.toString()));
        assertTrue(jsonObj.has(CLIENT_NAME.toString()));
        assertTrue(jsonObj.has(ID_TOKEN_SIGNED_RESPONSE_ALG.toString()));
        assertTrue(jsonObj.has(SCOPE.toString()));
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example #24
Source File: TokenRestWebServiceEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Parameters({"tokenPath"})
@Test(dependsOnMethods = "dynamicClientRegistration")
public void refreshingAccessTokenFail(final String tokenPath) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + tokenPath).request();

    TokenRequest tokenRequest = new TokenRequest(GrantType.REFRESH_TOKEN);
    tokenRequest.setRefreshToken("tGzv3JOkF0XG5Qx2TlKWIA");
    tokenRequest.setScope("email read_stream manage_pages");
    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("refreshingAccessTokenFail", 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
Source File: ApplicationTypeRestrictionEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
/**
 * Read client to check whether it is using the Application Type
 * <code>native</code>.
 */
@Parameters({"registerPath"})
@Test(dependsOnMethods = "applicationTypeNativeStep1")
public void applicationTypeNativeStep2(final String registerPath) throws Exception {

    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + registerPath + "?"
            + registrationClientUri3.substring(registrationClientUri3.indexOf("?") + 1)).request();
    request.header("Authorization", "Bearer " + registrationAccessToken3);

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

    showResponse("applicationTypeNativeStep2", response);

    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(CLIENT_ID_ISSUED_AT.toString()));
        assertTrue(jsonObj.has(CLIENT_SECRET_EXPIRES_AT.toString()));

        // Registered Metadata
        assertTrue(jsonObj.has(APPLICATION_TYPE.toString()));
        assertEquals(jsonObj.getString(APPLICATION_TYPE.toString()), ApplicationType.NATIVE.toString());
        assertTrue(jsonObj.has(RESPONSE_TYPES.toString()));
        assertNotNull(jsonObj.optJSONArray(RESPONSE_TYPES.toString()));
        assertEquals(jsonObj.getJSONArray(RESPONSE_TYPES.toString()).getString(0), ResponseType.CODE.toString());
        assertTrue(jsonObj.has(REDIRECT_URIS.toString()));
        assertTrue(jsonObj.has(APPLICATION_TYPE.toString()));
        assertTrue(jsonObj.has(CLIENT_NAME.toString()));
        assertTrue(jsonObj.has(ID_TOKEN_SIGNED_RESPONSE_ALG.toString()));
        assertTrue(jsonObj.has(SCOPE.toString()));
    } catch (JSONException e) {
        e.printStackTrace();
        fail(e.getMessage() + "\nResponse was: " + entity);
    }
}
 
Example #26
Source File: UiResourceIT.java    From digdag with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp()
        throws Exception
{
    http = new ResteasyClientBuilder()
        .build();
}
 
Example #27
Source File: OpenIDRequestObjectWithRSAlgEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Parameters({ "registerPath", "redirectUris", "clientJwksUri" })
@Test
public void requestParameterMethodRS512X509CertStep1(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.RS512);
		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("requestParameterMethodRS512X509CertStep1", response, entity);

	ResponseAsserter responseAsserter = ResponseAsserter.of(response.getStatus(), entity);
	responseAsserter.assertRegisterResponse();
	clientId6 = responseAsserter.getJson().getJson().getString(RegisterResponseParam.CLIENT_ID.toString());
}
 
Example #28
Source File: TRegisterResource.java    From oxAuth with MIT License 5 votes vote down vote up
private UmaResourceResponse registerResourceInternal(final Token pat, String umaRegisterResourcePath,
													 final UmaResource resource) throws Exception {
	String path = umaRegisterResourcePath;
	System.out.println("Path: " + path);

	System.out.println("PAT: " + pat.getAccessToken());
	Builder request = ResteasyClientBuilder.newClient().target(baseUri.toString() + path).request();
	request.header("Accept", UmaConstants.JSON_MEDIA_TYPE);
	request.header("Authorization", "Bearer " + pat.getAccessToken());

	String json = null;
	try {
		// final String json = "{\"resource\":{\"name\":\"Server Photo
		// Album22\",\"iconUri\":\"http://www.example.com/icons/flower.png\",\"scopes\":[\"http://photoz.example.com/dev/scopes/view\",\"http://photoz.example.com/dev/scopes/all\"]}}";
		// final String json =
		// ServerUtil.jsonMapperWithWrapRoot().writeValueAsString(resource);
		json = ServerUtil.createJsonMapper().writeValueAsString(resource);
		System.out.println("Json: " + json);
	} catch (Exception e) {
		e.printStackTrace();
		fail();
	}

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

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

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

	registerStatus = TUma.readJsonValue(entity, UmaResourceResponse.class);

	UmaTestUtil.assert_(registerStatus);
	return registerStatus;
}
 
Example #29
Source File: OpenIDRequestObjectWithRSAlgEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Parameters({ "registerPath", "redirectUris", "clientJwksUri" })
@Test
public void requestParameterMethodRS512Step1(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.RS512);
		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("requestParameterMethodRS512Step1", response, entity);

	ResponseAsserter responseAsserter = ResponseAsserter.of(response.getStatus(), entity);
	responseAsserter.assertRegisterResponse();
	clientId3 = responseAsserter.getJson().getJson().getString(RegisterResponseParam.CLIENT_ID.toString());
}
 
Example #30
Source File: ClientInfoRestWebServiceEmbeddedTest.java    From oxAuth with MIT License 5 votes vote down vote up
@Parameters({"clientInfoPath"})
@Test
public void requestClientInfoInvalidToken(final String clientInfoPath) throws Exception {
    Builder request = ResteasyClientBuilder.newClient().target(url.toString() + clientInfoPath).request();

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

    ClientInfoRequest clientInfoRequest = new ClientInfoRequest("INVALID-TOKEN");
    clientInfoRequest.setAuthorizationMethod(AuthorizationMethod.FORM_ENCODED_BODY_PARAMETER);

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

    showResponse("requestClientInfoInvalidToken", 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);
    }
}