use of org.apache.http.client.CookieStore in project wildfly by wildfly.
the class SSOTestBase method executeFormAuthSingleSignOnTest.
/**
* Test single sign-on across two web apps using form based auth
*
* @throws Exception
*/
public static void executeFormAuthSingleSignOnTest(URL serverA, URL serverB, Logger log) throws Exception {
URL warA1 = new URL(serverA, "/war1/");
URL warB2 = new URL(serverB, "/war2/");
// Start by accessing the secured index.html of war1
CookieStore store = new BasicCookieStore();
HttpClient httpclient = TestHttpClientUtils.promiscuousCookieHttpClientBuilder().setDefaultCookieStore(store).disableRedirectHandling().build();
try {
checkAccessDenied(httpclient, warA1 + "index.html");
log.debug("Saw JSESSIONID=" + getSessionIdValueFromState(store));
// Submit the login form
executeFormLogin(httpclient, warA1);
String ssoID = processSSOCookie(store, serverA.toString(), serverB.toString());
log.debug("Saw JSESSIONIDSSO=" + ssoID);
// Now try getting the war2 index using the JSESSIONIDSSO cookie
log.debug("Prepare /war2/index.html get");
checkAccessAllowed(httpclient, warB2 + "index.html");
// Access a secured servlet that calls a secured ejb in war2 to test
// propagation of the SSO identity to the ejb container.
checkAccessAllowed(httpclient, warB2 + "EJBServlet");
// Now try logging out of war2
executeLogout(httpclient, warB2);
} finally {
HttpClientUtils.closeQuietly(httpclient);
}
try {
// Reset Http client
httpclient = HttpClients.createDefault();
// Try accessing war1 again
checkAccessDenied(httpclient, warA1 + "index.html");
// Try accessing war2 again
checkAccessDenied(httpclient, warB2 + "index.html");
} finally {
HttpClientUtils.closeQuietly(httpclient);
}
}
use of org.apache.http.client.CookieStore in project undertow by undertow-io.
the class ServletSessionCrawlerTestCase method testCrawlerSessionUsage.
@Test
public void testCrawlerSessionUsage() throws IOException, InterruptedException {
final PathHandler pathHandler = new PathHandler();
final ServletContainer container = ServletContainer.Factory.newInstance();
DeploymentInfo builder = new DeploymentInfo().setCrawlerSessionManagerConfig(new CrawlerSessionManagerConfig()).setClassLoader(SimpleServletTestCase.class.getClassLoader()).setContextPath("/servletContext").setClassIntrospecter(TestClassIntrospector.INSTANCE).setDeploymentName("servletContext.war").addListener(new ListenerInfo(SessionCookieConfigListener.class)).addServlets(new ServletInfo("servlet", SessionServlet.class).addMapping("/aa/b"));
DeploymentManager manager = container.addDeployment(builder);
manager.deploy();
try {
pathHandler.addPrefixPath(builder.getContextPath(), manager.start());
} catch (ServletException e) {
throw new RuntimeException(e);
}
DefaultServer.setRootHandler(pathHandler);
TestHttpClient client = new TestHttpClient();
client.setCookieStore(new CookieStore() {
@Override
public void addCookie(Cookie cookie) {
}
@Override
public List<Cookie> getCookies() {
return Collections.EMPTY_LIST;
}
@Override
public boolean clearExpired(Date date) {
return false;
}
@Override
public void clear() {
}
});
try {
HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/servletContext/aa/b");
get.addHeader(Headers.USER_AGENT_STRING, "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)");
HttpResponse result = client.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
String response = HttpClientUtils.readResponse(result);
Assert.assertEquals("1", response);
result = client.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
response = HttpClientUtils.readResponse(result);
Assert.assertEquals("2", response);
result = client.execute(get);
Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
response = HttpClientUtils.readResponse(result);
Assert.assertEquals("3", response);
} finally {
client.getConnectionManager().shutdown();
}
}
use of org.apache.http.client.CookieStore in project webmagic by code4craft.
the class HttpClientGenerator method generateCookie.
private void generateCookie(HttpClientBuilder httpClientBuilder, Site site) {
CookieStore cookieStore = new BasicCookieStore();
for (Map.Entry<String, String> cookieEntry : site.getCookies().entrySet()) {
BasicClientCookie cookie = new BasicClientCookie(cookieEntry.getKey(), cookieEntry.getValue());
cookie.setDomain(site.getDomain());
cookieStore.addCookie(cookie);
}
for (Map.Entry<String, Map<String, String>> domainEntry : site.getAllCookies().entrySet()) {
for (Map.Entry<String, String> cookieEntry : domainEntry.getValue().entrySet()) {
BasicClientCookie cookie = new BasicClientCookie(cookieEntry.getKey(), cookieEntry.getValue());
cookie.setDomain(domainEntry.getKey());
cookieStore.addCookie(cookie);
}
}
httpClientBuilder.setDefaultCookieStore(cookieStore);
}
use of org.apache.http.client.CookieStore in project android-instagram by markchang.
the class LoginActivity method doLogin.
public void doLogin(View view) {
CookieStore cookieStore;
// clear cookies
clearCookies();
// gather login info
String password = txtPassword.getText().toString();
String username = txtUsername.getText().toString();
if (Utils.isOnline(getApplicationContext()) == false) {
Toast.makeText(LoginActivity.this, "No connection to Internet.\nTry again later.", Toast.LENGTH_SHORT).show();
Log.i(Utils.TAG, "No internet, failed Login");
return;
}
// create POST
HttpPost httpPost = new HttpPost(Utils.LOGIN_URL);
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("username", username));
postParams.add(new BasicNameValuePair("password", password));
postParams.add(new BasicNameValuePair("device_id", "0000"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(postParams, HTTP.UTF_8));
HttpResponse httpResponse = httpClient.execute(httpPost);
// test result code
if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
Toast.makeText(LoginActivity.this, "Login failed", Toast.LENGTH_SHORT).show();
Log.i(TAG, "Login HTTP status fail");
return;
}
// test json response
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"));
String json = reader.readLine();
JSONTokener jsonTokener = new JSONTokener(json);
JSONObject jsonObject = new JSONObject(jsonTokener);
Log.i(TAG, "JSON: " + jsonObject.toString());
String loginStatus = jsonObject.getString("status");
if (!loginStatus.equals("ok")) {
Toast.makeText(LoginActivity.this, "Login failed", Toast.LENGTH_SHORT).show();
Log.e(TAG, "JSON status not ok: " + jsonObject.getString("status"));
return;
}
}
// save login info so that we can reuse them later
cookieStore = httpClient.getCookieStore();
if (saveLoginInfo(cookieStore, username, password) == true) {
Toast.makeText(LoginActivity.this, "Logged in", Toast.LENGTH_SHORT).show();
openMainActivity();
} else {
Toast.makeText(LoginActivity.this, "Login failed", Toast.LENGTH_SHORT).show();
Log.e(TAG, "Cookie error");
}
} catch (IOException e) {
Log.e(TAG, "HttpPost error: " + e.toString());
Toast.makeText(LoginActivity.this, "Login failed " + e.toString(), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Log.e(TAG, "JSON parse error: " + e.toString());
Toast.makeText(LoginActivity.this, "Result from instagr.am was unexpected: " + e.toString(), Toast.LENGTH_LONG).show();
}
}
use of org.apache.http.client.CookieStore in project openhab1-addons by openhab.
the class Tr064Comm method createTr064HttpClient.
/***
* Creates a apache HTTP Client object, ignoring SSL Exceptions like self signed certificates
* and sets Auth. Scheme to Digest Auth
*
* @param fboxUrl the URL from config file of fbox to connect to
* @return the ready-to-use httpclient for tr064 requests
*/
private CloseableHttpClient createTr064HttpClient(String fboxUrl) {
CloseableHttpClient hc = null;
// Convert URL String from config in easy explotable URI object
URIBuilder uriFbox = null;
try {
uriFbox = new URIBuilder(fboxUrl);
} catch (URISyntaxException e) {
logger.error("Invalid FritzBox URL! {}", e.getMessage());
return null;
}
// Create context of the http client
_httpClientContext = HttpClientContext.create();
CookieStore cookieStore = new BasicCookieStore();
_httpClientContext.setCookieStore(cookieStore);
// SETUP AUTH
// Auth is specific for this target
HttpHost target = new HttpHost(uriFbox.getHost(), uriFbox.getPort(), uriFbox.getScheme());
// Add digest authentication with username/pw from global config
CredentialsProvider credp = new BasicCredentialsProvider();
credp.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(_user, _pw));
// Create AuthCache instance. Manages authentication based on server response
AuthCache authCache = new BasicAuthCache();
// Generate DIGEST scheme object, initialize it and add it to the local auth cache. Digeste is standard for fbox
// auth SOAP
DigestScheme digestAuth = new DigestScheme();
// known from fbox specification
digestAuth.overrideParamter("realm", "HTTPS Access");
// never known at first request
digestAuth.overrideParamter("nonce", "");
authCache.put(target, digestAuth);
// Add AuthCache to the execution context
_httpClientContext.setAuthCache(authCache);
// SETUP SSL TRUST
SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
SSLConnectionSocketFactory sslsf = null;
try {
// accept self signed certs
sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
// dont
sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), null, null, new NoopHostnameVerifier());
// verify
// hostname
// against
// cert
// CN
} catch (Exception ex) {
logger.error(ex.getMessage());
}
// Set timeout values
RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(4000).setConnectTimeout(4000).setConnectionRequestTimeout(4000).build();
// BUILDER
// setup builder with parameters defined before
hc = // set the SSL options which trust every self signed
HttpClientBuilder.create().setSSLSocketFactory(sslsf).setDefaultCredentialsProvider(// set auth options using digest
credp).setDefaultRequestConfig(// set the request config specifying timeout
rc).build();
return hc;
}
Aggregations