Example usage for org.apache.http.auth AuthScope AuthScope

List of usage examples for org.apache.http.auth AuthScope AuthScope

Introduction

In this page you can find the example usage for org.apache.http.auth AuthScope AuthScope.

Prototype

public AuthScope(final String host, final int port) 

Source Link

Document

Creates a new credentials scope for the given host, port, any realm name, and any authentication scheme.

Usage

From source file:com.xebialabs.deployit.ci.server.PreemptiveAuthenticationInterceptor.java

@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    if (request.getFirstHeader("Authorization") == null) {
        LOGGER.trace("No 'Authorization' header found for request: {}", request.getRequestLine());
        HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        CredentialsProvider credentialsProvider = (CredentialsProvider) context
                .getAttribute(ClientContext.CREDS_PROVIDER);
        if (credentialsProvider != null) {
            Credentials credentials = credentialsProvider
                    .getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
            if (credentials != null) {
                request.setHeader(new BasicScheme().authenticate(credentials, request, context));
                LOGGER.trace("Set 'Authorization' header {} for request: {}", credentials.getUserPrincipal(),
                        request.getRequestLine());
            }//  w w  w .j av a2  s . c  o m
        }
    }
}

From source file:org.nekorp.workflow.desktop.rest.util.RestTemplateFactory.java

@PostConstruct
public void init() {
    targetHost = new HttpHost(host, port, protocol);
    //connectionPool = new PoolingHttpClientConnectionManager();
    //connectionPool.setDefaultMaxPerRoute(10);
    //connectionPool.setMaxTotal(20);

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
            new UsernamePasswordCredentials(username, password));
    //wildcard ssl certificate
    SSLContext sslContext = SSLContexts.createDefault();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
            NoopHostnameVerifier.INSTANCE);

    httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
            //.setConnectionManager(connectionPool)
            .setSSLSocketFactory(sslsf).build();
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local
    // auth cache
    BasicScheme basicAuth = new BasicScheme();
    authCache.put(targetHost, basicAuth);

    // Add AuthCache to the execution context
    HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);

    HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactoryBasicAuth(
            httpclient, localContext);/*w ww .j a  va2 s.  c o  m*/
    this.template = new RestTemplate();
    template.getMessageConverters().add(new BufferedImageHttpMessageConverter());
    template.setRequestFactory(factory);
}

From source file:org.xwiki.extension.repository.http.internal.PreemptiveAuth.java

@Override
public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);

    // If no auth scheme available yet, try to initialize it
    // preemptively
    if (authState.getAuthScheme() == null) {
        AuthScheme authScheme = (AuthScheme) context.getAttribute("preemptive-auth");
        CredentialsProvider credsProvider = (CredentialsProvider) context
                .getAttribute(ClientContext.CREDS_PROVIDER);
        HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        if (authScheme != null) {
            Credentials credentials = credsProvider
                    .getCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()));
            if (credentials == null) {
                throw new HttpException("No credentials for preemptive authentication");
            }// www  .j  a  v  a2  s  . c o  m
            authState.update(authScheme, credentials);
        }
    }

}

From source file:org.commonjava.couch.io.CouchHttpClient.java

@PostConstruct
private void setupClient() {
    final ThreadSafeClientConnManager ccm = new ThreadSafeClientConnManager();
    ccm.setMaxTotal(config.getMaxConnections());

    final DefaultHttpClient c = new DefaultHttpClient(ccm);

    if (config.getDatabaseUser() != null) {
        final AuthScope scope = new AuthScope(config.getDatabaseHost(), config.getDatabasePort());
        final UsernamePasswordCredentials cred = new UsernamePasswordCredentials(config.getDatabaseUser(),
                config.getDatabasePassword());

        c.getCredentialsProvider().setCredentials(scope, cred);
    }//from   w  w w.j a v a  2 s.  c om

    client = c;
}

From source file:com.apm4all.tracy.TracyAsyncHttpClientPublisher.java

TracyAsyncHttpClientPublisher(String hostname, int port, boolean waitForResponse, String resourcePath,
        HttpProxyConfig httpProxyConfig, boolean debug) {
    this.uri = "http://" + hostname + ":" + port + "/" + resourcePath;
    this.waitForResponse = waitForResponse;
    this.httpProxyConfig = httpProxyConfig;
    this.debug = debug;
    if (httpProxyConfig.isEnabled()) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(httpProxyConfig.getHost(), httpProxyConfig.getPort()),
                new UsernamePasswordCredentials(httpProxyConfig.getUsername(), httpProxyConfig.getPassword()));
        this.httpClient = HttpAsyncClients.custom().setDefaultCredentialsProvider(credsProvider).build();

    } else {/* www  .j av  a  2 s  .  c  o m*/
        this.httpClient = HttpAsyncClients.custom().build();
    }
    this.httpClient.start();
}

From source file:cz.zcu.kiv.eegdatabase.logic.util.BasicAuthHttpClient.java

public BasicAuthHttpClient(URL url, String username, String password, ThreadSafeClientConnManager connManager) {
    super(connManager);
    this.url = url;

    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(url.getHost(), AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(username, password));
    setCredentialsProvider(credsProvider);
}

From source file:org.zenoss.metrics.reporter.HttpPoster.java

private HttpPoster(final URL url, final String user, final String password, ObjectMapper mapper) {
    this.url = url;
    this.mapper = mapper;
    if (!Strings.nullToEmpty(user).trim().isEmpty()) {
        httpClient.getCredentialsProvider().setCredentials(new AuthScope(url.getHost(), url.getPort()),
                new UsernamePasswordCredentials(user, password));
        this.needsAuth = true;
    } else {//  w  w  w  .  j  av  a 2s . c  o  m
        this.needsAuth = false;
    }
}

From source file:org.apache.nifi.processors.gcp.ProxyAwareTransportFactory.java

@Override
public HttpTransport create() {

    if (proxyConfig == null) {
        return DEFAULT_TRANSPORT;
    }/*w  w  w . j  ava  2s.  c o  m*/

    final Proxy proxy = proxyConfig.createProxy();

    if (Proxy.Type.HTTP.equals(proxy.type()) && proxyConfig.hasCredential()) {
        // If it requires authentication via username and password, use ApacheHttpTransport
        final String host = proxyConfig.getProxyServerHost();
        final int port = proxyConfig.getProxyServerPort();
        final HttpHost proxyHost = new HttpHost(host, port);

        final DefaultHttpClient httpClient = new DefaultHttpClient();
        ConnRouteParams.setDefaultProxy(httpClient.getParams(), proxyHost);

        if (proxyConfig.hasCredential()) {
            final AuthScope proxyAuthScope = new AuthScope(host, port);
            final UsernamePasswordCredentials proxyCredential = new UsernamePasswordCredentials(
                    proxyConfig.getProxyUserName(), proxyConfig.getProxyUserPassword());
            final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(proxyAuthScope, proxyCredential);
            httpClient.setCredentialsProvider(credentialsProvider);
        }

        return new ApacheHttpTransport(httpClient);

    }

    return new NetHttpTransport.Builder().setProxy(proxy).build();
}

From source file:com.urswolfer.intellij.plugin.gerrit.rest.ProxyHttpClientBuilderExtension.java

@Override
public CredentialsProvider extendCredentialProvider(HttpClientBuilder httpClientBuilder,
        CredentialsProvider credentialsProvider, GerritAuthData authData) {
    HttpConfigurable proxySettings = HttpConfigurable.getInstance();
    IdeaWideProxySelector ideaWideProxySelector = new IdeaWideProxySelector(proxySettings);

    // This will always return at least one proxy, which can be the "NO_PROXY" instance.
    List<Proxy> proxies = ideaWideProxySelector.select(URI.create(authData.getHost()));

    // Find the first real proxy with an address type we support.
    for (Proxy proxy : proxies) {
        SocketAddress socketAddress = proxy.address();

        if (HttpConfigurable.isRealProxy(proxy) && socketAddress instanceof InetSocketAddress) {
            InetSocketAddress address = (InetSocketAddress) socketAddress;
            HttpHost proxyHttpHost = new HttpHost(address.getHostName(), address.getPort());
            httpClientBuilder.setProxy(proxyHttpHost);

            // Here we use the single username/password that we got from IDEA's settings. It feels kinda strange
            // to use these credential but it's probably what the user expects.
            if (proxySettings.PROXY_AUTHENTICATION) {
                AuthScope authScope = new AuthScope(proxySettings.PROXY_HOST, proxySettings.PROXY_PORT);
                UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                        proxySettings.PROXY_LOGIN, proxySettings.getPlainProxyPassword());
                credentialsProvider.setCredentials(authScope, credentials);
                break;
            }//from  w w  w .  ja  v a 2  s  . c  o m
        }
    }
    return credentialsProvider;
}

From source file:com.puppetlabs.geppetto.injectable.eclipse.impl.EclipseHttpClientProvider.java

@Override
public HttpClient get() {
    HttpParams params = new BasicHttpParams();
    if (connectonTimeout != null)
        HttpConnectionParams.setConnectionTimeout(params, connectonTimeout.intValue());
    if (soTimeout != null)
        HttpConnectionParams.setSoTimeout(params, soTimeout.intValue());

    DefaultHttpClient httpClient = new DefaultHttpClient(params);

    final SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();
    if (sslSocketFactory != null)
        schemeRegistry.register(new Scheme("https", 443, sslSocketFactory));

    httpClient.setRoutePlanner(new ProxiedRoutePlanner(schemeRegistry));
    for (IProxyData proxyData : Activator.getInstance().getProxyService().getProxyData()) {
        String user = proxyData.getUserId();
        String pwd = proxyData.getPassword();
        if (user != null || pwd != null)
            httpClient.getCredentialsProvider().setCredentials(
                    new AuthScope(proxyData.getHost(), proxyData.getPort()),
                    new UsernamePasswordCredentials(user, pwd));
    }/*from   w  w w .ja  va 2 s  . c  om*/
    return httpClient;
}