List of usage examples for org.apache.http.impl.client BasicCookieStore BasicCookieStore
public BasicCookieStore()
From source file:com.vmware.gemfire.tools.pulse.tests.junit.BaseServiceTest.java
/** * Login to pulse server and setup httpClient for tests * To be called from setupBeforeClass in each test class *//*from w w w. j ava 2s . c o m*/ protected static void doLogin() throws Exception { System.out.println("BaseServiceTest :: Executing doLogin with user : admin, password : admin."); CloseableHttpResponse loginResponse = null; try { BasicCookieStore cookieStore = new BasicCookieStore(); httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); HttpUriRequest login = RequestBuilder.post().setUri(new URI(LOGIN_URL)) .addParameter("j_username", "admin").addParameter("j_password", "admin").build(); loginResponse = httpclient.execute(login); try { HttpEntity entity = loginResponse.getEntity(); EntityUtils.consume(entity); System.out.println("BaseServiceTest :: HTTP request status : " + loginResponse.getStatusLine()); List<Cookie> cookies = cookieStore.getCookies(); if (cookies.isEmpty()) { } else { for (int i = 0; i < cookies.size(); i++) { } } } finally { if (loginResponse != null) loginResponse.close(); } } catch (Exception failed) { logException(failed); throw failed; } System.out.println("BaseServiceTest :: Executed doLogin"); }
From source file:biocode.fims.ezid.EzidService.java
/** * Construct an EzidService to be used to access EZID. *//*from w w w .jav a2 s .co m*/ public EzidService() { httpClient = createThreadSafeClient(); cookieStore = new BasicCookieStore(); httpClient.setCookieStore(cookieStore); }
From source file:com.farmafene.commons.cas.LoginTGT.java
public void doLogout(Cookie cookie) { HttpResponse res = null;/* w w w .jav a 2 s. c o m*/ HttpClientFactory f = new HttpClientFactory(); f.setLoginURL(getCasServerURL()); DefaultHttpClient client = null; client = f.getClient(); HttpContext localContext = new BasicHttpContext(); BasicCookieStore cs = new BasicCookieStore(); cs.addCookie(cookie); HttpPost post = new HttpPost(getURL("logout")); client.setCookieStore(cs); localContext.setAttribute(ClientContext.COOKIE_STORE, cs); try { res = client.execute(post, localContext); if (res.getStatusLine().getStatusCode() != 200) { AuriusAuthException ex = new AuriusAuthException("Error"); logger.error("Excepcion en el login", ex); throw ex; } } catch (ClientProtocolException e) { AuriusAuthException ex = new AuriusAuthException("ClientProtocolException", AuriusExceptionTO.getInstance(e)); logger.error("Excepcion en el login", ex); throw ex; } catch (IOException e) { AuriusAuthException ex = new AuriusAuthException("IOException", AuriusExceptionTO.getInstance(e)); logger.error("Excepcion en el login", ex); throw ex; } }
From source file:edu.mit.scratch.ScratchUserManager.java
public ScratchUserManager update() throws ScratchUserException { try {/*from ww w . ja va 2s .c o m*/ final RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT).build(); final CookieStore cookieStore = new BasicCookieStore(); final BasicClientCookie lang = new BasicClientCookie("scratchlanguage", "en"); final BasicClientCookie sessid = new BasicClientCookie("scratchsessionsid", this.session.getSessionID()); final BasicClientCookie token = new BasicClientCookie("scratchcsrftoken", this.session.getCSRFToken()); final BasicClientCookie debug = new BasicClientCookie("DEBUG", "true"); lang.setDomain(".scratch.mit.edu"); lang.setPath("/"); sessid.setDomain(".scratch.mit.edu"); sessid.setPath("/"); token.setDomain(".scratch.mit.edu"); token.setPath("/"); debug.setDomain(".scratch.mit.edu"); debug.setPath("/"); cookieStore.addCookie(lang); cookieStore.addCookie(sessid); cookieStore.addCookie(token); cookieStore.addCookie(debug); 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/messages/ajax/get-message-count/") .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") .addHeader("Cookie", "scratchsessionsid=" + this.session.getSessionID() + "; scratchcsrftoken=" + this.session.getCSRFToken()) .addHeader("X-CSRFToken", this.session.getCSRFToken()).build(); try { resp = httpClient.execute(update); } catch (final IOException e) { e.printStackTrace(); throw new ScratchUserException(); } BufferedReader rd; try { rd = new BufferedReader(new InputStreamReader(resp.getEntity().getContent())); } catch (UnsupportedOperationException | IOException e) { e.printStackTrace(); throw new ScratchUserException(); } 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 = jsonOBJ.keys(); while (keys.hasNext()) { final String key = "" + keys.next(); final Object o = jsonOBJ.get(key); final String val = "" + o; switch (key) { case "msg_count": this.message_count = Integer.parseInt(val); break; default: System.out.println("Missing reference:" + key); break; } } } catch (final Exception e) { e.printStackTrace(); throw new ScratchUserException(); } return this; }
From source file:org.apache.jena.atlas.web.auth.FormsAuthenticator.java
@Override public void apply(AbstractHttpClient client, HttpContext httpContext, URI target) { if (client == null) return;//from w w w . java 2s . c o m // Do we have a login available for the target server? FormLogin login = this.findCredentials(target); if (login == null) return; // We need to synchronize on the login because making a login attempt // may take a while and there is no point making multiple login attempts // against the same server synchronized (login) { // Have we already logged into this server? if (login.hasCookies()) { // Use existing cookies LOG.info("Using existing cookies to authenticate access to " + target.toString()); CookieStore store = login.getCookies(); if (store != null) client.setCookieStore(store); // Check if any of the cookies have expired if (!store.clearExpired(Calendar.getInstance().getTime())) { // No cookies were cleared so our cookies are still fresh // and we don't need to login again return; } // If we reach here then some of our cookies have expired and we // may no longer be logged in and should login again instead of // proceeding with the existing cookies } try { // Use a fresh Cookie Store for new login attempts CookieStore store = new BasicCookieStore(); client.setCookieStore(store); // Try to login LOG.info("Making login attempt against " + login.getLoginFormURL() + " to obtain authentication for access to " + target.toString()); HttpPost post = new HttpPost(login.getLoginFormURL()); post.setEntity(login.getLoginEntity()); HttpResponse response = client.execute(post, httpContext); // Always read the payload to ensure reusable connections final String payload = HttpOp.readPayload(response.getEntity()); // Check for successful login if (response.getStatusLine().getStatusCode() >= 400) { LOG.warn("Failed to login against " + login.getLoginFormURL() + " to obtain authentication for access to " + target.toString()); throw new HttpException(response.getStatusLine().getStatusCode(), "Login attempt failed - " + response.getStatusLine().getReasonPhrase(), payload); } // Otherwise assume a successful login LOG.info("Successfully logged in against " + login.getLoginFormURL() + " and obtained authentication for access to " + target.toString()); login.setCookies(client.getCookieStore()); } catch (UnsupportedEncodingException e) { throw new HttpException("UTF-8 encoding not supported on your platform", e); } catch (IOException e) { throw new HttpException("Error making login request", e); } } }
From source file:org.wildfly.elytron.web.undertow.server.FormAuthenticationWithClusteredSSOTest.java
@Test public void testSingleSignOn() throws Exception { BasicCookieStore cookieStore = new BasicCookieStore(); HttpClient httpClient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build(); assertLoginPage(httpClient.execute(new HttpGet(serverA.createUri()))); assertFalse(cookieStore.getCookies().stream().filter(cookie -> cookie.getName().equals("JSESSIONSSOID")) .findAny().isPresent());/* w w w .ja v a2 s .c o m*/ // authenticate on NODE_A HttpPost httpAuthenticate = new HttpPost(serverA.createUri("/j_security_check")); List<NameValuePair> parameters = new ArrayList<>(2); parameters.add(new BasicNameValuePair("j_username", "ladybird")); parameters.add(new BasicNameValuePair("j_password", "Coleoptera")); httpAuthenticate.setEntity(new UrlEncodedFormEntity(parameters)); HttpResponse execute = httpClient.execute(httpAuthenticate); assertTrue(cookieStore.getCookies().stream().filter(cookie -> cookie.getName().equals("JSESSIONSSOID")) .findAny().isPresent()); assertSuccessfulResponse(execute, "ladybird"); assertSuccessfulResponse(httpClient.execute(new HttpGet(serverB.createUri())), "ladybird"); assertSuccessfulResponse(httpClient.execute(new HttpGet(serverC.createUri())), "ladybird"); assertSuccessfulResponse(httpClient.execute(new HttpGet(serverD.createUri())), "ladybird"); assertSuccessfulResponse(httpClient.execute(new HttpGet(serverE.createUri())), "ladybird"); }
From source file:com.vaushell.shaarlijavaapi.ShaarliClient.java
/** * Construct the DAO with specifics templates. * * @param templates Shaarli templates (if you don't use the default one) * @param endpoint Shaarli endpoint (like http://fabien.vauchelles.com/~fabien/shaarli) *//*from w w w . j a va 2s.c o m*/ public ShaarliClient(final ShaarliTemplates templates, final String endpoint) { this(HttpClientBuilder.create().setDefaultCookieStore(new BasicCookieStore()) .setUserAgent("Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0.1").build(), templates, endpoint); }
From source file:io.undertow.server.security.SsoTestCase.java
@Test public void testSsoSuccess() throws IOException { TestHttpClient client = new TestHttpClient(); client.setCookieStore(new BasicCookieStore()); HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/test1"); HttpResponse result = client.execute(get); assertEquals(StatusCodes.UNAUTHORIZED, result.getStatusLine().getStatusCode()); Header[] values = result.getHeaders(WWW_AUTHENTICATE.toString()); String header = getAuthHeader(BASIC, values); assertEquals(BASIC + " realm=\"Test Realm\"", header); HttpClientUtils.readResponse(result); get = new HttpGet(DefaultServer.getDefaultServerURL() + "/test1"); get.addHeader(AUTHORIZATION.toString(), BASIC + " " + FlexBase64.encodeString("userOne:passwordOne".getBytes(), false)); result = client.execute(get);/*from ww w . j a va 2s . c o m*/ assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); values = result.getHeaders("ProcessedBy"); assertEquals(1, values.length); assertEquals("ResponseHandler", values[0].getValue()); HttpClientUtils.readResponse(result); assertSingleNotificationType(SecurityNotification.EventType.AUTHENTICATED); get = new HttpGet(DefaultServer.getDefaultServerURL() + "/test2"); result = client.execute(get); assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); values = result.getHeaders("ProcessedBy"); assertEquals(1, values.length); assertEquals("ResponseHandler", values[0].getValue()); HttpClientUtils.readResponse(result); assertSingleNotificationType(SecurityNotification.EventType.AUTHENTICATED); //now test that logout will invalidate the SSO session get = new HttpGet(DefaultServer.getDefaultServerURL() + "/test1?logout=true"); get.addHeader(AUTHORIZATION.toString(), BASIC + " " + FlexBase64.encodeString("userOne:passwordOne".getBytes(), false)); result = client.execute(get); assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode()); values = result.getHeaders("ProcessedBy"); assertEquals(1, values.length); assertEquals("ResponseHandler", values[0].getValue()); HttpClientUtils.readResponse(result); assertNotifiactions(SecurityNotification.EventType.AUTHENTICATED, SecurityNotification.EventType.LOGGED_OUT); get = new HttpGet(DefaultServer.getDefaultServerURL() + "/test2"); result = client.execute(get); assertEquals(StatusCodes.UNAUTHORIZED, result.getStatusLine().getStatusCode()); }
From source file:org.zenoss.metrics.reporter.HttpPoster.java
@Override public void start() { this.httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); cookieJar = new BasicCookieStore(); post = new HttpPost(url.toString()); post.addHeader(ACCEPT, APPLICATION_JSON.toString()); responseHandler = new AuthResponseHandler(); }
From source file:org.datacleaner.util.http.CASMonitorHttpClient.java
@Override public HttpResponse execute(final HttpUriRequest request) throws Exception { // enable cookies final CookieStore cookieStore = new BasicCookieStore(); final HttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.COOKIE_STORE, cookieStore); _httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); final String ticketGrantingTicket; try {//from w ww . j a va 2s . c o m ticketGrantingTicket = _ticketGrantingTicketRef.get(); } catch (IllegalStateException e) { if (e.getCause() instanceof SSLPeerUnverifiedException) { // Unverified SSL peer exceptions needs to be rethrown // specifically, since they can be caught and the user may // decide to remove certificate checks. throw (SSLPeerUnverifiedException) e.getCause(); } throw e; } final String ticket = getTicket(_requestedService, _casRestServiceUrl, ticketGrantingTicket, context); logger.debug("Got a service ticket: {}", ticketGrantingTicket); logger.debug("Cookies 2: {}", cookieStore.getCookies()); // now we request the spring security CAS check service, this will set // cookies on the client. final HttpGet cookieRequest = new HttpGet(_requestedService + "?ticket=" + ticket); final HttpResponse cookieResponse = executeHttpRequest(cookieRequest, context); EntityUtils.consume(cookieResponse.getEntity()); cookieRequest.releaseConnection(); logger.debug("Cookies 3: {}", cookieStore.getCookies()); final HttpResponse result = executeHttpRequest(request, context); logger.debug("Cookies 4: {}", cookieStore.getCookies()); return result; }