public AccessToken submit() throws IOException { Form form = new Form(); form.param("assertion", assertion); form.param("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"); Entity<Form> entity = Entity.form(form); Response response = client.target(EINSTEIN_VISION_URL + "/v1/oauth2/token") .request() .post(entity); if (!isSuccessful(response)) { throw new IOException("Error occurred while fetching Access Token " + response); } return readResponseAs(response, AccessToken.class); }
@Test public void testEngineWithInjectedClientPost() { final HttpClient httpClient = Vertx.vertx().createHttpClient(httpClientOptions); final Client client = new ResteasyClientBuilder().httpEngine(new VertxClientEngine(httpClient)) .register(GsonMessageBodyHandler.class).build(); final Form xform = new Form(); xform.param("userName", "ca1\\\\meowmix"); xform.param("password", "mingnamulan"); xform.param("state", "authenticate"); xform.param("style", "xml"); xform.param("xsl", "none"); final JsonObject arsString = client.target("https://httpbin.org/post").request() .post(Entity.form(xform), JsonObject.class); assertEquals("xml", arsString.getAsJsonObject("form").get("style").getAsString()); }
@Override public Form asForm() { final MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); for (final Part part : values.values()) { if (part.getSubmittedFileName() != null) { continue; } try { map.add(part.getName(), IOUtils.toString(part.getInputStream(), StandardCharsets.UTF_8)); } catch (final IOException ex) { LOG.error(ex.getMessage(), ex); } } return new Form(map); }
public static InputStream serializeMultipartForm(final Form form) { final String boundary = "------Boundary" + UUID.randomUUID().toString(); final StringBuilder b = new StringBuilder(); final MultivaluedMap<String, String> map = form.asMap(); for (final Entry<String, List<String>> entry : map.entrySet()) { for (final String value : entry.getValue()) { b.append(boundary); b.append("\nContent-Disposition: form-data; name=\""); b.append(entry.getKey()); b.append("\"\n\n"); b.append(value); b.append("\n"); } } b.append(boundary); return new ByteArrayInputStream(b.toString().getBytes(StandardCharsets.UTF_8)); }
private InputStream getEntityInputStream() { if (entity == null || entity.getEntity() == null) { return null; } final Object obj = entity.getEntity(); if (obj instanceof InputStream) { return (InputStream) obj; } if (obj instanceof String) { return IOUtils.toInputStream((String) obj, StandardCharsets.UTF_8); } if (obj instanceof Form) { if (headers.containsKey(HttpHeaders.CONTENT_TYPE) && headers.getFirst(HttpHeaders.CONTENT_TYPE).equals(MediaType.MULTIPART_FORM_DATA)) { return MultipartUtils.serializeMultipartForm((Form) obj); } else { return IOUtils.toInputStream(UrlUtils.urlEncodeMultivaluedParams(((Form) obj).asMap()), StandardCharsets.UTF_8); } } throw new UnsupportedOperationException("Unknown entity type: " + obj.getClass()); }
@Test public void testNewOwner() { final Response r1 = target("/owners/new").request().get(); assertEquals(200, r1.getStatus()); assertEquals("newowner", ((View) r1.getEntity()).getTemplateName()); final Form form = new Form() .param("name", "Barack Obama") .param("address", "1600 Penn Ave") .param("city", "Washington DC") .param("telephone", "800-555-5555"); final Response r2 = target("/owners/new").request().post(Entity.form(form)); assertNotNull(r2); assertEquals(303, r2.getStatus()); assertNotNull(r2.getHeaderString("Location")); final Response r3 = target(r2.getHeaderString("Location")).request().get(); assertNotNull(r3); assertEquals(200, r3.getStatus()); final View view = (View) r3.getEntity(); final Owner owner = (Owner) view.getModel().get("owner"); assertEquals("Barack Obama", owner.getName()); }
public <T> T generateClient(Class<T> resource) { Client clientToUse = client != null ? client : ClientBuilder.newClient(); MultivaluedMap<String, Object> headerArg = new MultivaluedHashMap<>(headers); WebTarget webTarget = clientToUse.target(uri); if (apiPath != null) { webTarget = webTarget.path(apiPath); } if(throwExceptionForErrors) { webTarget.register(ClientErrorResponseFilter.class); } webTarget.register(RequestIdClientFilter.class); webTarget.register(ClientNameFilter.class); if (logging) { webTarget.register(ClientLogFilter.class); } return WebResourceFactory.newResource(resource, webTarget, false, headerArg, cookies, new Form()); }
@Test public void testAuthWithUser() throws MalformedURLException { LOG.log(Level.INFO, "base url @{0}", base); //get an authentication final WebTarget targetAuth = client.target(URI.create(new URL(base, "api/auth/login").toExternalForm())); String token; try (Response resAuth = targetAuth.request().post(form(new Form().param("username", "user").param("password", "password")))) { assertEquals(200, resAuth.getStatus()); token = (String) resAuth.getHeaders().getFirst(HttpHeaders.AUTHORIZATION); LOG.log(Level.INFO, "resAuth.getHeaders().getFirst(\"Bearer\"):{0}", token); assertTrue(token != null); } client.register(new JwtTokenAuthentication(token.substring(AUTHORIZATION_PREFIX.length()))); final WebTarget targetUser = client.target(URI.create(new URL(base, "api/auth/userinfo").toExternalForm())); try (Response resUser = targetUser.request().accept(MediaType.APPLICATION_JSON_TYPE).get()) { assertEquals(200, resUser.getStatus()); final UserInfo userInfo = resUser.readEntity(UserInfo.class); LOG.log(Level.INFO, "get user info @{0}", userInfo); assertTrue("user".equals(userInfo.getName())); } }
@Before public void setup() throws MalformedURLException { client = ClientBuilder.newClient(); client.register(PostNotFoundExceptionMapper.class); client.register(CommentNotFoundExceptionMapper.class); final WebTarget targetAuth = client.target(URI.create(new URL(base, "api/auth/login").toExternalForm())); final Response resAuthGetAll = targetAuth.request() .accept(MediaType.APPLICATION_JSON) .post(form(new Form("username", "user").param("password", "password"))); assertEquals(200, resAuthGetAll.getStatus()); String token = resAuthGetAll.getHeaderString(HttpHeaders.AUTHORIZATION); client.register(new JwtTokenAuthentication(token.substring(Constants.AUTHORIZATION_PREFIX.length()))); }
String doPostOauth2(String api, Prameters prams) { WebClient wc = WebClient.create(api); Form form = new Form(); String[] keys = prams.keys; for(int i = 0 ; i < keys.length ; i ++){ form.param(keys[i], prams.value(i).toString()); } Response resp = wc.form(form); String result = ""; try { result = IOUtils.toString((InputStream) resp.getEntity()); } catch (IOException e) { throw new ParseResultException(e); } handleResponse(resp, wc); return result; }
@Test public void grantsAccessToResourcesForm() throws Exception { setup(ConfigOverride.config("pac4j.globalFilters[0].clients", DirectFormClient.class.getSimpleName())); // username == password Form form = new Form(); form.param("username", "rosebud"); form.param("password", "rosebud"); final String dogName = client.target(getUrlPrefix() + "/dogs/pierre") .request(MediaType.APPLICATION_JSON) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class); assertThat(dogName).isEqualTo("pierre"); }
@Test(groups = {"Subscriptions:POST"}) public void subscriptionOperationsTest() { String subscription="http://new_test.com/rss"; //subscribe Form form = new Form(); form.param("rss", subscription); Response response = target(PATH + username + "/"+ email + "/subscribe").request().post(Entity.form(form), Response.class); assertEquals("Adding new subscription failed", 200, response.getStatus()); //unsubscribe Form form_update = new Form(); form_update.param("rss", subscription); response = target(PATH + username + "/" + email + "/unsubscribe").request().post(Entity.form(form_update), Response.class); assertEquals("Deleting subscription failed", 200, response.getStatus()); }
public void registerMessagingServiceCallback(String consumerKey, String callback) { WebTarget target = ClientBuilder.newClient().target(MessagingServiceCallbackRegistrationURL); Invocation.Builder builder = target.request(); String base64Credentials = new String(Base64.encodeBytes("admin:admin".getBytes())); builder.header("Authorization", "Basic " + base64Credentials); Form form = new Form("consumer_id", consumerKey); form.param("callback_uri", callback); Response response = null; try { response = builder.post(Entity.form(form)); if (HttpResponseCodes.SC_OK != response.getStatus()) { throw new RuntimeException("Callback Registration failed"); } } catch (Exception ex) { throw new RuntimeException("Callback Registration failed"); } finally { response.close(); } }
@SuppressWarnings("unchecked") @Test public void testGetForSiteListDownloadError() throws ClientException { Mockito.when(connectionmock.post(Mockito.anyString(), Mockito.any(Form.class))) .thenReturn(response); //Mockito.when(response.readEntity(Mockito.any(Class.class))).thenReturn(LOGIN); Mockito.when(connectionmock.getReportData(Mockito.anyString(), Mockito.any(T1User.class))).thenReturn(response); Mockito.when(response.getStatus()).thenReturn(100); Mockito.when(response.readEntity(Mockito.any(Class.class))).thenReturn(SITE_LIST_DATA_ERROR); QueryCriteria query = QueryCriteria.builder().setCollection("site_lists").setEntity(9538) .setDownloadSiteList(true).setPageLimit(0).build(); BufferedReader reader = null; try { t1.authenticate("abc", "xyz", "adfadslfadkfakjf"); reader = t1.getSiteListData(query); } catch (ClientException | ParseException e) { assertNull(reader); } }
@SuppressWarnings("unchecked") @Test public void testAgencyGetAllWithMocks() throws ClientException, ParseException { Mockito.when(connectionmock.post(Mockito.anyString(), Mockito.any(Form.class))) .thenReturn(response); Mockito.when(response.readEntity(Mockito.any(Class.class))).thenReturn(LOGIN); Mockito.when(connectionmock.get(Mockito.anyString(), Mockito.any(T1User.class))).thenReturn(GET_ALL_RESPONSE_1,GET_ALL_RESPONSE_2,GET_ALL_RESPONSE_3); QueryCriteria query = QueryCriteria.builder().setCollection("agencies").setGetAll(true).build(); JsonResponse<?> jsonresponse = null; try { t1.authenticate("abc", "xyz", "adfadslfadkfakjf"); jsonresponse = t1.get(query); Mockito.verify(connectionmock, times(1)).post(Mockito.anyString(), Mockito.any(Form.class)); } catch (ClientException | ParseException e) { e.printStackTrace(); } assertNotNull(jsonresponse); assertNotNull(jsonresponse.getData()); }
public String registerMessagingService(String consumerKey) throws Exception { WebTarget target = ClientBuilder.newClient().target(ConsumerRegistrationURL); Invocation.Builder builder = target.request(); builder.header("Authorization", "OpenId " + SubscriberOpenIdIdentifier); //request.formParameter(OAuth.OAUTH_CONSUMER_KEY, consumerKey); Response response = builder.post(Entity.form(new Form(OAuth.OAUTH_CONSUMER_KEY, consumerKey))); if (HttpResponseCodes.SC_OK != response.getStatus()) { throw new RuntimeException("Registration failed"); } // check that we got all tokens Map<String, String> tokens = OAuth.newMap(OAuth.decodeForm(response.readEntity(String.class))); String secret = tokens.get("xoauth_consumer_secret"); if (secret == null) { throw new RuntimeException("No secret available"); } return secret; }
public String registerMessagingService(String consumerKey) throws Exception { WebTarget target = ClientBuilder.newClient().target(ConsumerRegistrationURL); String base64Credentials = new String(Base64.encodeBytes("admin:admin".getBytes())); Invocation.Builder builder = target.request(); builder.header("Authorization", "Basic " + base64Credentials); Entity<Form> formEntity = Entity.form(new Form(OAuth.OAUTH_CONSUMER_KEY, consumerKey)); Response response = null; try { response = builder.post(formEntity); if (HttpResponseCodes.SC_OK != response.getStatus()) { throw new RuntimeException("Registration failed"); } // check that we got all tokens Map<String, String> tokens = OAuth.newMap(OAuth.decodeForm(response.readEntity(String.class))); String secret = tokens.get("xoauth_consumer_secret"); if (secret == null) { throw new RuntimeException("No secret available"); } return secret; } finally { response.close(); } }
@Test @SuppressWarnings("unchecked") public void testGetWithCampaignCBS() throws ClientException, ParseException { Mockito.when(connectionmock.post(Mockito.anyString(), Mockito.any(Form.class))) .thenReturn(response); Mockito.when(response.readEntity(Mockito.any(Class.class))).thenReturn(LOGIN); Mockito.when(connectionmock.get(Mockito.anyString(), Mockito.any(T1User.class))).thenReturn( "{\"data\":[{\"entity_type\":\"campaign_custom_brain_selection\",\"name\":\"CampaignCustomBrainSelections#143213\",\"id\":143213}]," +"\"meta\":{\"etag\":\"528884ebf3a2df890f76e184e732f748d8dbc27b\",\"count\":1,\"called_on\":\"2017-07-24T11:28:10+0000\",\"status\":\"ok\",\"offset\":0,\"total_count\":1}}"); QueryCriteria query = QueryCriteria.builder().setCollection("campaigns").setEntity(338158).setChild("custom_brain_selections").build(); JsonResponse<?> jsonresponse = null; try { t1.authenticate("abc", "xyz", "adfadslfadkfakjf"); jsonresponse = t1.get(query); Mockito.verify(connectionmock).get(Mockito.anyString(), Mockito.any(T1User.class)); Mockito.verify(connectionmock, times(1)).post(Mockito.anyString(), Mockito.any(Form.class)); } catch (ClientException | ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } assertNotNull(jsonresponse); }
public String obtainAccessToken(String username, String password) { Form form = new Form(); form.param("grant_type", "password"); form.param("username", username); form.param("password", password); form.param("client_id", deployment.getClientId()); String secret = deployment.getClientCredentials().get("secret").toString(); form.param("client_secret", secret); Client client = null; try { ClientBuilder clientBuilder = ClientBuilder.newBuilder(); SSLContext sslcontext = deployment.getSSLContext(); if(sslcontext != null) { client = clientBuilder.sslContext(sslcontext).hostnameVerifier(new AnyHostnameVerifier()).build(); } else { client = clientBuilder.build(); } String tokenURL = String.format("%s/auth/realms/%s/protocol/openid-connect/token", deployment.getAuthServerUrl(), deployment.getRealm()); WebTarget target = client.target(tokenURL); if(deployment.getDebug() > 0) target.register(new LoggingFilter()); String json = target.request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), String.class); AccessToken accessToken = JsonSerialization.readValue(json, AccessToken.class); return accessToken.getToken(); } catch (Exception e) { throw new RuntimeException("Failed to request token", e); } finally { if (client != null) { client.close(); } } }
Form getForm() { Form form = new Form(); for (Entry<String, String> pramEntry : parameters.entrySet()) { form.param(pramEntry.getKey(), pramEntry.getValue()); } return form; }
@Override public void filter( ClientRequestContext context ) throws IOException { if (debugLevel == RESTDebugLevel.NONE || debugLevel == RESTDebugLevel.TARGET_URI) { return; } MultivaluedMap<String, Object> reqHeaders = context.getHeaders(); StringBuilder requestMessage = new StringBuilder(); requestMessage.append("Sending the following request: \n"); if ( (debugLevel & RESTDebugLevel.HEADERS) == RESTDebugLevel.HEADERS) { requestMessage.append(context.getMethod() + " " + context.getUri() + " \n"); for (Entry<String, List<Object>> reqHeaderEntry : reqHeaders.entrySet()) { requestMessage.append(reqHeaderEntry.getKey() + ": " + Arrays.toString(reqHeaderEntry.getValue().toArray()) + " \n"); } } if ( (debugLevel & RESTDebugLevel.BODY) == RESTDebugLevel.BODY && context.hasEntity()) { //log request body Object entity = context.getEntity(); if (entity instanceof Form) { requestMessage.append("Body: " + ((Form) entity).asMap()); } else { requestMessage.append("Body: " + entity.toString()); } } log.info(requestMessage); }
@POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @ApiResponses(@ApiResponse(code = 401, message = "Unauthorized Response", response = ErrorResponse.class)) public Response json(final UsernamePassword usernamePassword, @HeaderParam(HttpHeaders.AUTHORIZATION) final String authorization) { if (!"password".equals(usernamePassword.getPassword())) { throw ErrorResponses.unauthorized(ErrorCodes.UNAUTHORIZED_CLIENT, "invalid username/password combination", "FORM"); } final JwtClaims claims = new JwtClaims(); claims.setSubject(usernamePassword.getUsername()); claims.setAudience(HttpAuthorizationHeaders.parseBasicAuthorization(authorization)[0]); final Form form = new Form(); form.param("grant_type", GrantTypes.JWT_ASSERTION); form.param("assertion", cryptoOps.sign(claims)); return Response.ok(client.target(authorizationEndpoint).request(MediaType.APPLICATION_JSON_TYPE) .header(HttpHeaders.AUTHORIZATION, authorization) .post(Entity.form(form), OAuthTokenResponse.class)) .build(); }
@Test public void testEngineWithInjectedClientPost2() { final ResteasyDeployment deployment = new ResteasyDeployment(); deployment.start(); final ResteasyProviderFactory providerFactory = deployment.getProviderFactory(); final HttpClient httpClient = Vertx.vertx().createHttpClient(httpClientOptions); final Client client = new ResteasyClientBuilder() .providerFactory(providerFactory) .httpEngine(new VertxClientEngine(httpClient)) .register(GsonMessageBodyHandler.class) .build(); final Form xform = new Form(); xform.param("userName", "ca1\\\\meowmix"); xform.param("password", "mingnamulan"); xform.param("state", "authenticate"); xform.param("style", "xml"); xform.param("xsl", "none"); final Response response = client.target("https://httpbin.org/post").request(MediaType.APPLICATION_JSON) .post(Entity.form(xform), Response.class); assertFalse(response.getStringHeaders().isEmpty()); System.out.println(response.getStringHeaders()); assertFalse(response.getHeaders().isEmpty()); assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getMediaType()); assertTrue(response.hasEntity()); final JsonObject arsString = response.readEntity(JsonObject.class); assertEquals("xml", arsString.getAsJsonObject("form").get("style").getAsString()); }
@Test public void testResetPasswordNotFound() throws IOException { final String code = "does-not-exist"; final Form form = new Form(); form.param("newPassword", "my-new-password"); form.param("confirmNewPassword", "my-new-password"); final Response r = target("/resetpassword/" + code).request().post(Entity.form(form)); assertNotNull(r); assertEquals(404, r.getStatus()); assertTrue(r.getCookies().isEmpty()); }
@Test public void testPublic() { final Form form = new Form(); final Response r = target("/public_form").request().post(Entity.form(form)); assertNotNull(r); assertEquals(200, r.getStatus()); }
@Test public void testPrivateFormWithoutUser() { final Form form = new Form(); final Response r = target("/private_form").request().post(Entity.form(form)); assertNotNull(r); assertEquals(401, r.getStatus()); }
@Test public void testPrivateFormWithoutCsrf() { final Form form = new Form(); final Response r = target("/private_form").request().cookie(cookie).post(Entity.form(form)); assertNotNull(r); assertEquals(400, r.getStatus()); }
@Test public void testPrivateFormWithCsrf() { final Form form = new Form(); form.param("csrf", cookie.getValue()); final Response r = target("/private_form").request().cookie(cookie).post(Entity.form(form)); assertNotNull(r); assertEquals(200, r.getStatus()); }
@Test public void testFormParam() { final Entity<Form> form = Entity.form(new Form("test", "Hello")); assertEquals( "Hello", target("/formtest").request().post(form, String.class)); }
@Test public void testFormParamDefaultValue() { final Entity<Form> form = Entity.form(new Form()); assertEquals( "foo", target("/defval").request().post(form, String.class)); }
@Test public void testWholeForm() { final Entity<Form> form = Entity.form(new Form("test", "Hello")); assertEquals( "Hello", target("/wholeform").request().post(form, String.class)); }
@Test public void testFormParam() { final Form form = new Form(); form.param("a", "hello"); final InjectedResource r = target("/inject/test").request().post(Entity.form(form), InjectedResource.class); assertEquals("hello", r.form); }