org.apache.commons.httpclient.auth.AuthScope Java Examples

The following examples show how to use org.apache.commons.httpclient.auth.AuthScope. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpTemplateDownloader.java    From cloudstack with Apache License 2.0 7 votes vote down vote up
private void checkCredentials(String user, String password) {
    try {
        Pair<String, Integer> hostAndPort = UriUtils.validateUrl(downloadUrl);
        if ((user != null) && (password != null)) {
            client.getParams().setAuthenticationPreemptive(true);
            Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
            client.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds);
            s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second());
        } else {
            s_logger.info("No credentials configured for host=" + hostAndPort.first() + ":" + hostAndPort.second());
        }
    } catch (IllegalArgumentException iae) {
        errorString = iae.getMessage();
        status = TemplateDownloader.Status.UNRECOVERABLE_ERROR;
        inited = false;
    }
}
 
Example #2
Source File: CredentialsUtils.java    From httpclientAuthHelper with Apache License 2.0 7 votes vote down vote up
public static void setNTLMCredentials(HttpClient httpClient, UsernamePasswordCredentials credentials,
                                      String domain) {
    initNTLMv2();

    String localHostName;
    try {
        localHostName = Inet4Address.getLocalHost().getHostName();
    } catch (Exception e) {
        localHostName = "";
    }

    AuthScope authscope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
    httpClient.getState().setCredentials(
            authscope,
            new NTCredentials(
                    credentials.getUserName(),
                    credentials.getPassword(),
                    localHostName, domain));
}
 
Example #3
Source File: DavGatewayHttpClientFacade.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Enable NTLM authentication on http client
 *
 * @param httpClient HttpClient instance
 */
public static void addNTLM(HttpClient httpClient) {
    // disable preemptive authentication
    httpClient.getParams().setParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, false);

    ArrayList<String> authPrefs = new ArrayList<>();
    authPrefs.add(AuthPolicy.NTLM);
    authPrefs.add(AuthPolicy.DIGEST);
    authPrefs.add(AuthPolicy.BASIC);
    httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

    // make sure NTLM is always active
    needNTLM = true;

    // separate domain from username in credentials
    AuthScope authScope = new AuthScope(null, -1);
    NTCredentials credentials = (NTCredentials) httpClient.getState().getCredentials(authScope);
    if (credentials != null && (credentials.getDomain() == null || credentials.getDomain().isEmpty())) {
        setCredentials(httpClient, credentials.getUserName(), credentials.getPassword());
    }
}
 
Example #4
Source File: RORClientTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void createClient_WithoutCredentials() throws Exception {
	// given
	System.setProperty(HTTPS_PROXY_HOST, HTTPS_PROXY_HOST_VALUE);
	System.setProperty(HTTPS_PROXY_PORT, HTTPS_PROXY_PORT_VALUE);

	// when
	HttpClient client = vdcClient.createHttpClient();

	// then
	assertEquals(HTTPS_PROXY_HOST_VALUE, client.getHostConfiguration()
			.getProxyHost());
	assertEquals(HTTPS_PROXY_PORT_VALUE,
			String.valueOf(client.getHostConfiguration().getProxyPort()));
	assertNull(client.getState().getProxyCredentials(AuthScope.ANY));

}
 
Example #5
Source File: RORClientTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void createClient_WithEmptyCredentials() throws Exception {
	// given
	System.setProperty(HTTPS_PROXY_HOST, HTTPS_PROXY_HOST_VALUE);
	System.setProperty(HTTPS_PROXY_PORT, HTTPS_PROXY_PORT_VALUE);
	System.setProperty(HTTPS_PROXY_USER, "");
	System.setProperty(HTTPS_PROXY_PASSWORD, "");

	// when
	HttpClient client = vdcClient.createHttpClient();

	// then
	assertEquals(HTTPS_PROXY_HOST_VALUE, client.getHostConfiguration()
			.getProxyHost());
	assertEquals(HTTPS_PROXY_PORT_VALUE,
			String.valueOf(client.getHostConfiguration().getProxyPort()));
	assertNull(client.getState().getProxyCredentials(AuthScope.ANY));

}
 
Example #6
Source File: RORClientTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void createClient() throws Exception {
	// given
	System.setProperty(HTTPS_PROXY_HOST, HTTPS_PROXY_HOST_VALUE);
	System.setProperty(HTTPS_PROXY_PORT, HTTPS_PROXY_PORT_VALUE);
	System.setProperty(HTTPS_PROXY_USER, HTTPS_PROXY_USER_VALUE);
	System.setProperty(HTTPS_PROXY_PASSWORD, HTTPS_PROXY_PASSWORD_VALUE);
	Credentials proxyCredentials = new UsernamePasswordCredentials(
			HTTPS_PROXY_USER_VALUE, HTTPS_PROXY_PASSWORD_VALUE);
	AuthScope authScope = new AuthScope(HTTPS_PROXY_HOST_VALUE,
			Integer.parseInt(HTTPS_PROXY_PORT_VALUE));

	// when
	HttpClient client = vdcClient.createHttpClient();

	// then
	assertEquals(HTTPS_PROXY_HOST_VALUE, client.getHostConfiguration()
			.getProxyHost());
	assertEquals(HTTPS_PROXY_PORT_VALUE,
			String.valueOf(client.getHostConfiguration().getProxyPort()));
	assertEquals(proxyCredentials,
			client.getState().getProxyCredentials(authScope));

}
 
Example #7
Source File: PortFactory.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the content under the given URL with username and passwort
 * authentication.
 * 
 * @param url
 * @param username
 * @param password
 * @return
 * @throws IOException
 */
private static byte[] getUrlContent(URL url, String username,
        String password) throws IOException {
    final HttpClient client = new HttpClient();

    // Set credentials:
    client.getParams().setAuthenticationPreemptive(true);
    final Credentials credentials = new UsernamePasswordCredentials(
            username, password);
    client.getState()
            .setCredentials(
                    new AuthScope(url.getHost(), url.getPort(),
                            AuthScope.ANY_REALM), credentials);

    // Retrieve content:
    final GetMethod method = new GetMethod(url.toString());
    final int status = client.executeMethod(method);
    if (status != HttpStatus.SC_OK) {
        throw new IOException("Error " + status + " while retrieving "
                + url);
    }
    return method.getResponseBody();
}
 
Example #8
Source File: HttpClientFactory.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * A HttpClient with basic authentication and no host or port setting. Can only be used to retrieve absolute URLs
 * 
 * @param user
 *            can be NULL
 * @param password
 *            can be NULL
 * @return HttpClient
 */
public static HttpClient getHttpClientInstance(String user, String password) {
    HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    HttpConnectionParams params = connectionManager.getParams();
    // wait max 10 seconds to establish connection
    params.setConnectionTimeout(10000);
    // a read() call on the InputStream associated with this Socket
    // will block for only this amount
    params.setSoTimeout(10000);
    HttpClient c = new HttpClient(connectionManager);

    // use basic authentication if available
    if (user != null && user.length() > 0) {
        AuthScope authScope = new AuthScope(null, -1, null);
        Credentials credentials = new UsernamePasswordCredentials(user, password);
        c.getState().setCredentials(authScope, credentials);
    }
    return c;
}
 
Example #9
Source File: RORClientTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void createClient_MissingPassword() throws Exception {
	// given
	System.setProperty(HTTPS_PROXY_HOST, HTTPS_PROXY_HOST_VALUE);
	System.setProperty(HTTPS_PROXY_PORT, HTTPS_PROXY_PORT_VALUE);
	System.setProperty(HTTPS_PROXY_USER, HTTPS_PROXY_USER_VALUE);

	// when
	HttpClient client = vdcClient.createHttpClient();

	// then
	assertEquals(HTTPS_PROXY_HOST_VALUE, client.getHostConfiguration()
			.getProxyHost());
	assertEquals(HTTPS_PROXY_PORT_VALUE,
			String.valueOf(client.getHostConfiguration().getProxyPort()));
	assertNull(client.getState().getProxyCredentials(AuthScope.ANY));
}
 
Example #10
Source File: RORClientTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void createClient_MissingUser() throws Exception {
	// given
	System.setProperty(HTTPS_PROXY_HOST, HTTPS_PROXY_HOST_VALUE);
	System.setProperty(HTTPS_PROXY_PORT, HTTPS_PROXY_PORT_VALUE);
	System.setProperty(HTTPS_PROXY_USER, HTTPS_PROXY_USER_VALUE);

	// when
	HttpClient client = vdcClient.createHttpClient();

	// then
	assertEquals(HTTPS_PROXY_HOST_VALUE, client.getHostConfiguration()
			.getProxyHost());
	assertEquals(HTTPS_PROXY_PORT_VALUE,
			String.valueOf(client.getHostConfiguration().getProxyPort()));
	assertNull(client.getState().getProxyCredentials(AuthScope.ANY));
}
 
Example #11
Source File: HttpClientFactory.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * A HttpClient with basic authentication and no host or port setting. Can only be used to retrieve absolute URLs
 * 
 * @param user
 *            can be NULL
 * @param password
 *            can be NULL
 * @return HttpClient
 */
public static HttpClient getHttpClientInstance(String user, String password) {
    HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    HttpConnectionParams params = connectionManager.getParams();
    // wait max 10 seconds to establish connection
    params.setConnectionTimeout(10000);
    // a read() call on the InputStream associated with this Socket
    // will block for only this amount
    params.setSoTimeout(10000);
    HttpClient c = new HttpClient(connectionManager);

    // use basic authentication if available
    if (user != null && user.length() > 0) {
        AuthScope authScope = new AuthScope(null, -1, null);
        Credentials credentials = new UsernamePasswordCredentials(user, password);
        c.getState().setCredentials(authScope, credentials);
    }
    return c;
}
 
Example #12
Source File: RORClientTest.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void createClient_NFE() throws Exception {
	// given
	System.setProperty(HTTPS_PROXY_HOST, HTTPS_PROXY_HOST_VALUE);
	System.setProperty(HTTPS_PROXY_PORT, "");
	System.setProperty(HTTPS_PROXY_USER, HTTPS_PROXY_PASSWORD_VALUE);
	System.setProperty(HTTPS_PROXY_PASSWORD, HTTPS_PROXY_PASSWORD_VALUE);

	// when
	HttpClient client = vdcClient.createHttpClient();

	// then
	assertNull(client.getHostConfiguration().getProxyHost());
	assertEquals(-1, client.getHostConfiguration().getProxyPort());
	assertNull(client.getState().getProxyCredentials(AuthScope.ANY));
}
 
Example #13
Source File: Http.java    From anthelion with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an authentication scope for the specified
 * <code>host</code>, <code>port</code>, <code>realm</code> and
 * <code>scheme</code>.
 *
 * @param host    Host name or address.
 * @param port    Port number.
 * @param realm   Authentication realm.
 * @param scheme  Authentication scheme.
 */
private static AuthScope getAuthScope(String host, int port,
    String realm, String scheme) {
  
  if (host.length() == 0)
    host = null;

  if (port < 0)
    port = -1;

  if (realm.length() == 0)
    realm = null;

  if (scheme.length() == 0)
    scheme = null;

  return new AuthScope(host, port, realm, scheme);
}
 
Example #14
Source File: BasicAuthLoader.java    From development with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves the content under the given URL with username and passwort
 * authentication.
 * 
 * @param url
 *            the URL to read
 * @param username
 * @param password
 * @return the read content.
 * @throws IOException
 *             if an I/O exception occurs.
 */
private static byte[] getUrlContent(URL url, String username,
        String password) throws IOException {
    final HttpClient client = new HttpClient();

    // Set credentials:
    client.getParams().setAuthenticationPreemptive(true);
    final Credentials credentials = new UsernamePasswordCredentials(
            username, password);
    client.getState()
            .setCredentials(
                    new AuthScope(url.getHost(), url.getPort(),
                            AuthScope.ANY_REALM), credentials);

    // Retrieve content:
    final GetMethod method = new GetMethod(url.toString());
    final int status = client.executeMethod(method);
    if (status != HttpStatus.SC_OK) {
        throw new IOException("Error " + status + " while retrieving "
                + url);
    }
    return method.getResponseBody();
}
 
Example #15
Source File: TlsTunnelBuilder.java    From jframe with Apache License 2.0 6 votes vote down vote up
private Socket AuthenticateProxy(ConnectMethod method, ProxyClient client, 
        String proxyHost, int proxyPort, 
        String proxyUsername, String proxyPassword) throws IOException {   
    if(method.getProxyAuthState().getAuthScheme().getSchemeName().equalsIgnoreCase("ntlm")) {
        // If Auth scheme is NTLM, set NT credentials with blank host and domain name
        client.getState().setProxyCredentials(new AuthScope(proxyHost, proxyPort), 
                        new NTCredentials(proxyUsername, proxyPassword,"",""));
    } else {
        // If Auth scheme is Basic/Digest, set regular Credentials
        client.getState().setProxyCredentials(new AuthScope(proxyHost, proxyPort), 
                new UsernamePasswordCredentials(proxyUsername, proxyPassword));
    }
    
    ProxyClient.ConnectResponse response = client.connect();
    Socket socket = response.getSocket();
    
    if (socket == null) {
        method = response.getConnectMethod();
        throw new ProtocolException("Proxy Authentication failed. Socket not created: " 
                + method.getStatusLine());
    }
    return socket;
}
 
Example #16
Source File: UriUtils.java    From cosmic with Apache License 2.0 6 votes vote down vote up
public static InputStream getInputStreamFromUrl(final String url, final String user, final String password) {

        try {
            final Pair<String, Integer> hostAndPort = validateUrl(url);
            final HttpClient httpclient = new HttpClient(new MultiThreadedHttpConnectionManager());
            if ((user != null) && (password != null)) {
                httpclient.getParams().setAuthenticationPreemptive(true);
                final Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
                httpclient.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds);
                s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second());
            }
            // Execute the method.
            final GetMethod method = new GetMethod(url);
            final int statusCode = httpclient.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                s_logger.error("Failed to read from URL: " + url);
                return null;
            }

            return method.getResponseBodyAsStream();
        } catch (final Exception ex) {
            s_logger.error("Failed to read from URL: " + url);
            return null;
        }
    }
 
Example #17
Source File: HttpWorker.java    From office-365-connector-plugin with Apache License 2.0 6 votes vote down vote up
private HttpClient getHttpClient() {
    HttpClient client = new HttpClient();
    Jenkins jenkins = Jenkins.getInstance();
    if (jenkins != null) {
        ProxyConfiguration proxy = jenkins.proxy;
        if (proxy != null) {
            client.getHostConfiguration().setProxy(proxy.name, proxy.port);
            String username = proxy.getUserName();
            String password = proxy.getPassword();
            // Consider it to be passed if username specified. Sufficient?
            if (StringUtils.isNotBlank(username)) {
                client.getState().setProxyCredentials(AuthScope.ANY,
                        new UsernamePasswordCredentials(username, password));
            }
        }
    }
    client.getParams().setConnectionManagerTimeout(timeout);
    client.getHttpConnectionManager().getParams().setSoTimeout(timeout);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
    return client;
}
 
Example #18
Source File: ErrorReportSender.java    From otroslogviewer with Apache License 2.0 6 votes vote down vote up
public String sendReport(Map<String, String> values) throws IOException {
  HttpClient httpClient = new HttpClient();

  HostConfiguration hostConfiguration = new HostConfiguration();
  if (!StringUtils.isBlank(proxy)) {
    hostConfiguration.setProxy(proxy, proxyPort);
    if (StringUtils.isNotBlank(user) && StringUtils.isNotBlank(password)) {
      httpClient.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
    }
  }
  httpClient.setHostConfiguration(hostConfiguration);
  PostMethod method = new PostMethod(getSendUrl());

  addHttpPostParams(values, method);

  int executeMethod = httpClient.executeMethod(method);
  LOGGER.info("HTTP result of report send POST: " + executeMethod);
  return IOUtils.toString(method.getResponseBodyAsStream());
}
 
Example #19
Source File: Http.java    From nutch-htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an authentication scope for the specified
 * <code>host</code>, <code>port</code>, <code>realm</code> and
 * <code>scheme</code>.
 *
 * @param host    Host name or address.
 * @param port    Port number.
 * @param realm   Authentication realm.
 * @param scheme  Authentication scheme.
 */
private static AuthScope getAuthScope(String host, int port,
    String realm, String scheme) {
  
  if (host.length() == 0)
    host = null;

  if (port < 0)
    port = -1;

  if (realm.length() == 0)
    realm = null;

  if (scheme.length() == 0)
    scheme = null;

  return new AuthScope(host, port, realm, scheme);
}
 
Example #20
Source File: HTTPMetadataProvider.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructor.
 * 
 * @param client HTTP client used to pull in remote metadata
 * @param backgroundTaskTimer timer used to schedule background metadata refresh tasks
 * @param metadataURL URL to the remove remote metadata
 * 
 * @throws MetadataProviderException thrown if the HTTP client is null or the metadata URL provided is invalid
 */
public HTTPMetadataProvider(Timer backgroundTaskTimer, HttpClient client, String metadataURL)
        throws MetadataProviderException {
    super(backgroundTaskTimer);

    if (client == null) {
        throw new MetadataProviderException("HTTP client may not be null");
    }
    httpClient = client;

    try {
        metadataURI = new URI(metadataURL);
    } catch (URISyntaxException e) {
        throw new MetadataProviderException("Illegal URL syntax", e);
    }

    authScope = new AuthScope(metadataURI.getHost(), metadataURI.getPort());
}
 
Example #21
Source File: HTTPMetadataProvider.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Constructor.
 * 
 * @param metadataURL the URL to fetch the metadata
 * @param requestTimeout the time, in milliseconds, to wait for the metadata server to respond
 * 
 * @throws MetadataProviderException thrown if the URL is not a valid URL or the metadata can not be retrieved from
 *             the URL
 */
@Deprecated
public HTTPMetadataProvider(String metadataURL, int requestTimeout) throws MetadataProviderException {
    super();
    try {
        metadataURI = new URI(metadataURL);
    } catch (URISyntaxException e) {
        throw new MetadataProviderException("Illegal URL syntax", e);
    }

    HttpClientParams clientParams = new HttpClientParams();
    clientParams.setSoTimeout(requestTimeout);
    httpClient = new HttpClient(clientParams);
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(requestTimeout);
    authScope = new AuthScope(metadataURI.getHost(), metadataURI.getPort());

}
 
Example #22
Source File: UriUtils.java    From cloudstack with Apache License 2.0 6 votes vote down vote up
public static InputStream getInputStreamFromUrl(String url, String user, String password) {

        try {
            Pair<String, Integer> hostAndPort = validateUrl(url);
            HttpClient httpclient = new HttpClient(new MultiThreadedHttpConnectionManager());
            if ((user != null) && (password != null)) {
                httpclient.getParams().setAuthenticationPreemptive(true);
                Credentials defaultcreds = new UsernamePasswordCredentials(user, password);
                httpclient.getState().setCredentials(new AuthScope(hostAndPort.first(), hostAndPort.second(), AuthScope.ANY_REALM), defaultcreds);
                s_logger.info("Added username=" + user + ", password=" + password + "for host " + hostAndPort.first() + ":" + hostAndPort.second());
            }
            // Execute the method.
            GetMethod method = new GetMethod(url);
            int statusCode = httpclient.executeMethod(method);

            if (statusCode != HttpStatus.SC_OK) {
                s_logger.error("Failed to read from URL: " + url);
                return null;
            }

            return method.getResponseBodyAsStream();
        } catch (Exception ex) {
            s_logger.error("Failed to read from URL: " + url);
            return null;
        }
    }
 
Example #23
Source File: HttpState.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Find matching {@link Credentials credentials} for the given authentication scope.
 *
 * @param map the credentials hash map
 * @param token the {@link AuthScope authentication scope}
 * @return the credentials 
 * 
 */
private static Credentials matchCredentials(final HashMap map, final AuthScope authscope) {
    // see if we get a direct hit
    Credentials creds = (Credentials)map.get(authscope);
    if (creds == null) {
        // Nope.
        // Do a full scan
        int bestMatchFactor  = -1;
        AuthScope bestMatch  = null;
        Iterator items = map.keySet().iterator();
        while (items.hasNext()) {
            AuthScope current = (AuthScope)items.next();
            int factor = authscope.match(current);
            if (factor > bestMatchFactor) {
                bestMatchFactor = factor;
                bestMatch = current;
            }
        }
        if (bestMatch != null) {
            creds = (Credentials)map.get(bestMatch);
        }
    }
    return creds;
}
 
Example #24
Source File: TestCaldav.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void setUp() throws IOException {
    super.setUp();
    if (httpClient == null) {
        // start gateway
        DavGateway.start();
        httpClient = new HttpClient();
        HostConfiguration hostConfig = httpClient.getHostConfiguration();
        URI httpURI = new URI("http://localhost:" + Settings.getProperty("davmail.caldavPort"), true);
        hostConfig.setHost(httpURI);
        AuthScope authScope = new AuthScope(null, -1);
        httpClient.getState().setCredentials(authScope, new NTCredentials(Settings.getProperty("davmail.username"), Settings.getProperty("davmail.password"), "", ""));
    }
    if (session == null) {
        session = ExchangeSessionFactory.getInstance(Settings.getProperty("davmail.username"), Settings.getProperty("davmail.password"));
    }
}
 
Example #25
Source File: HttpMethodDirector.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Credentials promptForProxyCredentials(
    final AuthScheme authScheme,
    final HttpParams params,
    final AuthScope authscope) 
{
    LOG.debug("Proxy credentials required");
    Credentials creds = null;
    CredentialsProvider credProvider = 
        (CredentialsProvider)params.getParameter(CredentialsProvider.PROVIDER);
    if (credProvider != null) {
        try {
            creds = credProvider.getCredentials(
                authScheme, authscope.getHost(), authscope.getPort(), true);
        } catch (CredentialsNotAvailableException e) {
            LOG.warn(e.getMessage());
        }
        if (creds != null) {
            this.state.setProxyCredentials(authscope, creds);
            if (LOG.isDebugEnabled()) {
                LOG.debug(authscope + " new credentials given");
            }
        }
    } else {
        LOG.debug("Proxy credentials provider not available");
    }
    return creds;
}
 
Example #26
Source File: HttpMethodDirector.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Credentials promptForCredentials(
    final AuthScheme authScheme,
    final HttpParams params, 
    final AuthScope authscope)
{
    LOG.debug("Credentials required");
    Credentials creds = null;
    CredentialsProvider credProvider = 
        (CredentialsProvider)params.getParameter(CredentialsProvider.PROVIDER);
    if (credProvider != null) {
        try {
            creds = credProvider.getCredentials(
                authScheme, authscope.getHost(), authscope.getPort(), false);
        } catch (CredentialsNotAvailableException e) {
            LOG.warn(e.getMessage());
        }
        if (creds != null) {
            this.state.setCredentials(authscope, creds);
            if (LOG.isDebugEnabled()) {
                LOG.debug(authscope + " new credentials given");
            }
        }
    } else {
        LOG.debug("Credentials provider not available");
    }
    return creds;
}
 
Example #27
Source File: HttpTemplateDownloader.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private void checkProxy(Proxy proxy) {
    if (proxy != null) {
        client.getHostConfiguration().setProxy(proxy.getHost(), proxy.getPort());
        if (proxy.getUserName() != null) {
            Credentials proxyCreds = new UsernamePasswordCredentials(proxy.getUserName(), proxy.getPassword());
            client.getState().setProxyCredentials(AuthScope.ANY, proxyCreds);
        }
    }
}
 
Example #28
Source File: HttpMethodDirector.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void authenticateProxy(final HttpMethod method) throws AuthenticationException {
    // Clean up existing authentication headers
    if (!cleanAuthHeaders(method, PROXY_AUTH_RESP)) {
        // User defined authentication header(s) present
        return;
    }
    AuthState authstate = method.getProxyAuthState();
    AuthScheme authscheme = authstate.getAuthScheme();
    if (authscheme == null) {
        return;
    }
    if (authstate.isAuthRequested() || !authscheme.isConnectionBased()) {
        AuthScope authscope = new AuthScope(
            conn.getProxyHost(), conn.getProxyPort(), 
            authscheme.getRealm(), 
            authscheme.getSchemeName());  
        if (LOG.isDebugEnabled()) {
            LOG.debug("Authenticating with " + authscope);
        }
        Credentials credentials = this.state.getProxyCredentials(authscope);
        if (credentials != null) {
            String authstring = authscheme.authenticate(credentials, method);
            if (authstring != null) {
                method.addRequestHeader(new Header(PROXY_AUTH_RESP, authstring, true));
            }
        } else {
            if (LOG.isWarnEnabled()) {
                LOG.warn("Required proxy credentials not available for " + authscope);
                if (method.getProxyAuthState().isPreemptive()) {
                    LOG.warn("Preemptive authentication requested but no default " +
                        "proxy credentials available"); 
                }
            }
        }
    }
}
 
Example #29
Source File: HTTPUtils.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
/**
 * @param proxy
 * @param httpClient
 */
public static void setProxy(Proxy proxy, HttpClient httpClient) {
    if (proxy != null && httpClient != null) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Setting proxy with host " + proxy.getHost() + " and port " + proxy.getPort() + " for host " + httpClient.getHostConfiguration().getHost() + ":" + httpClient.getHostConfiguration().getPort());
        }

        httpClient.getHostConfiguration().setProxy(proxy.getHost(), proxy.getPort());
        if (proxy.getUserName() != null && proxy.getPassword() != null) {
            httpClient.getState().setProxyCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxy.getUserName(), proxy.getPassword()));
        }
    }
}
 
Example #30
Source File: CredentialsUtils.java    From httpclientAuthHelper with Apache License 2.0 5 votes vote down vote up
public static void setProxyHost(HttpClient httpClient, UsernamePasswordCredentials proxyCredentials,
                                String proxyHost, int proxyPort) {

    if (proxyHost != null && !proxyHost.isEmpty()) {
        httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort);
        if (proxyCredentials != null) {
            HttpState state = new HttpState();
            state.setProxyCredentials(new AuthScope(proxyHost, proxyPort), proxyCredentials);
            httpClient.setState(state);
        }
    }
}