List of usage examples for org.apache.http.auth AuthScope getHost
public String getHost()
From source file:com.nesscomputing.httpclient.factory.httpclient4.InternalCredentialsProvider.java
@Override public Credentials getCredentials(final AuthScope authScope) { for (final HttpClientAuthProvider authProvider : authProviders) { if (authProvider.acceptRequest(authScope.getScheme(), authScope.getHost(), authScope.getPort(), authScope.getRealm())) { return new Credentials() { @Override/*from ww w. ja v a 2s .c o m*/ public Principal getUserPrincipal() { return new BasicUserPrincipal(authProvider.getUser()); } @Override public String getPassword() { return authProvider.getPassword(); } }; } } return null; }
From source file:com.mooregreatsoftware.gitprocess.lib.CredentialHelperCredentialsProvider.java
@Nullable @Override/* w w w .j a v a2s . co m*/ @SuppressWarnings("override.return.invalid") public Credentials getCredentials(AuthScope authscope) { if (authscope == null) return null; @SuppressWarnings("argument.type.incompatible") URI uri = e(() -> new URI(authscope.getScheme(), null, authscope.getHost(), authscope.getPort(), null, null, null)); final String credentialHelper = remoteConfig.credentialHelper(uri); if (credentialHelper == null) return null; final String progName; if (credentialHelper.startsWith("/")) { progName = credentialHelper; } else { progName = "git-credential-" + credentialHelper; } return null; }
From source file:com.android.sdklib.internal.repository.UrlOpener.java
private static InputStream openWithHttpClient(String url, ITaskMonitor monitor) throws IOException, ClientProtocolException, CanceledByUserException { UserCredentials result = null;/*from w w w. j av a2 s. co m*/ String realm = null; // use the simple one final DefaultHttpClient httpClient = new DefaultHttpClient(); // create local execution context HttpContext localContext = new BasicHttpContext(); HttpGet httpget = new HttpGet(url); // retrieve local java configured network in case there is the need to // authenticate a proxy ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner( httpClient.getConnectionManager().getSchemeRegistry(), ProxySelector.getDefault()); httpClient.setRoutePlanner(routePlanner); // Set preference order for authentication options. // In particular, we don't add AuthPolicy.SPNEGO, which is given preference over NTLM in // servers that support both, as it is more secure. However, we don't seem to handle it // very well, so we leave it off the list. // See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/authentication.html for // more info. List<String> authpref = new ArrayList<String>(); authpref.add(AuthPolicy.BASIC); authpref.add(AuthPolicy.DIGEST); authpref.add(AuthPolicy.NTLM); httpClient.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref); httpClient.getParams().setParameter(AuthPNames.TARGET_AUTH_PREF, authpref); boolean trying = true; // loop while the response is being fetched while (trying) { // connect and get status code HttpResponse response = httpClient.execute(httpget, localContext); int statusCode = response.getStatusLine().getStatusCode(); // check whether any authentication is required AuthState authenticationState = null; if (statusCode == HttpStatus.SC_UNAUTHORIZED) { // Target host authentication required authenticationState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); } if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) { // Proxy authentication required authenticationState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); } if (statusCode == HttpStatus.SC_OK) { // in case the status is OK and there is a realm and result, // cache it if (realm != null && result != null) { sRealmCache.put(realm, result); } } // there is the need for authentication if (authenticationState != null) { // get scope and realm AuthScope authScope = authenticationState.getAuthScope(); // If the current realm is different from the last one it means // a pass was performed successfully to the last URL, therefore // cache the last realm if (realm != null && !realm.equals(authScope.getRealm())) { sRealmCache.put(realm, result); } realm = authScope.getRealm(); // in case there is cache for this Realm, use it to authenticate if (sRealmCache.containsKey(realm)) { result = sRealmCache.get(realm); } else { // since there is no cache, request for login and password result = monitor.displayLoginCredentialsPrompt("Site Authentication", "Please login to the following domain: " + realm + "\n\nServer requiring authentication:\n" + authScope.getHost()); if (result == null) { throw new CanceledByUserException("User canceled login dialog."); } } // retrieve authentication data String user = result.getUserName(); String password = result.getPassword(); String workstation = result.getWorkstation(); String domain = result.getDomain(); // proceed in case there is indeed a user if (user != null && user.length() > 0) { Credentials credentials = new NTCredentials(user, password, workstation, domain); httpClient.getCredentialsProvider().setCredentials(authScope, credentials); trying = true; } else { trying = false; } } else { trying = false; } HttpEntity entity = response.getEntity(); if (entity != null) { if (trying) { // in case another pass to the Http Client will be performed, close the entity. entity.getContent().close(); } else { // since no pass to the Http Client is needed, retrieve the // entity's content. // Note: don't use something like a BufferedHttpEntity since it would consume // all content and store it in memory, resulting in an OutOfMemory exception // on a large download. return new FilterInputStream(entity.getContent()) { @Override public void close() throws IOException { super.close(); // since Http Client is no longer needed, close it httpClient.getConnectionManager().shutdown(); } }; } } } // We get here if we did not succeed. Callers do not expect a null result. httpClient.getConnectionManager().shutdown(); throw new FileNotFoundException(url); }
From source file:org.apache.taverna.activities.rest.RESTActivityCredentialsProvider.java
@Override public Credentials getCredentials(AuthScope authscope) { logger.info("Looking for credentials for: Host - " + authscope.getHost() + ";" + "Port - " + authscope.getPort() + ";" + "Realm - " + authscope.getRealm() + ";" + "Authentication scheme - " + authscope.getScheme());// w w w. j a v a2 s .co m // Ask the superclass first Credentials creds = super.getCredentials(authscope); if (creds != null) { /* * We have used setCredentials() on this class (for proxy host, * port, username,password) just before we invoked the http request, * which will then pick the proxy credentials up from here. */ return creds; } // Otherwise, ask Credential Manager if is can provide the credential String AUTHENTICATION_REQUEST_MSG = "This REST service requires authentication in " + authscope.getRealm(); try { UsernamePassword credentials = null; /* * if port is 80 - use HTTP, don't append port if port is 443 - use * HTTPS, don't append port any other port - append port + do 2 * tests: * * --- test HTTPS first has...() * --- if not there, do get...() for HTTP (which will save the thing) * * (save both these entries for HTTP + HTTPS if not there) */ // build the service URI back to front StringBuilder serviceURI = new StringBuilder(); serviceURI.insert(0, "/#" + URLEncoder.encode(authscope.getRealm(), "UTF-16")); if (authscope.getPort() != DEFAULT_HTTP_PORT && authscope.getPort() != DEFAULT_HTTPS_PORT) { // non-default port - add port name to the URI serviceURI.insert(0, ":" + authscope.getPort()); } serviceURI.insert(0, authscope.getHost()); serviceURI.insert(0, "://"); // now the URI is complete, apart from the protocol name if (authscope.getPort() == DEFAULT_HTTP_PORT || authscope.getPort() == DEFAULT_HTTPS_PORT) { // definitely HTTP or HTTPS serviceURI.insert(0, (authscope.getPort() == DEFAULT_HTTP_PORT ? HTTP_PROTOCOL : HTTPS_PROTOCOL)); // request credentials from CrendentialManager credentials = credentialManager.getUsernameAndPasswordForService(URI.create(serviceURI.toString()), true, AUTHENTICATION_REQUEST_MSG); } else { /* * non-default port - will need to try both HTTP and HTTPS; just * check (no pop-up will be shown) if credentials are there - * one protocol that matched will be used; if */ if (credentialManager .hasUsernamePasswordForService(URI.create(HTTPS_PROTOCOL + serviceURI.toString()))) { credentials = credentialManager.getUsernameAndPasswordForService( URI.create(HTTPS_PROTOCOL + serviceURI.toString()), true, AUTHENTICATION_REQUEST_MSG); } else if (credentialManager .hasUsernamePasswordForService(URI.create(HTTP_PROTOCOL + serviceURI.toString()))) { credentials = credentialManager.getUsernameAndPasswordForService( URI.create(HTTP_PROTOCOL + serviceURI.toString()), true, AUTHENTICATION_REQUEST_MSG); } else { /* * Neither of the two options succeeded, request details with a * popup for HTTP... */ credentials = credentialManager.getUsernameAndPasswordForService( URI.create(HTTP_PROTOCOL + serviceURI.toString()), true, AUTHENTICATION_REQUEST_MSG); /* * ...then save a second entry with HTTPS protocol (if the * user has chosen to save the credentials) */ if (credentials != null && credentials.isShouldSave()) { credentialManager.addUsernameAndPasswordForService(credentials, URI.create(HTTPS_PROTOCOL + serviceURI.toString())); } } } if (credentials != null) { logger.info("Credentials obtained successfully"); return new RESTActivityCredentials(credentials.getUsername(), credentials.getPasswordAsString()); } } catch (Exception e) { logger.error("Unexpected error while trying to obtain user's credential from CredentialManager", e); } // error or nothing was found logger.info("Credentials not found - the user must have refused to enter them."); return null; }
From source file:org.gbif.utils.PreemptiveAuthenticationInterceptor.java
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { LOG.debug(request.getRequestLine().toString()); 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 not auth scheme has been initialized yet if (authState.getAuthScheme() == null && credsProvider != null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); // Obtain credentials matching the target host Credentials creds = credsProvider.getCredentials(authScope); // If found, generate BasicScheme preemptively if (creds != null) { LOG.debug("Authentication used for scope " + authScope.getHost()); authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); }// w ww . j av a 2 s . c o m } }
From source file:ucar.unidata.util.AccountManager.java
/** * _more_//www . j ava 2 s .c o m * * @param scope _more_ * * @return _more_ */ public Credentials getCredentialsnew(AuthScope scope) { //String host, int port, boolean proxy String host = scope.getHost(); int port = scope.getPort(); String realm = scope.getRealm(); // public Credentials getCredentials(AuthScheme scheme, String host, // int port, boolean proxy) // throws InvalidCredentialsException { if (scope == null) { throw new IllegalArgumentException("Null scope"); } /* //TODO: check if the scheme in the auth is rfc26217 if ( !(scheme instanceof RFC2617Scheme)) { throw new InvalidCredentialsException( "Unsupported authentication scheme: " + scheme.getSchemeName()); } */ String key = host + realm; // System.err.println ("got auth call " + key); UserInfo userInfo = getUserNamePassword(key, "The server " + host + ":" + port + " requires a username/password"); if (userInfo == null) { return null; } return new UsernamePasswordCredentials(userInfo.getUserId(), userInfo.getPassword()); }
From source file:org.openiot.gsn.http.rest.PushRemoteWrapper.java
public DataField[] registerAndGetStructure() throws IOException, ClassNotFoundException { // Create the POST request HttpPost httpPost = new HttpPost(initParams.getRemoteContactPointEncoded(lastReceivedTimestamp)); // Add the POST parameters httpPost.setEntity(new UrlEncodedFormEntity(postParameters, HTTP.UTF_8)); //// w w w .ja va2 s.c o m httpPost.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE); // Create local execution context HttpContext localContext = new BasicHttpContext(); // NotificationRegistry.getInstance().addNotification(uid, this); int tries = 0; AuthState authState = null; // while (tries < 2) { tries++; HttpResponse response = null; try { // Execute the POST request response = httpclient.execute(httpPost, localContext); // int sc = response.getStatusLine().getStatusCode(); // if (sc == HttpStatus.SC_OK) { logger.debug(new StringBuilder().append("Wants to consume the structure packet from ") .append(initParams.getRemoteContactPoint())); structure = (DataField[]) XSTREAM.fromXML(response.getEntity().getContent()); logger.debug("Connection established for: " + initParams.getRemoteContactPoint()); break; } else { if (sc == HttpStatus.SC_UNAUTHORIZED) authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); // Target host authentication required else if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); // Proxy authentication required else { logger.error(new StringBuilder().append("Unexpected POST status code returned: ").append(sc) .append("\nreason: ").append(response.getStatusLine().getReasonPhrase())); } if (authState != null) { if (initParams.getUsername() == null || (tries > 1 && initParams.getUsername() != null)) { logger.error("A valid username/password required to connect to the remote host: " + initParams.getRemoteContactPoint()); } else { AuthScope authScope = authState.getAuthScope(); logger.warn(new StringBuilder().append("Setting Credentials for host: ") .append(authScope.getHost()).append(":").append(authScope.getPort())); Credentials creds = new UsernamePasswordCredentials(initParams.getUsername(), initParams.getPassword()); httpclient.getCredentialsProvider().setCredentials(authScope, creds); } } } } catch (RuntimeException ex) { // In case of an unexpected exception you may want to abort // the HTTP request in order to shut down the underlying // connection and release it back to the connection manager. logger.warn("Aborting the HTTP POST request."); httpPost.abort(); throw ex; } finally { if (response != null && response.getEntity() != null) { response.getEntity().consumeContent(); } } } if (structure == null) throw new RuntimeException("Cannot connect to the remote host."); return structure; }
From source file:org.openiot.gsn.http.rest.RestRemoteWrapper.java
public DataField[] connectToRemote() throws IOException, ClassNotFoundException { // Create the GET request HttpGet httpget = new HttpGet(initParams.getRemoteContactPointEncoded(lastReceivedTimestamp)); // Create local execution context HttpContext localContext = new BasicHttpContext(); ////ww w . j a va 2 s. co m structure = null; int tries = 0; AuthState authState = null; // if (inputStream != null) { try { if (response != null && response.getEntity() != null) { response.getEntity().consumeContent(); } inputStream.close(); inputStream = null; } catch (Exception e) { logger.debug(e.getMessage(), e); } } // while (tries < 2) { tries++; try { // Execute the GET request response = httpclient.execute(httpget, localContext); // int sc = response.getStatusLine().getStatusCode(); // if (sc == HttpStatus.SC_OK) { logger.debug(new StringBuilder().append("Wants to consume the structure packet from ") .append(initParams.getRemoteContactPoint())); inputStream = XSTREAM.createObjectInputStream(response.getEntity().getContent()); structure = (DataField[]) inputStream.readObject(); logger.warn("Connection established for: " + initParams.getRemoteContactPoint()); break; } else { if (sc == HttpStatus.SC_UNAUTHORIZED) authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); // Target host authentication required else if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); // Proxy authentication required else { logger.error(new StringBuilder().append("Unexpected GET status code returned: ").append(sc) .append("\nreason: ").append(response.getStatusLine().getReasonPhrase())); } if (authState != null) { if (initParams.getUsername() == null || (tries > 1 && initParams.getUsername() != null)) { logger.error("A valid username/password required to connect to the remote host: " + initParams.getRemoteContactPoint()); } else { AuthScope authScope = authState.getAuthScope(); logger.warn(new StringBuilder().append("Setting Credentials for host: ") .append(authScope.getHost()).append(":").append(authScope.getPort())); Credentials creds = new UsernamePasswordCredentials(initParams.getUsername(), initParams.getPassword()); httpclient.getCredentialsProvider().setCredentials(authScope, creds); } } } } catch (RuntimeException ex) { // In case of an unexpected exception you may want to abort // the HTTP request in order to shut down the underlying // connection and release it back to the connection manager. logger.warn("Aborting the HTTP GET request."); httpget.abort(); throw ex; } finally { if (structure == null) { if (response != null && response.getEntity() != null) { response.getEntity().consumeContent(); } } } } if (structure == null) throw new RuntimeException("Cannot connect to the remote host: " + initParams.getRemoteContactPoint()); return structure; }
From source file:gsn.http.rest.RestRemoteWrapper.java
public DataField[] connectToRemote() throws IOException, ClassNotFoundException { // Create the GET request HttpGet httpget = new HttpGet(initParams.getRemoteContactPointEncoded(lastReceivedTimestamp)); // Create local execution context HttpContext localContext = new BasicHttpContext(); ////from w ww. j ava 2s . c o m structure = null; int tries = 0; AuthState authState = null; // if (inputStream != null) { try { if (response != null && response.getEntity() != null) { response.getEntity().consumeContent(); } inputStream.close(); inputStream = null; } catch (Exception e) { logger.debug(e.getMessage(), e); } } // while (tries < 2) { tries++; try { // Execute the GET request response = httpclient.execute(httpget, localContext); // int sc = response.getStatusLine().getStatusCode(); // if (sc == HttpStatus.SC_OK) { logger.debug(new StringBuilder().append("Wants to consume the structure packet from ") .append(initParams.getRemoteContactPoint()).toString()); inputStream = XSTREAM.createObjectInputStream(response.getEntity().getContent()); structure = (DataField[]) inputStream.readObject(); logger.warn("Connection established for: " + initParams.getRemoteContactPoint()); break; } else { if (sc == HttpStatus.SC_UNAUTHORIZED) authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE); // Target host authentication required else if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE); // Proxy authentication required else { logger.error(new StringBuilder().append("Unexpected GET status code returned: ").append(sc) .append("\nreason: ").append(response.getStatusLine().getReasonPhrase()) .toString()); } if (authState != null) { if (initParams.getUsername() == null || (tries > 1 && initParams.getUsername() != null)) { logger.error("A valid username/password required to connect to the remote host: " + initParams.getRemoteContactPoint()); } else { AuthScope authScope = authState.getAuthScope(); logger.warn(new StringBuilder().append("Setting Credentials for host: ") .append(authScope.getHost()).append(":").append(authScope.getPort()) .toString()); Credentials creds = new UsernamePasswordCredentials(initParams.getUsername(), initParams.getPassword()); httpclient.getCredentialsProvider().setCredentials(authScope, creds); } } } } catch (RuntimeException ex) { // In case of an unexpected exception you may want to abort // the HTTP request in order to shut down the underlying // connection and release it back to the connection manager. logger.warn("Aborting the HTTP GET request."); httpget.abort(); throw ex; } finally { if (structure == null) { if (response != null && response.getEntity() != null) { response.getEntity().consumeContent(); } } } } if (structure == null) throw new RuntimeException("Cannot connect to the remote host: " + initParams.getRemoteContactPoint()); return structure; }
From source file:org.codelibs.fess.crawler.extractor.impl.ApiExtractor.java
@PostConstruct public void init() { if (logger.isDebugEnabled()) { logger.debug("Initializing " + ApiExtractor.class.getName()); }/*from ww w . ja va 2s. c om*/ // httpclient final org.apache.http.client.config.RequestConfig.Builder requestConfigBuilder = RequestConfig.custom(); final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); final Integer connectionTimeoutParam = connectionTimeout; if (connectionTimeoutParam != null) { requestConfigBuilder.setConnectTimeout(connectionTimeoutParam); } final Integer soTimeoutParam = soTimeout; if (soTimeoutParam != null) { requestConfigBuilder.setSocketTimeout(soTimeoutParam); } // AuthSchemeFactory final RegistryBuilder<AuthSchemeProvider> authSchemeProviderBuilder = RegistryBuilder.create(); // @SuppressWarnings("unchecked") final Map<String, AuthSchemeProvider> factoryMap = authSchemeProviderMap; if (factoryMap != null) { for (final Map.Entry<String, AuthSchemeProvider> entry : factoryMap.entrySet()) { authSchemeProviderBuilder.register(entry.getKey(), entry.getValue()); } } // user agent if (StringUtil.isNotBlank(userAgent)) { httpClientBuilder.setUserAgent(userAgent); } // Authentication final Authentication[] siteCredentialList = new Authentication[0]; for (final Authentication authentication : siteCredentialList) { final AuthScope authScope = authentication.getAuthScope(); credentialsProvider.setCredentials(authScope, authentication.getCredentials()); final AuthScheme authScheme = authentication.getAuthScheme(); if (authScope.getHost() != null && authScheme != null) { final HttpHost targetHost = new HttpHost(authScope.getHost(), authScope.getPort()); authCache.put(targetHost, authScheme); } } httpClientContext.setAuthCache(authCache); httpClientContext.setCredentialsProvider(credentialsProvider); // Request Header final RequestHeader[] requestHeaders = { new RequestHeader("enctype", "multipart/form-data") }; for (final RequestHeader requestHeader : requestHeaders) { if (requestHeader.isValid()) { requestHeaderList.add(new BasicHeader(requestHeader.getName(), requestHeader.getValue())); } } final CloseableHttpClient closeableHttpClient = httpClientBuilder .setDefaultRequestConfig(requestConfigBuilder.build()).build(); if (!httpClientPropertyMap.isEmpty()) { final BeanDesc beanDesc = BeanDescFactory.getBeanDesc(closeableHttpClient.getClass()); for (final Map.Entry<String, Object> entry : httpClientPropertyMap.entrySet()) { final String propertyName = entry.getKey(); if (beanDesc.hasPropertyDesc(propertyName)) { final PropertyDesc propertyDesc = beanDesc.getPropertyDesc(propertyName); propertyDesc.setValue(closeableHttpClient, entry.getValue()); } else { logger.warn("DefaultHttpClient does not have " + propertyName + "."); } } } httpClient = closeableHttpClient; }