List of usage examples for org.apache.http.impl.client BasicCookieStore clear
public synchronized void clear()
From source file:net.fizzl.redditengine.impl.AccountApi.java
/** * Log into a reddit account using SSL * //from w w w . j a v a 2 s . c om * @param user username * @param passwd users password * @param remember specifies whether or not the session cookie returned should last beyond the current browser session * @throws RedditEngineException */ public AuthResponse login(String user, String passwd, boolean remember) throws RedditEngineException { StringBuilder sb = new StringBuilder(); sb.append(UrlUtils.REDDIT_SSL); sb.append(LOGIN_PATH); String url = sb.toString(); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("user", user)); params.add(new BasicNameValuePair("passwd", passwd)); params.add(new BasicNameValuePair("api_type", API_TYPE_JSON)); params.add(new BasicNameValuePair("rem", Boolean.toString(remember))); // The HTTP status code of the response will almost always be a 200 (OK) regardless of authentication success. // To see if login was successful, check the JSON response. // POST requests to /api/login must not include a reddit_session cookie along in the request. If a reddit_session cookie exists, the request may fail with a 409 status. AuthResponse ret = null; SimpleHttpClient client = SimpleHttpClient.getInstance(); // TODO should SimpleHttpClient have some kind of save/restore cookies function instead of accessing the cookiestore directly? BasicCookieStore cookieStore = client.getCookieStore(); List<Cookie> cookies = cookieStore.getCookies(); Cookie[] cookieArray = cookies.toArray(new Cookie[cookies.size()]); try { cookieStore.clear(); InputStream is = client.post(url, params); ret = AuthResponse.fromInputStream(is); if (ret.getJson().getData() != null) { lastPassword = passwd; } else { // an error occurred cookieStore.addCookies(cookieArray); } is.close(); } catch (Exception e) { // if failed, put the cookies back cookieStore.addCookies(cookieArray); throw new RedditEngineException(e); } return ret; }
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 . ja va2 s .com*/ } } 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:org.cloudfoundry.identity.uaa.integration.RefreshTokenSupportIntegrationTests.java
@Test public void testTokenRefreshedCorrectFlow() throws Exception { BasicCookieStore cookies = new BasicCookieStore(); AuthorizationCodeResourceDetails resource = testAccounts.getDefaultAuthorizationCodeResource(); URI uri = serverRunning.buildUri("/oauth/authorize").queryParam("response_type", "code") .queryParam("state", "mystateid").queryParam("client_id", resource.getClientId()) .queryParam("redirect_uri", resource.getPreEstablishedRedirectUri()).build(); ResponseEntity<Void> result = serverRunning.getForResponse(uri.toString(), getHeaders(cookies)); assertEquals(HttpStatus.FOUND, result.getStatusCode()); String location = result.getHeaders().getLocation().toString(); if (result.getHeaders().containsKey("Set-Cookie")) { for (String cookie : result.getHeaders().get("Set-Cookie")) { int nameLength = cookie.indexOf('='); cookies.addCookie(//ww w . j a va2s .c o m new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1))); } } ResponseEntity<String> response = serverRunning.getForString(location, getHeaders(cookies)); if (response.getHeaders().containsKey("Set-Cookie")) { for (String cookie : response.getHeaders().get("Set-Cookie")) { int nameLength = cookie.indexOf('='); cookies.addCookie( new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1))); } } // should be directed to the login screen... assertTrue(response.getBody().contains("/login.do")); assertTrue(response.getBody().contains("username")); assertTrue(response.getBody().contains("password")); MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>(); formData.add("username", testAccounts.getUserName()); formData.add("password", testAccounts.getPassword()); formData.add(DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(response.getBody())); // Should be redirected to the original URL, but now authenticated result = serverRunning.postForResponse("/login.do", getHeaders(cookies), formData); cookies.clear(); if (result.getHeaders().containsKey("Set-Cookie")) { for (String cookie : result.getHeaders().get("Set-Cookie")) { int nameLength = cookie.indexOf('='); cookies.addCookie( new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1))); } } assertEquals(HttpStatus.FOUND, result.getStatusCode()); response = serverRunning.getForString(result.getHeaders().getLocation().toString(), getHeaders(cookies)); if (response.getHeaders().containsKey("Set-Cookie")) { for (String cookie : response.getHeaders().get("Set-Cookie")) { int nameLength = cookie.indexOf('='); cookies.addCookie( new BasicClientCookie(cookie.substring(0, nameLength), cookie.substring(nameLength + 1))); } } if (response.getStatusCode() == HttpStatus.OK) { // The grant access page should be returned assertTrue(response.getBody().contains("<h1>Application Authorization</h1>")); formData.clear(); formData.add(USER_OAUTH_APPROVAL, "true"); formData.add(DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(response.getBody())); result = serverRunning.postForResponse("/oauth/authorize", getHeaders(cookies), formData); assertEquals(HttpStatus.FOUND, result.getStatusCode()); location = result.getHeaders().getLocation().toString(); } else { // Token cached so no need for second approval assertEquals(HttpStatus.FOUND, response.getStatusCode()); location = response.getHeaders().getLocation().toString(); } assertTrue("Wrong location: " + location, location.matches(resource.getPreEstablishedRedirectUri() + ".*code=.+")); formData.clear(); formData.add("client_id", resource.getClientId()); formData.add("redirect_uri", resource.getPreEstablishedRedirectUri()); formData.add("grant_type", GRANT_TYPE_AUTHORIZATION_CODE); formData.add("code", location.split("code=")[1].split("&")[0]); HttpHeaders tokenHeaders = new HttpHeaders(); tokenHeaders.set("Authorization", testAccounts.getAuthorizationHeader(resource.getClientId(), resource.getClientSecret())); tokenHeaders.set("Cache-Control", "no-store"); @SuppressWarnings("rawtypes") ResponseEntity<Map> tokenResponse = serverRunning.postForMap("/oauth/token", formData, tokenHeaders); assertEquals(HttpStatus.OK, tokenResponse.getStatusCode()); @SuppressWarnings("unchecked") OAuth2AccessToken accessToken = DefaultOAuth2AccessToken.valueOf(tokenResponse.getBody()); // get the refresh token formData = new LinkedMultiValueMap<String, String>(); formData.add("grant_type", "refresh_token"); formData.add("refresh_token", accessToken.getRefreshToken().getValue()); tokenResponse = serverRunning.postForMap("/oauth/token", formData, tokenHeaders); assertEquals(HttpStatus.OK, tokenResponse.getStatusCode()); assertEquals("no-store", tokenResponse.getHeaders().getFirst("Cache-Control")); @SuppressWarnings("unchecked") OAuth2AccessToken newAccessToken = DefaultOAuth2AccessToken.valueOf(tokenResponse.getBody()); try { JwtHelper.decode(newAccessToken.getValue()); } catch (IllegalArgumentException e) { fail("Refreshed token was not a JWT"); } assertFalse("New access token should be different to the old one.", newAccessToken.getValue().equals(accessToken.getValue())); }