List of usage examples for org.apache.http.client CookieStore getCookies
List<Cookie> getCookies();
From source file:com.cognifide.qa.bb.aem.AemAuthCookieFactory.java
/** * This method provides browser cookie for authenticating user to AEM instance * * @param url URL to AEM instance, like http://localhost:4502 * @param login Username to use/*from w w w.j a v a2s . com*/ * @param password Password to use * @return Cookie for selenium WebDriver. */ public Cookie getCookie(String url, String login, String password) { if (!cookieJar.containsKey(url)) { HttpPost loginPost = new HttpPost(url + "/libs/granite/core/content/login.html/j_security_check"); List<NameValuePair> nameValuePairs = new ArrayList<>(); nameValuePairs.add(new BasicNameValuePair("_charset_", "utf-8")); nameValuePairs.add(new BasicNameValuePair("j_username", login)); nameValuePairs.add(new BasicNameValuePair("j_password", password)); nameValuePairs.add(new BasicNameValuePair("j_validate", "true")); CookieStore cookieStore = new BasicCookieStore(); HttpClientContext context = HttpClientContext.create(); if ("true".equals(properties.getProperty(ConfigKeys.WEBDRIVER_PROXY_COOKIE))) { addProxyCookie(cookieStore); } context.setCookieStore(cookieStore); try { loginPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); CloseableHttpResponse loginResponse = httpClient.execute(loginPost, context); loginResponse.close(); } catch (IOException e) { LOG.error("Can't get AEM authentication cookie", e); } finally { loginPost.reset(); } Cookie cookie = findAuthenticationCookie(cookieStore.getCookies()); if (cookie != null) { cookieJar.put(url, cookie); } } return cookieJar.get(url); }
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 {// w w w .ja va 2 s . 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; }
From source file:nya.miku.wishmaster.http.cloudflare.InterceptingAntiDDOS.java
/** anti-DDOS , ? ? ?? webview httpclient (? ?? ? ?-? API >= 11) */ Cookie check(final CloudflareException exception, final ExtendedHttpClient httpClient, final CancellableTask task, final Activity activity) { synchronized (lock) { if (processing) return null; processing = true;/*w ww. j a v a 2 s.c o m*/ } processing2 = true; currentCookie = null; final HttpRequestModel rqModel = HttpRequestModel.builder().setGET().build(); final CookieStore cookieStore = httpClient.getCookieStore(); CloudflareChecker.removeCookie(cookieStore, exception.getRequiredCookieName()); final ViewGroup layout = (ViewGroup) activity.getWindow().getDecorView().getRootView(); final WebViewClient client = new WebViewClient() { @Override public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) { handler.proceed(); } @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { HttpResponseModel responseModel = null; try { responseModel = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, null, task); for (int i = 0; i < 3 && responseModel.statusCode == 400; ++i) { Logger.d(TAG, "HTTP 400"); responseModel.release(); responseModel = HttpStreamer.getInstance().getFromUrl(url, rqModel, httpClient, null, task); } for (Cookie cookie : cookieStore.getCookies()) { if (CloudflareChecker.isClearanceCookie(cookie, url, exception.getRequiredCookieName())) { Logger.d(TAG, "Cookie found: " + cookie.getValue()); currentCookie = cookie; processing2 = false; return new WebResourceResponse("text/html", "UTF-8", new ByteArrayInputStream("cookie received".getBytes())); } } BufOutputStream output = new BufOutputStream(); IOUtils.copyStream(responseModel.stream, output); return new WebResourceResponse(null, null, output.toInputStream()); } catch (Exception e) { Logger.e(TAG, e); } finally { if (responseModel != null) responseModel.release(); } return new WebResourceResponse("text/html", "UTF-8", new ByteArrayInputStream("something wrong".getBytes())); } }; activity.runOnUiThread(new Runnable() { @SuppressLint("SetJavaScriptEnabled") @Override public void run() { webView = new WebView(activity); webView.setVisibility(View.GONE); layout.addView(webView); webView.setWebViewClient(client); webView.getSettings().setUserAgentString(HttpConstants.USER_AGENT_STRING); webView.getSettings().setJavaScriptEnabled(true); webView.loadUrl(exception.getCheckUrl()); } }); long startTime = System.currentTimeMillis(); while (processing2) { long time = System.currentTimeMillis() - startTime; if ((task != null && task.isCancelled()) || time > CloudflareChecker.TIMEOUT) { processing2 = false; } } activity.runOnUiThread(new Runnable() { @Override public void run() { try { layout.removeView(webView); webView.stopLoading(); webView.clearCache(true); webView.destroy(); webView = null; } finally { processing = false; } } }); return currentCookie; }
From source file:ca.osmcanada.osvuploadr.JPMain.java
public String GetOSMUser(String usr, String psw) throws IOException { final OAuth10aService service = new ServiceBuilder().apiKey(API_KEY).apiSecret(API_SECRET) .build(OSMApi.instance());/*from ww w . j a v a2 s . c om*/ final OAuth1RequestToken requestToken = service.getRequestToken(); String url = service.getAuthorizationUrl(requestToken); //Automated grant and login*************************************** //Get logon form CookieStore httpCookieStore = new BasicCookieStore(); HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(httpCookieStore).build(); //post.setHeader("User-Agent", USER_AGENT); try { PageContent pc = Helper.GetPageContent(url, client); List<Cookie> cookies = httpCookieStore.getCookies(); System.out.println("Getting OSM Login page"); String page = pc.GetPage(); System.out.println("Sending username and password"); int start_indx = page.indexOf("value=\"", page.indexOf("name=\"authenticity_token\"")) + 7; int end_indx = page.indexOf("\"", start_indx); String utf8 = ""; String authenticity_token = page.substring(start_indx, end_indx); start_indx = page.indexOf("value=\"", page.indexOf("name=\"referer\"")) + 7; end_indx = page.indexOf("\"", start_indx); String referer = page.substring(start_indx, end_indx); Map<String, String> arguments = new HashMap<>(); arguments.put("utf8", utf8); arguments.put("authenticity_token", authenticity_token); arguments.put("referer", referer); arguments.put("username", usr); arguments.put("password", psw); arguments.put("commit", "Login"); arguments.put("openid_url", ""); System.out.println("Logging in"); page = sendForm(BASE_URL + "login", arguments, "POST", cookies); //Proccessing grant access page System.out.println("Processing Granting Access page"); start_indx = page.indexOf("<form");//Find form tag start_indx = page.indexOf("action=\"", start_indx) + 8; //get action url end_indx = page.indexOf("\"", start_indx); //get closing tag String action_url = page.substring(start_indx, end_indx); if (action_url.startsWith("/")) { action_url = BASE_URL + action_url.substring(1, action_url.length()); } else if (!action_url.toLowerCase().startsWith("http")) { //Need to post same level as current url end_indx = url.lastIndexOf("/") + 1; action_url = url.substring(0, end_indx) + action_url; } start_indx = page.indexOf("name=\"authenticity_token\""); start_indx = FindOpening(page, start_indx, "<"); start_indx = page.indexOf("value=\"", start_indx) + 7; end_indx = page.indexOf("\"", start_indx); authenticity_token = page.substring(start_indx, end_indx); start_indx = page.indexOf("name=\"oauth_token\""); start_indx = FindOpening(page, start_indx, "<"); start_indx = page.indexOf("value=\"", start_indx) + 7; end_indx = page.indexOf("\"", start_indx); String oauth_token = page.substring(start_indx, end_indx); arguments.clear(); arguments.put("utf8", utf8); arguments.put("authenticity_token", authenticity_token); arguments.put("oauth_token", oauth_token); arguments.put("allow_read_prefs", "yes"); arguments.put("commit", "Grant+Access"); //Get PIN System.out.println("Submitting grant access"); page = sendForm(action_url, arguments, "POST", cookies); //Find lovely PIN code in page that might be multilingual...(fun) start_indx = page.indexOf("class=\"content-body\""); end_indx = page.indexOf("</div>", start_indx); String tmp = page.substring(start_indx, end_indx); //Get aproximate location of pin code Pattern p = Pattern.compile("([A-Za-z0-9]){15,25}"); Matcher m = p.matcher(tmp); String pin = ""; if (m.find()) { pin = m.group(); } final OAuth1AccessToken accessToken = service.getAccessToken(requestToken, pin); return accessToken.getToken() + "|" + accessToken.getTokenSecret(); } catch (Exception ex) { Logger.getLogger(JPMain.class.getName()).log(Level.SEVERE, null, ex); } //End Automated grant and login ********************************** return ""; }
From source file:org.sonatype.nexus.testsuite.security.SimpleSessionCookieIT.java
/** * Validate Nexus Cookies during Sign-in and Sign-out *///from w w w . ja va 2s .c o m private void exerciseCookieSpec(final URL baseUrl) throws Exception { // handle cookies like a browser to aid validation final CookieSpec spec = new DefaultCookieSpecProvider().create(null); final CookieOrigin cookieOrigin = cookieOrigin(baseUrl); final CookieStore cookieStore = new BasicCookieStore(); final CredentialsProvider credProvider = credentialsProvider(); SetCookie loginCookie; try (CloseableHttpClient client = clientBuilder().setDefaultCookieStore(cookieStore) .setDefaultCredentialsProvider(credProvider).build()) { // 1. login with credentials and get session cookie // Set-Cookie: NXSESSIONID=98a766bc-bc33-4b3c-9d9f-d3bb85b0cf00; Path=/; Secure; HttpOnly HttpPost loginRequest = new HttpPost(resolveUrl(baseUrl, SESSION_PATH).toURI()); List<NameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("username", Strings2.encodeBase64(credentials().getUserPrincipal().getName()))); params.add(new BasicNameValuePair("password", Strings2.encodeBase64(credentials().getPassword()))); loginRequest.setEntity(new UrlEncodedFormEntity(params)); withCommonBrowserHeaders(loginRequest); try (CloseableHttpResponse response = client.execute(loginRequest, clientContext())) { assertThat(response.getStatusLine().getStatusCode(), is(200)); assertThat("login cookie should have been stored in the cookie store", cookieStore.getCookies(), hasSize(1)); assertThat("expected session cookie in cookie store", getSessionCookie(cookieStore), notNullValue()); Header[] setCookieHeaders = response.getHeaders(SET_COOKIE); Header sessionCookieHeader = getSessionCookieHeader(setCookieHeaders); List<Cookie> sessionCookies = spec.parse(sessionCookieHeader, cookieOrigin); loginCookie = (SetCookie) sessionCookies.get(0); String headerText = sessionCookieHeader.toString(); assertCommonSessionCookieAttributes(baseUrl, loginCookie, headerText); assertThat(String.format("expecting one cookie parsed from session %s header", SET_COOKIE), sessionCookies, hasSize(1)); assertThat(String.format( "expecting 2 %s headers for login, one session cookie, one remember me, but got %s", SET_COOKIE, setCookieHeaders), setCookieHeaders, arrayWithSize(2)); assertThat("login cookie should NOT look like deleteMe cookie", loginCookie.getValue(), not(containsString("deleteMe"))); assertThat( "login cookie should not have an expiry date - the UA deletes the session cookie when " + "replaced by a new one by same name from the server OR when the UA decides", loginCookie.isPersistent(), is(false)); assertThat("login session cookie with valid session id should always be marked HttpOnly", headerText, containsString("; HttpOnly")); } HttpClientContext logoutContext = HttpClientContext.create(); logoutContext.setCookieStore(cookieStore); HttpDelete logoutRequest = new HttpDelete(resolveUrl(baseUrl, SESSION_PATH).toURI()); withCommonBrowserHeaders(logoutRequest); // 2. Logout, sending valid session cookie, no credentials // Set-Cookie: NXSESSIONID=deleteMe; Path=/; Max-Age=0; Expires=Sun, 28-Dec-2014 15:59:11 GMT try (CloseableHttpResponse response = client.execute(logoutRequest, logoutContext)) { assertThat(response.getStatusLine().getStatusCode(), is(200)); // can't use client CookieStore to examine logout cookie, because the Expires header will prevent it from being // added but we can implicitly confirm it expired the existing cookie according to our client assertThat("logout cookie should have emptied the cookie store due to expiry date", cookieStore.getCookies(), hasSize(0)); Header[] setCookieHeaders = response.getHeaders(SET_COOKIE); Header sessionCookieHeader = getSessionCookieHeader(setCookieHeaders); List<Cookie> sessionCookies = spec.parse(sessionCookieHeader, cookieOrigin); SetCookie logoutCookie = (SetCookie) sessionCookies.get(0); final String headerText = sessionCookieHeader.toString(); assertCommonSessionCookieAttributes(baseUrl, logoutCookie, headerText); assertThat("expecting one cookie in same Set-Cookie header", sessionCookies, hasSize(1)); assertThat(String.format( "expecting 2 %s headers for logout, one session cookie delete cookie, one remember me delete cookie, but got %s", SET_COOKIE, setCookieHeaders), setCookieHeaders, arrayWithSize(2)); assertThat("logout session cookie value should be dummy value", logoutCookie.getValue(), equalTo("deleteMe")); assertThat("logout session cookie should be expired to tell browser to delete it", logoutCookie.isExpired(new Date()), is(true)); assertThat( "technically the presence of an expiry date means the cookie is persistent, but expiry will override", logoutCookie.isPersistent(), is(true)); assertThat( "logout cookie does not have a real session id value, therefore it does not need to be HttpOnly", headerText, not(containsString("; HttpOnly"))); } // 3. Access a protected resource again using our original login cookie, no credentials, to verify session is dead HttpGet loginFailedGet = new HttpGet(resolveUrl(baseUrl, PROTECTED_PATH).toURI()); cookieStore.addCookie(loginCookie); try (CloseableHttpResponse response = client.execute(loginFailedGet, HttpClientContext.create())) { assertThat("expected dead login session cookie to not authenticate", response.getStatusLine().getStatusCode(), is(401)); Header[] setCookieHeaders = response.getHeaders(SET_COOKIE); assertThat("expecting no session cookie since login was unsuccessful", getSessionCookieHeader(setCookieHeaders), nullValue()); assertThat("expecting no cookies since login was unsuccessful", setCookieHeaders, arrayWithSize(0)); } } }
From source file:org.ofbiz.testtools.seleniumxml.RemoteRequest.java
public void runTest() { ClientConnectionManager ccm = new ThreadSafeClientConnManager(defaultParameters, supportedSchemes); // new SingleClientConnManager(getParams(), supportedSchemes); DefaultHttpClient client = new DefaultHttpClient(ccm, defaultParameters); client.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()); ////from w w w . j a v a 2 s .co m // We first try to login with the loginAs to set the session. // Then we call the remote service. // HttpEntity entity = null; ResponseHandler<String> responseHandler = null; try { BasicHttpContext localContext = new BasicHttpContext(); // Create a local instance of cookie store CookieStore cookieStore = new BasicCookieStore(); localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); Header sessionHeader = null; if (this.loginAsUrl != null) { String loginAsUri = this.host + this.loginAsUrl; String loginAsParamString = "?" + this.loginAsUserParam + "&" + this.loginAsPasswordParam; HttpGet req2 = new HttpGet(loginAsUri + loginAsParamString); System.out.println("loginAsUrl:" + loginAsUri + loginAsParamString); req2.setHeader("Connection", "Keep-Alive"); HttpResponse rsp = client.execute(req2, localContext); Header[] headers = rsp.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Header hdr = headers[i]; String headerValue = hdr.getValue(); if (headerValue.startsWith("JSESSIONID")) { sessionHeader = hdr; } System.out.println("login: " + hdr.getName() + " : " + hdr.getValue()); } List<Cookie> cookies = cookieStore.getCookies(); System.out.println("cookies.size(): " + cookies.size()); for (int i = 0; i < cookies.size(); i++) { System.out.println("Local cookie(0): " + cookies.get(i)); } } //String paramString2 = "USERNAME=" + this.parent.getUserName() // + "&PASSWORD=" + this.parent.getPassword(); //String thisUri2 = this.host + "/eng/control/login?" + paramString2; //HttpGet req2 = new HttpGet ( thisUri2 ); //req2.setHeader("Connection","Keep-Alive"); //HttpResponse rsp = client.execute(req2, localContext); //Header sessionHeader = null; //Header[] headers = rsp.getAllHeaders(); //for (int i=0; i<headers.length; i++) { // Header hdr = headers[i]; // String headerValue = hdr.getValue(); // if (headerValue.startsWith("JSESSIONID")) { // sessionHeader = hdr; // } // System.out.println(headers[i]); // System.out.println(hdr.getName() + " : " + hdr.getValue()); //} //List<Cookie> cookies = cookieStore.getCookies(); //System.out.println("cookies.size(): " + cookies.size()); //for (int i = 0; i < cookies.size(); i++) { // System.out.println("Local cookie(0): " + cookies.get(i)); //} if (HttpHandleMode.equals(this.responseHandlerMode)) { } else { responseHandler = new JsonResponseHandler(this); } String paramString = urlEncodeArgs(this.inMap, false); String thisUri = null; if (sessionHeader != null) { String sessionHeaderValue = sessionHeader.getValue(); int pos1 = sessionHeaderValue.indexOf("="); int pos2 = sessionHeaderValue.indexOf(";"); String sessionId = sessionHeaderValue.substring(pos1 + 1, pos2); thisUri = this.host + this.requestUrl + ";jsessionid=" + sessionId + "?" + paramString; } else { thisUri = this.host + this.requestUrl + "?" + paramString; } //String sessionHeaderValue = sessionHeader.getValue(); //int pos1 = sessionHeaderValue.indexOf("="); //int pos2 = sessionHeaderValue.indexOf(";"); //String sessionId = sessionHeaderValue.substring(pos1 + 1, pos2); //System.out.println("sessionId: " + sessionId); //String thisUri = this.host + this.requestUrl + ";jsessionid=" + sessionId + "?" + paramString; //String thisUri = this.host + this.requestUrl + "?" + paramString; System.out.println("thisUri: " + thisUri); HttpGet req = new HttpGet(thisUri); if (sessionHeader != null) { req.setHeader(sessionHeader); } String responseBody = client.execute(req, responseHandler, localContext); /* entity = rsp.getEntity(); System.out.println("----------------------------------------"); System.out.println(rsp.getStatusLine()); Header[] headers = rsp.getAllHeaders(); for (int i=0; i<headers.length; i++) { System.out.println(headers[i]); } System.out.println("----------------------------------------"); if (entity != null) { System.out.println(EntityUtils.toString(rsp.getEntity())); } */ } catch (HttpResponseException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } finally { // If we could be sure that the stream of the entity has been // closed, we wouldn't need this code to release the connection. // However, EntityUtils.toString(...) can throw an exception. // if there is no entity, the connection is already released try { if (entity != null) entity.consumeContent(); // release connection gracefully } catch (IOException e) { System.out.println("in 'finally' " + e.getMessage()); } } return; }
From source file:org.keycloak.testsuite.oauth.LoginStatusIframeEndpointTest.java
@Test public void checkIframe() throws IOException { CookieStore cookieStore = new BasicCookieStore(); try (CloseableHttpClient client = HttpClients.custom().setDefaultCookieStore(cookieStore).build()) { String redirectUri = URLEncoder.encode( suiteContext.getAuthServerInfo().getContextRoot() + "/auth/admin/master/console", "UTF-8"); HttpGet get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/auth?response_type=code&client_id=" + Constants.ADMIN_CONSOLE_CLIENT_ID + "&redirect_uri=" + redirectUri); CloseableHttpResponse response = client.execute(get); String s = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); response.close();/*from w w w . j a v a 2 s . c o m*/ String action = ActionURIUtils.getActionURIFromPageSource(s); HttpPost post = new HttpPost(action); List<NameValuePair> params = new LinkedList<>(); params.add(new BasicNameValuePair("username", "admin")); params.add(new BasicNameValuePair("password", "admin")); post.setHeader("Content-Type", "application/x-www-form-urlencoded"); post.setEntity(new UrlEncodedFormEntity(params)); response = client.execute(post); assertEquals("CP=\"This is not a P3P policy!\"", response.getFirstHeader("P3P").getValue()); Header setIdentityCookieHeader = null; Header setSessionCookieHeader = null; for (Header h : response.getAllHeaders()) { if (h.getName().equals("Set-Cookie")) { if (h.getValue().contains("KEYCLOAK_SESSION")) { setSessionCookieHeader = h; } else if (h.getValue().contains("KEYCLOAK_IDENTITY")) { setIdentityCookieHeader = h; } } } assertNotNull(setIdentityCookieHeader); assertTrue(setIdentityCookieHeader.getValue().contains("HttpOnly")); assertNotNull(setSessionCookieHeader); assertFalse(setSessionCookieHeader.getValue().contains("HttpOnly")); response.close(); Cookie sessionCookie = null; for (Cookie cookie : cookieStore.getCookies()) { if (cookie.getName().equals("KEYCLOAK_SESSION")) { sessionCookie = cookie; break; } } assertNotNull(sessionCookie); get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html"); response = client.execute(get); assertEquals(200, response.getStatusLine().getStatusCode()); s = IOUtils.toString(response.getEntity().getContent(), "UTF-8"); assertTrue(s.contains("function getCookie()")); assertEquals("CP=\"This is not a P3P policy!\"", response.getFirstHeader("P3P").getValue()); response.close(); get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html/init"); response = client.execute(get); assertEquals(403, response.getStatusLine().getStatusCode()); response.close(); get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html/init?" + "client_id=invalid" + "&origin=" + suiteContext.getAuthServerInfo().getContextRoot()); response = client.execute(get); assertEquals(403, response.getStatusLine().getStatusCode()); response.close(); get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html/init?" + "client_id=" + Constants.ADMIN_CONSOLE_CLIENT_ID + "&origin=http://invalid"); response = client.execute(get); assertEquals(403, response.getStatusLine().getStatusCode()); response.close(); get = new HttpGet(suiteContext.getAuthServerInfo().getContextRoot() + "/auth/realms/master/protocol/openid-connect/login-status-iframe.html/init?" + "client_id=" + Constants.ADMIN_CONSOLE_CLIENT_ID + "&origin=" + suiteContext.getAuthServerInfo().getContextRoot()); response = client.execute(get); assertEquals(204, response.getStatusLine().getStatusCode()); response.close(); } }
From source file:me.vertretungsplan.parser.LoginHandler.java
private String handleLogin(Executor executor, CookieStore cookieStore, boolean needsResponse) throws JSONException, IOException, CredentialInvalidException { if (auth == null) return null; if (!(auth instanceof UserPasswordCredential || auth instanceof PasswordCredential)) { throw new IllegalArgumentException("Wrong authentication type"); }//from w ww . j a v a2s . com String login; String password; if (auth instanceof UserPasswordCredential) { login = ((UserPasswordCredential) auth).getUsername(); password = ((UserPasswordCredential) auth).getPassword(); } else { login = null; password = ((PasswordCredential) auth).getPassword(); } JSONObject data = scheduleData.getData(); JSONObject loginConfig = data.getJSONObject(LOGIN_CONFIG); String type = loginConfig.optString(PARAM_TYPE, "post"); switch (type) { case "post": List<Cookie> cookieList = cookieProvider != null ? cookieProvider.getCookies(auth) : null; if (cookieList != null && !needsResponse) { for (Cookie cookie : cookieList) cookieStore.addCookie(cookie); String checkUrl = loginConfig.optString(PARAM_CHECK_URL, null); String checkText = loginConfig.optString(PARAM_CHECK_TEXT, null); if (checkUrl != null && checkText != null) { String response = executor.execute(Request.Get(checkUrl)).returnContent().asString(); if (!response.contains(checkText)) { return null; } } else { return null; } } executor.clearCookies(); Document preDoc = null; if (loginConfig.has(PARAM_PRE_URL)) { String preUrl = loginConfig.getString(PARAM_PRE_URL); String preHtml = executor.execute(Request.Get(preUrl)).returnContent().asString(); preDoc = Jsoup.parse(preHtml); } String postUrl = loginConfig.getString(PARAM_URL); JSONObject loginData = loginConfig.getJSONObject(PARAM_DATA); List<NameValuePair> nvps = new ArrayList<>(); String typo3Challenge = null; if (loginData.has("_hiddeninputs") && preDoc != null) { for (Element hidden : preDoc.select(loginData.getString("_hiddeninputs") + " input[type=hidden]")) { nvps.add(new BasicNameValuePair(hidden.attr("name"), hidden.attr("value"))); if (hidden.attr("name").equals("challenge")) { typo3Challenge = hidden.attr("value"); } } } for (String name : JSONObject.getNames(loginData)) { String value = loginData.getString(name); if (name.equals("_hiddeninputs")) continue; switch (value) { case "_login": value = login; break; case "_password": value = password; break; case "_password_md5": value = DigestUtils.md5Hex(password); break; case "_password_md5_typo3": value = DigestUtils.md5Hex(login + ":" + DigestUtils.md5Hex(password) + ":" + typo3Challenge); break; } nvps.add(new BasicNameValuePair(name, value)); } Request request = Request.Post(postUrl); if (loginConfig.optBoolean("form-data", false)) { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (NameValuePair nvp : nvps) { builder.addTextBody(nvp.getName(), nvp.getValue()); } request.body(builder.build()); } else { request.bodyForm(nvps, Charset.forName("UTF-8")); } String html = executor.execute(request).returnContent().asString(); if (cookieProvider != null) cookieProvider.saveCookies(auth, cookieStore.getCookies()); String checkUrl = loginConfig.optString(PARAM_CHECK_URL, null); String checkText = loginConfig.optString(PARAM_CHECK_TEXT, null); if (checkUrl != null && checkText != null) { String response = executor.execute(Request.Get(checkUrl)).returnContent().asString(); if (response.contains(checkText)) throw new CredentialInvalidException(); } else if (checkText != null) { if (html.contains(checkText)) throw new CredentialInvalidException(); } return html; case "basic": if (login == null) throw new IOException("wrong auth type"); executor.auth(login, password); if (loginConfig.has(PARAM_URL)) { String url = loginConfig.getString(PARAM_URL); if (executor.execute(Request.Get(url)).returnResponse().getStatusLine().getStatusCode() != 200) { throw new CredentialInvalidException(); } } break; case "ntlm": if (login == null) throw new IOException("wrong auth type"); executor.auth(login, password, null, null); if (loginConfig.has(PARAM_URL)) { String url = loginConfig.getString(PARAM_URL); if (executor.execute(Request.Get(url)).returnResponse().getStatusLine().getStatusCode() != 200) { throw new CredentialInvalidException(); } } break; case "fixed": String loginFixed = loginConfig.optString(PARAM_LOGIN, null); String passwordFixed = loginConfig.getString(PARAM_PASSWORD); if (!Objects.equals(loginFixed, login) || !Objects.equals(passwordFixed, password)) { throw new CredentialInvalidException(); } break; } return null; }
From source file:com.nguyenmp.gauchodroid.login.LoginFragment.java
public static void setCookies(Context context, CookieStore cookies) { PersistentCookieStore store = new PersistentCookieStore(context); store.clear();/*from w w w . j a v a 2s .c o m*/ CookieSyncManager.createInstance(context); CookieManager cookieManager = CookieManager.getInstance(); cookieManager.removeAllCookie(); cookieManager.setAcceptCookie(true); if (cookies != null) { for (Cookie cookie : cookies.getCookies()) { store.addCookie(cookie); cookieManager.setCookie(cookie.getDomain(), cookie.getName() + "=" + cookie.getValue()); } } CookieSyncManager.getInstance().sync(); }
From source file:org.apache.http.client.protocol.RequestAddCookies.java
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { Args.notNull(request, "HTTP request"); Args.notNull(context, "HTTP context"); final String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase("CONNECT")) { return;/*from w w w .j av a 2s.c o m*/ } final HttpClientContext clientContext = HttpClientContext.adapt(context); // Obtain cookie store final CookieStore cookieStore = clientContext.getCookieStore(); if (cookieStore == null) { this.log.debug("Cookie store not specified in HTTP context"); return; } // Obtain the registry of cookie specs final Lookup<CookieSpecProvider> registry = clientContext.getCookieSpecRegistry(); if (registry == null) { this.log.debug("CookieSpec registry not specified in HTTP context"); return; } // Obtain the target host, possibly virtual (required) final HttpHost targetHost = clientContext.getTargetHost(); if (targetHost == null) { this.log.debug("Target host not set in the context"); return; } // Obtain the route (required) final RouteInfo route = clientContext.getHttpRoute(); if (route == null) { this.log.debug("Connection route not set in the context"); return; } final RequestConfig config = clientContext.getRequestConfig(); String policy = config.getCookieSpec(); if (policy == null) { policy = CookieSpecs.BEST_MATCH; } if (this.log.isDebugEnabled()) { this.log.debug("CookieSpec selected: " + policy); } URI requestURI = null; if (request instanceof HttpUriRequest) { requestURI = ((HttpUriRequest) request).getURI(); } else { try { requestURI = new URI(request.getRequestLine().getUri()); } catch (final URISyntaxException ignore) { } } final String path = requestURI != null ? requestURI.getPath() : null; final String hostName = targetHost.getHostName(); int port = targetHost.getPort(); if (port < 0) { port = route.getTargetHost().getPort(); } final CookieOrigin cookieOrigin = new CookieOrigin(hostName, port >= 0 ? port : 0, !TextUtils.isEmpty(path) ? path : "/", route.isSecure()); // Get an instance of the selected cookie policy final CookieSpecProvider provider = registry.lookup(policy); if (provider == null) { throw new HttpException("Unsupported cookie policy: " + policy); } final CookieSpec cookieSpec = provider.create(clientContext); // Get all cookies available in the HTTP state final List<Cookie> cookies = new ArrayList<Cookie>(cookieStore.getCookies()); // Find cookies matching the given origin final List<Cookie> matchedCookies = new ArrayList<Cookie>(); final Date now = new Date(); for (final Cookie cookie : cookies) { if (!cookie.isExpired(now)) { if (cookieSpec.match(cookie, cookieOrigin)) { if (this.log.isDebugEnabled()) { this.log.debug("Cookie " + cookie + " match " + cookieOrigin); } matchedCookies.add(cookie); } } else { if (this.log.isDebugEnabled()) { this.log.debug("Cookie " + cookie + " expired"); } } } // Generate Cookie request headers if (!matchedCookies.isEmpty()) { final List<Header> headers = cookieSpec.formatCookies(matchedCookies); for (final Header header : headers) { request.addHeader(header); } } final int ver = cookieSpec.getVersion(); if (ver > 0) { boolean needVersionHeader = false; for (final Cookie cookie : matchedCookies) { if (ver != cookie.getVersion() || !(cookie instanceof SetCookie2)) { needVersionHeader = true; } } if (needVersionHeader) { final Header header = cookieSpec.getVersionHeader(); if (header != null) { // Advertise cookie version support request.addHeader(header); } } } // Stick the CookieSpec and CookieOrigin instances to the HTTP context // so they could be obtained by the response interceptor context.setAttribute(HttpClientContext.COOKIE_SPEC, cookieSpec); context.setAttribute(HttpClientContext.COOKIE_ORIGIN, cookieOrigin); }