List of usage examples for org.apache.http.impl.client BasicCookieStore BasicCookieStore
public BasicCookieStore()
From source file:edu.mit.scratch.ScratchCloudSession.java
public String get(final String key) throws ScratchProjectException { try {//from w w w. j av a 2 s. c o m final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build(); final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en"); lang.setDomain(".scratch.mit.edu"); lang.setPath("/"); cookieStore.addCookie(lang); final CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(globalConfig) .setUserAgent(Scratch.USER_AGENT).setDefaultCookieStore(cookieStore).build(); CloseableHttpResponse resp; final HttpUriRequest update = RequestBuilder.get() .setUri("https://scratch.mit.edu/varserver/" + this.getProjectID()) .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*//*;q=0.8") .addHeader("Referer", "https://scratch.mit.edu").addHeader("Origin", "https://scratch.mit.edu") .addHeader("Accept-Encoding", "gzip, deflate, sdch") .addHeader("Accept-Language", "en-US,en;q=0.8").addHeader("Content-Type", "application/json") .addHeader("X-Requested-With", "XMLHttpRequest").build(); try { resp = httpClient.execute(update); } catch (final IOException e) { e.printStackTrace(); throw new ScratchProjectException(); } BufferedReader rd; try { rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); } catch (UnsupportedOperationException | IOException e) { e.printStackTrace(); throw new ScratchProjectException(); } final StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) result.append(line); final JSONObject jsonOBJ = new JSONObject(result.toString().trim()); final Iterator<?> keys = ((JSONArray) jsonOBJ.get("variables")).iterator(); while (keys.hasNext()) { final JSONObject o = new JSONObject(StringEscapeUtils.unescapeJson("" + keys.next())); final String k = o.get("name") + ""; if (k.equals(key)) return o.get("value") + ""; } } catch (final Exception e) { e.printStackTrace(); throw new ScratchProjectException(); } return null; }
From source file:MinimalServerTest.java
License:asdf
public void testStartOfSession() throws Exception { //Create client HttpClient client = new DefaultHttpClient(); HttpPost mockRequest = new HttpPost("http://localhost:5555/login"); CookieStore cookieStore = new BasicCookieStore(); HttpContext httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); mockRequest.setHeader("Content-type", "application/x-www-form-urlencoded"); //Add parameters List<NameValuePair> urlParameters = new ArrayList<>(); urlParameters.add(new BasicNameValuePair("email", "test")); urlParameters.add(new BasicNameValuePair("deviceUID", "BD655C43-3A73-4DFB-AA1F-074A4F0B0DCE")); mockRequest.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8")); //Execute the request HttpResponse mockResponse = client.execute(mockRequest, httpContext); //Test if normal login is successful BufferedReader rd = new BufferedReader(new InputStreamReader(mockResponse.getEntity().getContent())); rd.close();//w ww . j ava 2 s . c om URL newURL = new URL("http://127.0.0.1:5555/start"); final Request request = Request.Post(newURL.toURI()); ExecutorService executor = Executors.newFixedThreadPool(1); Async async = Async.newInstance().use(executor); Future<Content> future = async.execute(request, new FutureCallback<Content>() { @Override public void failed(final Exception e) { e.printStackTrace(); } @Override public void completed(final Content content) { System.out.println("Done"); } @Override public void cancelled() { } }); server.startSession(); String asyncResponse = future.get().asString(); JSONObject jsonTest = new JSONObject(); // "status": "1", //0 if the app should keep waiting, 1 for success, 2 if the votong session has fininshed // "sessionType": "normal", //alternatively Yes/No or winner // "rangeBottom": "0", // "rangeTop": "15", // "description": "image discription here", // "comments": "True", //True if comments are allowed, False if not // "imgPath": "path/to/image.jpg" //the path where the image resides on the server jsonTest.put("status", "1"); jsonTest.put("sessionType", "normal"); jsonTest.put("rangeBottom", 0); jsonTest.put("rangeTop", 10); jsonTest.put("description", "helo"); jsonTest.put("comments", "true"); jsonTest.put("imgPath", "temp/1.jpg"); assertEquals("Testing if login was correctly failed due to incorrect username", jsonTest.toString(), asyncResponse); }
From source file:org.cloudfoundry.identity.uaa.integration.feature.AutologinIT.java
@Test public void testSimpleAutologinFlow() throws Exception { HttpHeaders headers = getAppBasicAuthHttpHeaders(); LinkedMultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>(); requestBody.add("username", testAccounts.getUserName()); requestBody.add("password", testAccounts.getPassword()); //generate an autologin code with our credentials ResponseEntity<Map> autologinResponseEntity = restOperations.exchange(baseUrl + "/autologin", HttpMethod.POST, new HttpEntity<>(requestBody.toSingleValueMap(), headers), Map.class); String autologinCode = (String) autologinResponseEntity.getBody().get("code"); //start the authorization flow - this will issue a login event //by using the autologin code String authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize") .queryParam("redirect_uri", appUrl).queryParam("response_type", "code") .queryParam("client_id", "app").queryParam("code", autologinCode).build().toUriString(); //rest template that does NOT follow redirects RestTemplate template = new RestTemplate(new DefaultIntegrationTestConfig.HttpClientFactory()); headers.remove("Authorization"); headers.add(HttpHeaders.ACCEPT, MediaType.TEXT_HTML_VALUE); ResponseEntity<String> authorizeResponse = template.exchange(authorizeUrl, HttpMethod.GET, new HttpEntity<>(new HashMap<String, String>(), headers), String.class); //we are now logged in. retrieve the JSESSIONID List<String> cookies = authorizeResponse.getHeaders().get("Set-Cookie"); int cookiesAdded = 0; headers = getAppBasicAuthHttpHeaders(); for (String cookie : cookies) { if (cookie.startsWith("X-Uaa-Csrf=") || cookie.startsWith("JSESSIONID=")) { headers.add("Cookie", cookie); cookiesAdded++;//from ww w .j ava2 s . c om } } assertEquals(2, cookiesAdded); //if we receive a 200, then we must approve our scopes if (HttpStatus.OK == authorizeResponse.getStatusCode()) { authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize") .queryParam("user_oauth_approval", "true") .queryParam(DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(authorizeResponse.getBody())) .build().toUriString(); authorizeResponse = template.exchange(authorizeUrl, HttpMethod.POST, new HttpEntity<>(new HashMap<String, String>(), headers), String.class); } //approval is complete, we receive a token code back assertEquals(HttpStatus.FOUND, authorizeResponse.getStatusCode()); List<String> location = authorizeResponse.getHeaders().get("Location"); assertEquals(1, location.size()); String newCode = location.get(0).substring(location.get(0).indexOf("code=") + 5); //request a token using our code String tokenUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/token").build().toUriString(); MultiValueMap<String, String> tokenParams = new LinkedMultiValueMap<>(); tokenParams.add("response_type", "token"); tokenParams.add("grant_type", GRANT_TYPE_AUTHORIZATION_CODE); tokenParams.add("code", newCode); tokenParams.add("redirect_uri", appUrl); headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE); headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE); RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>(tokenParams, headers, HttpMethod.POST, new URI(tokenUrl)); ResponseEntity<Map> tokenResponse = template.exchange(requestEntity, Map.class); assertEquals(HttpStatus.OK, tokenResponse.getStatusCode()); //here we must reset our state. we do that by following the logout flow. headers.clear(); BasicCookieStore cookieStore = new BasicCookieStore(); ResponseEntity<String> loginResponse = template.exchange(baseUrl + "/login", HttpMethod.GET, new HttpEntity<>(null, getHeaders(cookieStore)), String.class); setCookiesFromResponse(cookieStore, loginResponse); String csrf = IntegrationTestUtils.extractCookieCsrf(loginResponse.getBody()); requestBody.add(DEFAULT_CSRF_COOKIE_NAME, csrf); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); loginResponse = restOperations.exchange(baseUrl + "/login.do", HttpMethod.POST, new HttpEntity<>(requestBody, getHeaders(cookieStore)), String.class); cookies = loginResponse.getHeaders().get("Set-Cookie"); assertThat(cookies, hasItem(startsWith("JSESSIONID"))); assertThat(cookies, hasItem(startsWith("X-Uaa-Csrf"))); if (IdentityZoneHolder.get().getConfig().isAccountChooserEnabled()) { assertThat(cookies, hasItem(startsWith("Saved-Account-"))); } assertThat(cookies, hasItem(startsWith("Current-User"))); cookieStore.clear(); setCookiesFromResponse(cookieStore, loginResponse); headers.add(HttpHeaders.ACCEPT, MediaType.TEXT_HTML_VALUE); ResponseEntity<String> profilePage = restOperations.exchange(baseUrl + "/profile", HttpMethod.GET, new HttpEntity<>(null, getHeaders(cookieStore)), String.class); setCookiesFromResponse(cookieStore, profilePage); String revokeApprovalsUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/profile").build() .toUriString(); requestBody.clear(); requestBody.add("clientId", "app"); requestBody.add("delete", ""); requestBody.add(DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(profilePage.getBody())); ResponseEntity<Void> revokeResponse = template.exchange(revokeApprovalsUrl, HttpMethod.POST, new HttpEntity<>(requestBody, getHeaders(cookieStore)), Void.class); assertEquals(HttpStatus.FOUND, revokeResponse.getStatusCode()); }
From source file:io.mandrel.requests.http.ApacheHttpRequester.java
public HttpContext prepareContext(Spider spider) { CookieStore store = new BasicCookieStore(); if (cookies() != null) cookies().forEach(cookie -> { BasicClientCookie theCookie = new BasicClientCookie(cookie.name(), cookie.value()); theCookie.setDomain(cookie.domain()); theCookie.setPath(cookie.path()); theCookie.setExpiryDate(new Date(cookie.expires())); theCookie.setSecure(cookie.secure()); store.addCookie(theCookie);// w w w .ja v a 2s. com }); HttpContext localContext = new BasicHttpContext(); localContext.setAttribute(HttpClientContext.COOKIE_STORE, store); return localContext; }
From source file:ddf.security.samlp.impl.LogoutMessageImpl.java
@Override public String sendSamlLogoutRequest(LogoutRequest request, String targetUri, boolean isSoap, @Nullable Cookie cookie) throws IOException, WSSecurityException { XMLObject xmlObject = isSoap ? SamlProtocol.createSoapMessage(request) : request; Element requestElement = getElementFromSaml(xmlObject); String requestMessage = DOM2Writer.nodeToString(requestElement); try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost post = new HttpPost(targetUri); post.addHeader("Cache-Control", "no-cache, no-store"); post.addHeader("Pragma", "no-cache"); post.addHeader("SOAPAction", SAML_SOAP_ACTION); post.addHeader("Content-Type", "application/soap+xml"); post.setEntity(new StringEntity(requestMessage, "utf-8")); ResponseHandler<String> responseHandler = new BasicResponseHandler(); BasicHttpContext context = new BasicHttpContext(); if (cookie != null) { BasicClientCookie basicClientCookie = new BasicClientCookie(cookie.getName(), cookie.getValue()); basicClientCookie.setDomain(cookie.getDomain()); basicClientCookie.setPath(cookie.getPath()); BasicCookieStore cookieStore = new BasicCookieStore(); cookieStore.addCookie(basicClientCookie); context.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore); }/*from w ww.j av a2 s. c o m*/ return httpClient.execute(post, responseHandler, context); } }
From source file:net.vexelon.mobileops.GLBClient.java
/** * Initialize Http Client//w w w . ja v a 2 s . c o m */ private void initHttpClient() { HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); params.setParameter(CoreProtocolPNames.USER_AGENT, UserAgentHelper.getRandomUserAgent()); //params.setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, HTTP.UTF_8); // Bugfix #1: The target server failed to respond params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); DefaultHttpClient client = new DefaultHttpClient(params); httpCookieStore = new BasicCookieStore(); client.setCookieStore(httpCookieStore); httpContext = new BasicHttpContext(); httpContext.setAttribute(ClientContext.COOKIE_STORE, httpCookieStore); // Bugfix #1: Adding retry handler to repeat failed requests HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= MAX_REQUEST_RETRIES) { return false; } if (exception instanceof NoHttpResponseException || exception instanceof ClientProtocolException) { return true; } return false; } }; client.setHttpRequestRetryHandler(retryHandler); // SSL HostnameVerifier verifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; try { SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", new PlainSocketFactory(), 80)); registry.register(new Scheme("https", new TrustAllSocketFactory(), 443)); SingleClientConnManager connMgr = new SingleClientConnManager(client.getParams(), registry); httpClient = new DefaultHttpClient(connMgr, client.getParams()); } catch (InvalidAlgorithmParameterException e) { // Log.e(Defs.LOG_TAG, "", e); // init without connection manager httpClient = new DefaultHttpClient(client.getParams()); } HttpsURLConnection.setDefaultHostnameVerifier(verifier); }
From source file:eu.elf.license.LicenseService.java
/** * Get cookies from admin console/*w w w. j av a2 s . c om*/ * @return BasicCookieStore */ @SuppressWarnings("deprecation") public BasicCookieStore getAdminConsoleCookies() { //System.out.println("Fetching cookies..."); //CloseableHttpClient httpclient = HttpClients.createDefault(); DefaultHttpClient httpclient = new DefaultHttpClient(); LicenseService.setupProxy(httpclient); HttpPost post = new HttpPost(loginUrl + "&username=" + user + "&password=" + pass); BasicCookieStore bcs = new BasicCookieStore(); try { HttpResponse response = httpclient.execute(post); bcs = (BasicCookieStore) httpclient.getCookieStore(); //List<Cookie> cookieList = bcs.getCookies(); //System.out.println("cookieList.size: "+cookieList.size()); //for (int c = 0; c < cookieList.size(); c++) { //System.out.println("cookie "+c); //System.out.println(cookieList.get(c).getName()); //System.out.println(cookieList.get(c).getValue()); //} } catch (ClientProtocolException cpe) { cpe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } return bcs; }
From source file:de.tudarmstadt.ukp.shibhttpclient.ShibHttpClient.java
/** * Create a new client (with an explicit proxy and possibly transparent authentication) * /*from w w w.j a v a 2 s. c om*/ * @param aIdpUrl * the URL of the IdP. Should probably be something ending in "/SAML2/SOAP/ECP" * @param aUsername * the user name to log into the IdP. * @param aPassword * the password to log in to the IdP. * @param aProxy * if not {@code null}, use this proxy instead of the default system proxy (if any) * @param anyCert * if {@code true}, accept any certificate from any remote host. Otherwise, * certificates need to be installed in the JRE. * @param transparentAuth * if {@code true} (default), add a HttpRequestPostProcessor to transparently * authenticate. Otherwise, you must handle the authentication process yourself. */ public ShibHttpClient(String aIdpUrl, String aUsername, String aPassword, HttpHost aProxy, boolean anyCert, boolean transparentAuth) { setIdpUrl(aIdpUrl); setUsername(aUsername); setPassword(aPassword); // Use a pooling connection manager, because we'll have to do a call out to the IdP // while still being in a connection with the SP PoolingHttpClientConnectionManager connMgr; if (anyCert) { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("http", new PlainConnectionSocketFactory()) .register("https", new SSLConnectionSocketFactory(builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)) .build(); connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry); } catch (GeneralSecurityException e) { // There shouldn't be any of these exceptions, because we do not use an actual // keystore throw new IllegalStateException(e); } } else { connMgr = new PoolingHttpClientConnectionManager(); } connMgr.setMaxTotal(10); connMgr.setDefaultMaxPerRoute(5); // The client needs to remember the auth cookie cookieStore = new BasicCookieStore(); RequestConfig globalRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY) .build(); // Let's throw all common client elements into one builder object HttpClientBuilder customClient = HttpClients.custom().setConnectionManager(connMgr) // The client needs to remember the auth cookie .setDefaultRequestConfig(globalRequestConfig).setDefaultCookieStore(cookieStore) // Add the ECP/PAOS headers - needs to be added first so the cookie we get from // the authentication can be handled by the RequestAddCookies interceptor later .addInterceptorFirst(new HttpRequestPreprocessor()); // Automatically log into IdP if transparent Shibboleth authentication handling is requested (default) if (transparentAuth) { customClient = customClient.addInterceptorFirst(new HttpRequestPostprocessor()); } // Build the client with/without proxy settings if (aProxy == null) { // use the proxy settings of the JVM, if specified client = customClient.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault())) .build(); } else { // use the explicit proxy client = customClient.setProxy(aProxy).build(); } parserPool = new BasicParserPool(); parserPool.setNamespaceAware(true); }
From source file:org.xdi.oxauth.interop.SupportClaimsRequestSpecifyingSubValue.java
@Parameters({ "userId", "userSecret", "redirectUri", "redirectUris", "hostnameVerifier" }) @Test/*from ww w .j ava 2s. c om*/ public void supportClaimsRequestSpecifyingSubValueFail(final String userId, final String userSecret, final String redirectUri, final String redirectUris, String hostnameVerifier) throws Exception { showTitle("OC5:FeatureTest-Support claims Request Specifying sub Value (fail)"); List<ResponseType> responseTypes = Arrays.asList(ResponseType.TOKEN, ResponseType.ID_TOKEN); // 1. Register client RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app", StringUtils.spaceSeparatedToList(redirectUris)); registerRequest.setResponseTypes(responseTypes); RegisterClient registerClient = new RegisterClient(registrationEndpoint); registerClient.setRequest(registerRequest); RegisterResponse registerResponse = registerClient.exec(); showClient(registerClient); assertEquals(registerResponse.getStatus(), 200, "Unexpected response code: " + registerResponse.getEntity()); assertNotNull(registerResponse.getClientId()); assertNotNull(registerResponse.getClientSecret()); assertNotNull(registerResponse.getRegistrationAccessToken()); assertNotNull(registerResponse.getClientIdIssuedAt()); assertNotNull(registerResponse.getClientSecretExpiresAt()); String clientId = registerResponse.getClientId(); String clientSecret = registerResponse.getClientSecret(); DefaultHttpClient httpClient = createHttpClient(HostnameVerifierType.fromString(hostnameVerifier)); CookieStore cookieStore = new BasicCookieStore(); httpClient.setCookieStore(cookieStore); ClientExecutor clientExecutor = new ApacheHttpClient4Executor(httpClient); // 2. Request authorization List<String> scopes = Arrays.asList("openid", "email"); String nonce = UUID.randomUUID().toString(); String state = UUID.randomUUID().toString(); AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, nonce); authorizationRequest.setAuthUsername(userId); authorizationRequest.setAuthPassword(userSecret); authorizationRequest.getPrompts().add(Prompt.NONE); authorizationRequest.setState(state); JwtAuthorizationRequest jwtAuthorizationRequest = new JwtAuthorizationRequest(authorizationRequest, SignatureAlgorithm.HS256, clientSecret); jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.GIVEN_NAME, ClaimValue.createNull())); jwtAuthorizationRequest.addUserInfoClaim(new Claim(JwtClaimName.FAMILY_NAME, ClaimValue.createNull())); jwtAuthorizationRequest .addIdTokenClaim(new Claim(JwtClaimName.SUBJECT_IDENTIFIER, ClaimValue.createSingleValue(userId))); String authJwt = jwtAuthorizationRequest.getEncodedJwt(); authorizationRequest.setRequest(authJwt); AuthorizeClient authorizeClient = new AuthorizeClient(authorizationEndpoint); authorizeClient.setRequest(authorizationRequest); AuthorizationResponse authorizationResponse = authorizeClient.exec(); showClient(authorizeClient); assertEquals(authorizationResponse.getStatus(), 302, "Unexpected response code: " + authorizationResponse.getStatus()); assertNotNull(authorizationResponse.getErrorType(), "The error type is null"); assertEquals(authorizationResponse.getErrorType(), AuthorizeErrorResponseType.USER_MISMATCHED); assertNotNull(authorizationResponse.getErrorDescription(), "The error description is null"); }