@Override public TokenResult refreshAccessToken(final String refreshToken) { refreshTokenProperties.put(OAuth2Parameters.REFRESH_TOKEN, refreshToken); final Form form = new Form(); for (final Map.Entry<String, String> entry : refreshTokenProperties.entrySet()) { form.param(entry.getKey(), entry.getValue()); } final Response response = client.target(refreshTokenUri) .request(MediaType.APPLICATION_JSON_TYPE) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE)); if (response.getStatus() != 200) { throw new ProcessingException(LocalizationMessages.ERROR_FLOW_REQUEST_REFRESH_TOKEN(response.getStatus())); } this.tokenResult = response.readEntity(TokenResult.class); return tokenResult; }
public String start() { final Response response = addProperties(client.target(requestTokenUri).request()) .post(null); if (response.getStatus() != 200) { throw new RuntimeException(LocalizationMessages.ERROR_REQUEST_REQUEST_TOKEN(response.getStatus())); } final MultivaluedMap<String, String> formParams = response.readEntity(Form.class).asMap(); parameters.token(formParams.getFirst(OAuth1Parameters.TOKEN)); secrets.tokenSecret(formParams.getFirst(OAuth1Parameters.TOKEN_SECRET)); return UriBuilder.fromUri(authorizationUri).queryParam(OAuth1Parameters.TOKEN, parameters.getToken()) .build().toString(); }
Form form = new Form(); form.add("x", "foo"); form.add("y", "bar"); ClientResource resource = new ClientResource("http://localhost:8080/someresource"); Response response = resource.post(form.getWebRepresentation()); if (response.getStatus().isSuccess()) { System.out.println("Success! " + response.getStatus()); System.out.println(response.getEntity().getText()); } else { System.out.println("ERROR! " + response.getStatus()); System.out.println(response.getEntity().getText()); }
Form form = new Form(); form.add("x", "foo"); form.add("y", "bar"); Client client = ClientBuilder.newClient(); WebTarget resource = client.target("http://localhost:8080/someresource"); Builder request = resource.request(); request.accept(MediaType.APPLICATION_JSON); Response response = request.get(); if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { System.out.println("Success! " + response.getStatus()); System.out.println(response.getEntity()); } else { System.out.println("ERROR! " + response.getStatus()); System.out.println(response.getEntity()); }
@org.junit.Test public void testJWTBadAudienceRestriction() throws Exception { URL busFile = AuthorizationGrantNegativeTest.class.getResource("client.xml"); String address = "https://localhost:" + port + "/services/"; WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(), "alice", "security", busFile.toString()); // Create the JWT Token String token = OAuth2TestUtils.createToken("DoubleItSTSIssuer", "consumer-id", "https://localhost:" + port + "/services/badtoken", true, true); // Get Access Token client.type("application/x-www-form-urlencoded").accept("application/json"); client.path("token"); Form form = new Form(); form.param("grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"); form.param("assertion", token); form.param("client_id", "consumer-id"); Response response = client.post(form); try { response.readEntity(ClientAccessToken.class); fail("Failure expected on a bad audience restriction"); } catch (Exception ex) { // expected } }
public AccessToken oauthLogin(String hostUrl, String username, String email, String password) throws GitLabApiException,IOException { if ((username == null || username.trim().length() == 0) && (email == null || email.trim().length() == 0)) { throw new IllegalArgumentException("both username and email cannot be empty or null"); } Form formData = new Form(); addFormParam(formData, "email", email, false); addFormParam(formData, "password", password, true); addFormParam(formData, "username", username, false); addFormParam(formData,"grant_type","password"); StringBuilder url = new StringBuilder(); url.append(hostUrl.endsWith("/") ? hostUrl.replaceAll("/$", "") : hostUrl); url.append("/oauth/token"); Response response = post(Response.Status.OK,formData,new URL(url.toString())); return (response.readEntity(AccessToken.class)); } }
WebClient client = WebClient.create(address, OAuth2TestUtils.setupProviders(), "alice", "security", busFile.toString()); WebClient.getConfig(client).getRequestContext().put( org.apache.cxf.message.Message.MAINTAIN_SESSION, Boolean.TRUE); client.type("application/json").accept("application/json"); client.query("client_id", "consumer-id"); client.query("redirect_uri", "http://www.blah.apache.org"); Response response = client.get(); OAuthAuthorizationData authzData = response.readEntity(OAuthAuthorizationData.class); client.type("application/x-www-form-urlencoded"); Form form = new Form(); form.param("session_authenticity_token", authzData.getAuthenticityToken()); form.param("client_id", authzData.getClientId()); form.param("redirect_uri", authzData.getRedirectUri()); form.param("oauthDecision", "allow"); response = client.post(form); String location = response.getHeaderString("Location"); String accessToken = OAuth2TestUtils.getSubstring(location, "access_token"); assertNotNull(accessToken);
@Test public void testAddOneBookWithValidation() { final String id = UUID.randomUUID().toString(); Response r = createWebClient("/rest/v2/bookstore/books").post( new Form() .param("id", id)); assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), r.getStatus()); }
public void registerClientApplication() throws Exception { WebClient rs = WebClient.create("http://localhost:" + port + "/services/oauth/registerProvider"); WebClient.getConfig(rs).getHttpConduit().getClient().setReceiveTimeout(10000000L); rs.form(new Form().param("appName", "Restaurant Reservations") .param("appURI", "http://localhost:" + port + "/services/reservations/reserve") .param("appRedirectURI", "http://localhost:" + port + "/services/reservations/reserve/complete") ); }
private Form switchUrlEncoding(final ContainerRequest request, final Form otherForm) { final Set<Map.Entry<String, List<String>>> entries = otherForm.asMap().entrySet(); MultivaluedMap<String, String> formMap = new NullableMultivaluedHashMap<>(); for (Map.Entry<String, List<String>> entry : entries) { final String charsetName = ReaderWriter.getCharset(MediaType.valueOf( request.getHeaderString(HttpHeaders.CONTENT_TYPE))).name(); String key; try { key = decode ? URLDecoder.decode(entry.getKey(), charsetName) : URLEncoder.encode(entry.getKey(), charsetName); for (String value : entry.getValue()) { if (value != null) { formMap.add(key, decode ? URLDecoder.decode(value, charsetName) : URLEncoder.encode(value, charsetName)); } else { formMap.add(key, null); } } } catch (UnsupportedEncodingException uee) { throw new ProcessingException(LocalizationMessages.ERROR_UNSUPPORTED_ENCODING(charsetName, extractor.getName()), uee); } } return new Form(formMap); }
String time = DateUtil.formatDate(statistics.getCaptureTime()); Form form = new Form(); form.param("version", Context.getAppVersion()); form.param("captureTime", time); form.param("activeUsers", String.valueOf(statistics.getActiveUsers())); form.param("activeDevices", String.valueOf(statistics.getActiveDevices())); form.param("requests", String.valueOf(statistics.getRequests())); form.param("messagesReceived", String.valueOf(statistics.getMessagesReceived())); form.param("messagesStored", String.valueOf(statistics.getMessagesStored())); form.param("mailSent", String.valueOf(statistics.getMailSent())); form.param("smsSent", String.valueOf(statistics.getSmsSent())); form.param("geocoderRequests", String.valueOf(statistics.getGeocoderRequests())); form.param("geolocationRequests", String.valueOf(statistics.getGeolocationRequests())); Context.getClient().target(url).request().async().post(Entity.form(form));
private ClientAccessToken getAccessTokenUsingCode(String tokenEndpoint, String code, String clientId, String clientSecret, String redirectURI) { // Here we need to get the AccessToken using the authorization code List<Object> providers = new ArrayList<>(); providers.add(new OAuthJSONProvider()); WebClient client = WebClient.create(tokenEndpoint, providers, "cxf-tls.xml"); ClientConfiguration config = WebClient.getConfig(client); if (LOG.isDebugEnabled()) { config.getOutInterceptors().add(new LoggingOutInterceptor()); config.getInInterceptors().add(new LoggingInInterceptor()); } client.type("application/x-www-form-urlencoded"); client.accept("application/json"); Form form = new Form(); form.param("grant_type", "authorization_code"); form.param("code", code); form.param("client_id", clientId); form.param("redirect_uri", redirectURI); form.param("client_secret", clientSecret); Response response = client.post(form); return response.readEntity(ClientAccessToken.class); }
@Test public void testEchoForm() throws Exception { String address = "http://localhost:" + PORT + "/bookstore/form"; WebClient wc = WebClient.create(address, Collections.singletonList(new LoggingFeature())); Form formOut = new Form().param("a", "aValue").param("b", "b value") .param("c%", "cValue"); Form formIn = wc.post(formOut, Form.class); assertEquals(3, formIn.asMap().size()); assertEquals("aValue", formIn.asMap().getFirst("a")); assertEquals("b value", formIn.asMap().getFirst("b")); assertEquals("cValue", formIn.asMap().getFirst("c%")); }
@Test public void testInterceptorInvokedOnFormAndFormParamMatchesFormValue() throws Exception { Client client = ClientBuilder.newClient(); String uri = "http://localhost:" + PORT + "/form"; Form f = new Form("value", "ORIGINAL"); Response r = client.target(uri) .request(MediaType.APPLICATION_FORM_URLENCODED) .post(Entity.form(f)); Assert.assertEquals("MODIFIED", r.getHeaderString("FromForm")); Assert.assertEquals("MODIFIED", r.getHeaderString("FromFormParam")); } }
@Test @Ignore("Spring Security 3 does not preserve POSTed form parameters as HTTPServletRequest parameters") public void testBookFromHttpRequestParameters() throws Exception { WebClient wc = WebClient.create("http://localhost:" + PORT + "/bookstorestorage/bookforms2", "foo", "bar", null); WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(100000000L); wc.accept("application/xml"); Response r = wc.form(new Form().param("name", "CXF Rocks").param("id", "123")); Book b = readBook((InputStream)r.getEntity()); assertEquals("CXF Rocks", b.getName()); assertEquals(123L, b.getId()); }