List of usage examples for org.apache.http.protocol ExecutionContext HTTP_TARGET_HOST
String HTTP_TARGET_HOST
To view the source code for org.apache.http.protocol ExecutionContext HTTP_TARGET_HOST.
Click Source Link
From source file:org.jboss.as.test.integration.security.loginmodules.negotiation.JBossNegotiateScheme.java
/** * Produces Negotiate authorization Header based on token created by processChallenge. * //from w ww .ja va2s.co m * @param credentials Never used be the Negotiate scheme but must be provided to satisfy common-httpclient API. Credentials * from JAAS will be used instead. * @param request The request being authenticated * * @throws AuthenticationException if authorisation string cannot be generated due to an authentication failure * * @return an Negotiate authorisation Header */ @Override public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context) throws AuthenticationException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (state != State.CHALLENGE_RECEIVED) { throw new IllegalStateException("Negotiation authentication process has not been initiated"); } try { String key = null; if (isProxy()) { key = ExecutionContext.HTTP_PROXY_HOST; } else { key = ExecutionContext.HTTP_TARGET_HOST; } HttpHost host = (HttpHost) context.getAttribute(key); if (host == null) { throw new AuthenticationException("Authentication host is not set " + "in the execution context"); } String authServer; if (!this.stripPort && host.getPort() > 0) { authServer = host.toHostString(); } else { authServer = host.getHostName(); } if (log.isDebugEnabled()) { log.debug("init " + authServer); } /* * Using the SPNEGO OID is the correct method. Kerberos v5 works for IIS but not JBoss. Unwrapping the initial token * when using SPNEGO OID looks like what is described here... * * http://msdn.microsoft.com/en-us/library/ms995330.aspx * * Another helpful URL... * * http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp?topic=/com.ibm.websphere.express.doc/info/exp/ae/ * tsec_SPNEGO_token.html * * Unfortunately SPNEGO is JRE >=1.6. */ /** Try SPNEGO by default, fall back to Kerberos later if error */ negotiationOid = new Oid(SPNEGO_OID); boolean tryKerberos = false; try { GSSManager manager = getManager(); GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE); gssContext = manager.createContext(serverName.canonicalize(negotiationOid), negotiationOid, null, DEFAULT_LIFETIME); gssContext.requestMutualAuth(true); gssContext.requestCredDeleg(true); } catch (GSSException ex) { // BAD MECH means we are likely to be using 1.5, fall back to Kerberos MECH. // Rethrow any other exception. if (ex.getMajor() == GSSException.BAD_MECH) { log.debug("GSSException BAD_MECH, retry with Kerberos MECH"); tryKerberos = true; } else { throw ex; } } if (tryKerberos) { /* Kerberos v5 GSS-API mechanism defined in RFC 1964. */ log.debug("Using Kerberos MECH " + KERBEROS_OID); negotiationOid = new Oid(KERBEROS_OID); GSSManager manager = getManager(); GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE); gssContext = manager.createContext(serverName.canonicalize(negotiationOid), negotiationOid, null, DEFAULT_LIFETIME); gssContext.requestMutualAuth(true); gssContext.requestCredDeleg(true); } if (token == null) { token = new byte[0]; } token = gssContext.initSecContext(token, 0, token.length); if (token == null) { state = State.FAILED; throw new AuthenticationException("GSS security context initialization failed"); } /* * IIS accepts Kerberos and SPNEGO tokens. Some other servers Jboss, Glassfish? seem to only accept SPNEGO. Below * wraps Kerberos into SPNEGO token. */ if (spengoGenerator != null && negotiationOid.toString().equals(KERBEROS_OID)) { token = spengoGenerator.generateSpnegoDERObject(token); } state = State.TOKEN_GENERATED; String tokenstr = new String(Base64.encodeBase64(token, false)); if (log.isDebugEnabled()) { log.debug("Sending response '" + tokenstr + "' back to the auth server"); } return new BasicHeader("Authorization", "Negotiate " + tokenstr); } catch (GSSException gsse) { state = State.FAILED; if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED) throw new InvalidCredentialsException(gsse.getMessage(), gsse); if (gsse.getMajor() == GSSException.NO_CRED) throw new InvalidCredentialsException(gsse.getMessage(), gsse); if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN || gsse.getMajor() == GSSException.OLD_TOKEN) throw new AuthenticationException(gsse.getMessage(), gsse); // other error throw new AuthenticationException(gsse.getMessage()); } catch (IOException ex) { state = State.FAILED; throw new AuthenticationException(ex.getMessage()); } }
From source file:br.ufsc.das.gtscted.shibbauth.Connection.java
public String[] httpGetWithEndpoint(String url) throws IOException { HttpGet httpget = new HttpGet(url); HttpContext context = new BasicHttpContext(); HttpResponse response = httpClient.execute(httpget, context); String responseAsStr = readResponse(response.getEntity().getContent()).toString(); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new IOException(response.getStatusLine().toString()); }/* w ww . j a v a 2 s . c o m*/ HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); String currentUrl = currentHost.toURI() + currentReq.getURI(); URL endpointUrl = new URL(currentUrl); String endpointDomain = "https://" + endpointUrl.getHost(); String[] returnArray = { endpointDomain, responseAsStr }; return returnArray; }
From source file:com.klinker.android.twitter.utils.api_helper.TwitterDMPicHelper.java
public Bitmap getDMPicture(String picUrl, Twitter twitter) { try {//from w ww . ja va 2 s. com AccessToken token = twitter.getOAuthAccessToken(); String oauth_token = token.getToken(); String oauth_token_secret = token.getTokenSecret(); // generate authorization header String get_or_post = "GET"; String oauth_signature_method = "HMAC-SHA1"; String uuid_string = UUID.randomUUID().toString(); uuid_string = uuid_string.replaceAll("-", ""); String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here // get the timestamp Calendar tempcal = Calendar.getInstance(); long ts = tempcal.getTimeInMillis();// get current time in milliseconds String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds // the parameter string must be in alphabetical order, "text" parameter added at end String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0"; String twitter_endpoint = picUrl; String twitter_endpoint_host = picUrl.substring(0, picUrl.indexOf("1.1")).replace("https://", "") .replace("/", ""); String twitter_endpoint_path = picUrl.replace("ton.twitter.com", "").replace("https://", ""); String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string); String oauth_signature = computeSignature(signature_base_string, AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret)); Log.v("talon_dm_image", "endpoint_host: " + twitter_endpoint_host); Log.v("talon_dm_image", "endpoint_path: " + twitter_endpoint_path); String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\""; HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, "HttpCore/1.1"); HttpProtocolParams.setUseExpectContinue(params, false); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() }); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); HttpHost host = new HttpHost(twitter_endpoint_host, 443); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host); SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, null, null); SSLSocketFactory ssf = sslcontext.getSocketFactory(); Socket socket = ssf.createSocket(); socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0); conn.bind(socket, params); BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("GET", twitter_endpoint_path); request2.setParams(params); request2.addHeader("Authorization", authorization_header_string); httpexecutor.preProcess(request2, httpproc, context); HttpResponse response2 = httpexecutor.execute(request2, conn, context); response2.setParams(params); httpexecutor.postProcess(response2, httpproc, context); StatusLine statusLine = response2.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200 || statusCode == 302) { HttpEntity entity = response2.getEntity(); byte[] bytes = EntityUtils.toByteArray(entity); Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); return bitmap; } else { Log.v("talon_dm_image", statusCode + ""); } conn.close(); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.everit.authentication.http.session.ecm.tests.SessionAuthenticationComponentTest.java
private void logoutGet(final HttpContext httpContext) throws ClientProtocolException, IOException { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(logoutUrl); HttpResponse httpResponse = httpClient.execute(httpGet, httpContext); Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, httpResponse.getStatusLine().getStatusCode()); HttpUriRequest currentReq = (HttpUriRequest) httpContext.getAttribute(ExecutionContext.HTTP_REQUEST); HttpHost currentHost = (HttpHost) httpContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST); String currentUrl = (currentReq.getURI().isAbsolute()) ? currentReq.getURI().toString() : (currentHost.toURI() + currentReq.getURI()); Assert.assertEquals(loggedOutUrl, currentUrl); }
From source file:com.predic8.membrane.test.AssertUtils.java
private static DefaultHttpClient getAuthenticatingHttpClient(String host, int port, String user, String pass) { DefaultHttpClient hc = new DefaultHttpClient(); HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.update(new BasicScheme(), creds); }// w ww . j a v a 2 s.co m } } }; hc.addRequestInterceptor(preemptiveAuth, 0); Credentials defaultcreds = new UsernamePasswordCredentials(user, pass); BasicCredentialsProvider bcp = new BasicCredentialsProvider(); bcp.setCredentials(new AuthScope(host, port, AuthScope.ANY_REALM), defaultcreds); hc.setCredentialsProvider(bcp); hc.setCookieStore(new BasicCookieStore()); return hc; }
From source file:com.doculibre.constellio.opensearch.OpenSearchSolrServer.java
public static Element sendGet(String openSearchServerURLStr, Map<String, String> paramsMap) { if (paramsMap == null) { paramsMap = new HashMap<String, String>(); }//from w w w . java2 s.c o m try { HttpParams params = new BasicHttpParams(); for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) { String paramName = (String) it.next(); String paramValue = (String) paramsMap.get(paramName); params.setParameter(paramName, paramValue); } HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, CharSetUtils.UTF_8); HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1"); HttpProtocolParams.setUseExpectContinue(params, true); BasicHttpProcessor httpproc = new BasicHttpProcessor(); // Required protocol interceptors httpproc.addInterceptor(new RequestContent()); httpproc.addInterceptor(new RequestTargetHost()); // Recommended protocol interceptors httpproc.addInterceptor(new RequestConnControl()); httpproc.addInterceptor(new RequestUserAgent()); httpproc.addInterceptor(new RequestExpectContinue()); HttpRequestExecutor httpexecutor = new HttpRequestExecutor(); HttpContext context = new BasicHttpContext(null); URL openSearchServerURL = new URL(openSearchServerURLStr); String host = openSearchServerURL.getHost(); int port = openSearchServerURL.getPort(); if (port == -1) { port = 80; } HttpHost httpHost = new HttpHost(host, port); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, httpHost); try { boolean firstParam = true; for (Iterator<String> it = paramsMap.keySet().iterator(); it.hasNext();) { String paramName = (String) it.next(); String paramValue = (String) paramsMap.get(paramName); if (paramValue != null) { try { paramValue = URLEncoder.encode(paramValue, CharSetUtils.ISO_8859_1); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } if (firstParam) { openSearchServerURLStr += "?"; firstParam = false; } else { openSearchServerURLStr += "&"; } openSearchServerURLStr += paramName + "=" + paramValue; } if (!conn.isOpen()) { Socket socket = new Socket(host, port); conn.bind(socket, params); } BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("GET", openSearchServerURLStr); LOGGER.fine(">> Request URI: " + request.getRequestLine().getUri()); request.setParams(params); httpexecutor.preProcess(request, httpproc, context); HttpResponse response = httpexecutor.execute(request, conn, context); response.setParams(params); httpexecutor.postProcess(response, httpproc, context); LOGGER.fine("<< Response: " + response.getStatusLine()); String entityText = EntityUtils.toString(response.getEntity()); LOGGER.fine(entityText); LOGGER.fine("=============="); if (!connStrategy.keepAlive(response, context)) { conn.close(); } else { LOGGER.fine("Connection kept alive..."); } try { Document xml = DocumentHelper.parseText(entityText); return xml.getRootElement(); } catch (RuntimeException e) { LOGGER.severe("Error caused by text : " + entityText); throw e; } } finally { conn.close(); } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:fr.univsavoie.ltp.client.map.Session.java
/** * Procdure qui s'authentifie sur le serveur REST avec les donnes utilisateurs de faon scuris (protocole HTTPS). * Appeler secureAuth() avant chaque nouvelles requtes HTTP (get, post, ...) *//*from ww w .j a va2 s. co m*/ private void secureAuth() { try { // Instance de SharedPreferences pour lire les donnes dans un fichier SharedPreferences myPrefs = activity.getSharedPreferences("UserPrefs", activity.MODE_WORLD_READABLE); String login = myPrefs.getString("Login", null); String password = myPrefs.getString("Password", null); HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() { public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE); CredentialsProvider credsProvider = (CredentialsProvider) context .getAttribute(ClientContext.CREDS_PROVIDER); HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } }; // Setup a custom SSL Factory object which simply ignore the certificates validation and accept all type of self signed certificates SSLSocketFactory sslFactory = new SimpleSSLSocketFactory(null); sslFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // Enable HTTP parameters HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); // Register the HTTP and HTTPS Protocols. For HTTPS, register our custom SSL Factory object. SchemeRegistry registry = new SchemeRegistry(); // registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); registry.register(new Scheme("https", sslFactory, 443)); // Create a new connection manager using the newly created registry and then create a new HTTP client using this connection manager ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); httpClient = new DefaultHttpClient(ccm, params); CredentialsProvider authCred = new BasicCredentialsProvider(); Credentials creds = new UsernamePasswordCredentials(login, password); authCred.setCredentials(AuthScope.ANY, creds); httpClient.addRequestInterceptor(preemptiveAuth, 0); httpClient.setCredentialsProvider(authCred); } catch (KeyManagementException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } }
From source file:net.kungfoo.grizzly.proxy.impl.ConnectingHandler.java
/** * Triggered when the connection is ready to send an HTTP request. * * @see NHttpClientConnection/* w ww . ja v a2 s .c o m*/ * * @param conn HTTP connection that is ready to send an HTTP request */ public void requestReady(final NHttpClientConnection conn) { System.out.println(conn + " [proxy->origin] request ready"); HttpContext context = conn.getContext(); ProxyProcessingInfo proxyTask = (ProxyProcessingInfo) context.getAttribute(ProxyProcessingInfo.ATTRIB); // TODO: change it to ReentrantLock synchronized (proxyTask) { if (requestReadyValidateConnectionState(proxyTask)) return; HttpRequest request = proxyTask.getRequest(); if (request == null) { throw new IllegalStateException("HTTP request is null"); } requestReadyCleanUpHeaders(request); HttpHost targetHost = proxyTask.getTarget(); try { request.setParams(new DefaultedHttpParams(request.getParams(), this.params)); // Pre-process HTTP request context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost); this.httpProcessor.process(request, context); // and send it to the origin server Request originalRequest = proxyTask.getOriginalRequest(); int length = originalRequest.getContentLength(); if (length > 0) { BasicHttpEntity httpEntity = new BasicHttpEntity(); httpEntity.setContentLength(originalRequest.getContentLengthLong()); /* httpEntity.setContent(((InternalInputBuffer) originalRequest.getInputBuffer()).getInputStream()); ((BasicHttpEntityEnclosingRequest) request).setEntity(httpEntity); */ } conn.submitRequest(request); // Update connection state proxyTask.setOriginState(ConnState.REQUEST_SENT); System.out.println(conn + " [proxy->origin] >> " + request.getRequestLine().toString()); } catch (IOException ex) { shutdownConnection(conn); } catch (HttpException ex) { shutdownConnection(conn); } } }