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

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

Introduction

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

Prototype

String ANY_REALM

To view the source code for org.apache.http.auth AuthScope ANY_REALM.

Click Source Link

Document

The null value represents any realm.

Usage

From source file:org.switchyard.component.resteasy.util.ClientInvoker.java

private AuthScope createAuthScope(String host, String portStr, String realm) throws RuntimeException {
    if (realm == null) {
        realm = AuthScope.ANY_REALM;
    }//from   w  w w .jav  a 2 s.c o m
    int port = -1;
    if (portStr != null) {
        port = Integer.valueOf(portStr).intValue();
    }
    return new AuthScope(host, port, realm);
}

From source file:org.eclipse.mylyn.commons.http.HttpUtil.java

private static void configureHttpClientProxy(AbstractHttpClient client, HttpContext context,
        AbstractWebLocation location) {//from   w w  w.  j  a  v a2 s  . co  m
    String host = getHost(location.getUrl());

    Proxy proxy;
    if (isRepositoryHttps(location.getUrl())) {
        proxy = location.getProxyForHost(host, IProxyData.HTTPS_PROXY_TYPE);
    } else {
        proxy = location.getProxyForHost(host, IProxyData.HTTP_PROXY_TYPE);
    }

    if (proxy != null && !Proxy.NO_PROXY.equals(proxy)) {
        InetSocketAddress address = (InetSocketAddress) proxy.address();

        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
                new HttpHost(address.getHostName(), address.getPort()));

        if (proxy instanceof AuthenticatedProxy) {
            AuthenticatedProxy authProxy = (AuthenticatedProxy) proxy;
            Credentials credentials = getCredentials(authProxy.getUserName(), authProxy.getPassword(),
                    address.getAddress());
            if (credentials instanceof NTCredentials) {
                List<String> authpref = new ArrayList<String>();
                authpref.add(AuthPolicy.NTLM);
                authpref.add(AuthPolicy.BASIC);
                authpref.add(AuthPolicy.DIGEST);
                client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
            } else {
                List<String> authpref = new ArrayList<String>();
                authpref.add(AuthPolicy.BASIC);
                authpref.add(AuthPolicy.DIGEST);
                authpref.add(AuthPolicy.NTLM);
                client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref);
            }
            AuthScope proxyAuthScope = new AuthScope(address.getHostName(), address.getPort(),
                    AuthScope.ANY_REALM);
            client.getCredentialsProvider().setCredentials(proxyAuthScope, credentials);
        }
    } else {
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, null);
    }
}

From source file:com.madrobot.net.client.XMLRPCClient.java

/**
 * Sets basic authentication on web request using plain credentials
 * //from w  w w.j  a va  2s .c om
 * @param username
 *            The plain text username
 * @param password
 *            The plain text password
 * @param doPreemptiveAuth
 *            Select here whether to authenticate without it being requested first by the server.
 */
public void setBasicAuthentication(String username, String password, boolean doPreemptiveAuth) {
    // This code required to trigger the patch created by erickok in issue #6
    if (doPreemptiveAuth = true) {
        this.httpPreAuth = doPreemptiveAuth;
        this.username = username;
        this.password = password;
    } else {
        ((DefaultHttpClient) client).getCredentialsProvider()
                .setCredentials(new AuthScope(postMethod.getURI().getHost(), postMethod.getURI().getPort(),
                        AuthScope.ANY_REALM), new UsernamePasswordCredentials(username, password));
    }
}

From source file:org.bonitasoft.connectors.rest.RESTConnector.java

/**
 * Set the builder based on the request elements
 * /*from   ww w  .  ja v  a 2  s  .  c  om*/
 * @param requestConfigurationBuilder The builder to be set
 * @param authorization The authentication element of the request
 * @param proxy The proxy element of the request
 * @param urlHost The URL host of the request
 * @param urlPort The URL post of the request
 * @param urlProtocol The URL protocol of the request
 * @param httpClientBuilder The builder to be set
 * @return HTTPContext The HTTP context to be set
 */
private HttpContext setAuthorizations(final Builder requestConfigurationBuilder,
        final Authorization authorization, final Proxy proxy, final String urlHost, final int urlPort,
        final String urlProtocol, final HttpClientBuilder httpClientBuilder) {
    HttpContext httpContext = HttpClientContext.create();
    if (authorization != null) {
        if (authorization instanceof BasicDigestAuthorization) {
            final BasicDigestAuthorization castAuthorization = (BasicDigestAuthorization) authorization;

            final List<String> authPrefs = new ArrayList<>();
            if (castAuthorization.isBasic()) {
                authPrefs.add(AuthSchemes.BASIC);
            } else {
                authPrefs.add(AuthSchemes.DIGEST);
            }
            requestConfigurationBuilder.setTargetPreferredAuthSchemes(authPrefs);

            final String username = castAuthorization.getUsername();
            final String password = new String(castAuthorization.getPassword());
            String host = urlHost;
            if (isStringInputValid(castAuthorization.getHost())) {
                host = castAuthorization.getHost();
            }

            int port = urlPort;
            if (castAuthorization.getPort() != null) {
                port = castAuthorization.getPort();
            }

            String realm = AuthScope.ANY_REALM;
            if (isStringInputValid(castAuthorization.getRealm())) {
                realm = castAuthorization.getRealm();
            }

            final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(host, port, realm),
                    new UsernamePasswordCredentials(username, password));
            setProxyCrendentials(proxy, credentialsProvider);
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

            if (castAuthorization.isPreemptive() || proxy != null) {
                final AuthCache authoriationCache = new BasicAuthCache();
                if (castAuthorization.isPreemptive()) {
                    AuthSchemeBase authorizationScheme = null;
                    if (castAuthorization.isBasic()) {
                        authorizationScheme = new BasicScheme(ChallengeState.TARGET);
                    } else {
                        authorizationScheme = new DigestScheme(ChallengeState.TARGET);
                    }
                    authoriationCache.put(new HttpHost(host, port, urlProtocol), authorizationScheme);
                }
                if (proxy != null) {
                    final BasicScheme basicScheme = new BasicScheme(ChallengeState.PROXY);
                    authoriationCache.put(new HttpHost(proxy.getHost(), proxy.getPort()), basicScheme);
                }
                final HttpClientContext localContext = HttpClientContext.create();
                localContext.setAuthCache(authoriationCache);
                httpContext = localContext;
            }
        }
    } else if (proxy != null) {
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        setProxyCrendentials(proxy, credentialsProvider);
        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);

        // Make it preemptive
        if (proxy.hasCredentials()) {
            final AuthCache authoriationCache = new BasicAuthCache();
            final BasicScheme basicScheme = new BasicScheme(ChallengeState.PROXY);
            authoriationCache.put(new HttpHost(proxy.getHost(), proxy.getPort()), basicScheme);
            final HttpClientContext localContext = HttpClientContext.create();
            localContext.setAuthCache(authoriationCache);
            httpContext = localContext;
        }
    }

    return httpContext;
}

From source file:de.escidoc.core.common.util.service.ConnectionUtility.java

/**
 * Set Authentication to a given {@link DefaultHttpClient} instance.
 * /*  w  ww.ja v a  2  s . c o m*/
 * @param url
 *            URL of resource.
 * @param username
 *            User name for authentication
 * @param password
 *            Password for authentication.
 * @throws WebserverSystemException
 *             Thrown if connection failed.
 */
public void setAuthentication(final DefaultHttpClient client, final URL url, final String username,
        final String password) {
    final CredentialsProvider credsProvider = new BasicCredentialsProvider();
    final AuthScope authScope = new AuthScope(url.getHost(), AuthScope.ANY_PORT, AuthScope.ANY_REALM);
    final Credentials creds = new UsernamePasswordCredentials(username, password);
    credsProvider.setCredentials(authScope, creds);
    client.setCredentialsProvider(credsProvider);
    // don't wait for auth request
    final HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {

        @Override
        public void process(final HttpRequest request, final HttpContext context) {
            final AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            final CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            final HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            // If not auth scheme has been initialized yet
            if (authState.getAuthScheme() == null) {
                final AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                // Obtain credentials matching the target host
                final Credentials creds = credsProvider.getCredentials(authScope);
                // If found, generate BasicScheme preemptively
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    };
    client.addRequestInterceptor(preemptiveAuth, 0);
}

From source file:net.sourceforge.jwebunit.htmlunit.HtmlUnitTestingEngineImpl.java

/**
 * Initialise the web client before accessing a page.
 *///from www  .  ja  v a2 s .  c o  m
private void initWebClient() {

    wc = createWebClient();

    wc.getOptions().setJavaScriptEnabled(jsEnabled);
    wc.getOptions().setThrowExceptionOnFailingStatusCode(!ignoreFailingStatusCodes);
    wc.getOptions().setThrowExceptionOnScriptError(throwExceptionOnScriptError);
    wc.getOptions().setRedirectEnabled(true);
    wc.getOptions().setUseInsecureSSL(true);
    if (refreshHandler == null) {
        wc.setRefreshHandler(new ImmediateRefreshHandler());
    } else {
        wc.setRefreshHandler(refreshHandler);
    }
    wc.getOptions().setTimeout(timeout);
    DefaultCredentialsProvider creds = new DefaultCredentialsProvider();
    if (getTestContext().hasAuthorization()) {
        creds.addCredentials(getTestContext().getUser(), getTestContext().getPassword());
    }
    if (getTestContext().hasNTLMAuthorization()) {
        InetAddress netAddress;
        String address;
        try {
            netAddress = InetAddress.getLocalHost();
            address = netAddress.getHostName();
        } catch (UnknownHostException e) {
            address = "";
        }
        creds.addNTLMCredentials(getTestContext().getUser(), getTestContext().getPassword(), "", -1, address,
                getTestContext().getDomain());
    }
    if (getTestContext().hasProxyAuthorization()) {
        creds.addCredentials(getTestContext().getProxyUser(), getTestContext().getProxyPasswd(),
                getTestContext().getProxyHost(), getTestContext().getProxyPort(), AuthScope.ANY_REALM);
    }
    wc.setCredentialsProvider(creds);
    wc.addWebWindowListener(new WebWindowListener() {
        @Override
        public void webWindowClosed(WebWindowEvent event) {
            if (win == null || event.getOldPage().equals(win.getEnclosedPage())) {
                win = wc.getCurrentWindow();
                form = null;
            }
            String win = event.getWebWindow().getName();
            Page oldPage = event.getOldPage();
            String oldPageTitle = "no_html";
            if (oldPage instanceof HtmlPage) {
                oldPageTitle = ((HtmlPage) oldPage).getTitleText();
            }
            logger.debug("Window {} closed : {}", win, oldPageTitle);
        }

        @Override
        public void webWindowContentChanged(WebWindowEvent event) {
            form = null;
            String winName = event.getWebWindow().getName();
            Page oldPage = event.getOldPage();
            Page newPage = event.getNewPage();
            String oldPageTitle = "no_html";
            if (oldPage instanceof HtmlPage) {
                oldPageTitle = ((HtmlPage) oldPage).getTitleText();
            }
            String newPageTitle = "no_html";
            if (newPage instanceof HtmlPage) {
                newPageTitle = ((HtmlPage) newPage).getTitleText();
            }
            logger.debug("Window \"{}\" changed : \"{}\" became \"{}",
                    new Object[] { winName, oldPageTitle, newPageTitle });
        }

        @Override
        public void webWindowOpened(WebWindowEvent event) {
            String win = event.getWebWindow().getName();
            Page newPage = event.getNewPage();
            if (newPage instanceof HtmlPage) {
                logger.debug("Window {} opened : {}", win, ((HtmlPage) newPage).getTitleText());
            } else {
                logger.info("Window {} opened", win);
            }
        }
    });
    // Add Javascript Alert Handler
    wc.setAlertHandler(new AlertHandler() {
        @Override
        public void handleAlert(Page page, String msg) {
            if (expectedJavascriptAlerts.size() < 1) {
                throw new UnexpectedJavascriptAlertException(msg);
            } else {
                JavascriptAlert expected = expectedJavascriptAlerts.remove(0);
                if (!msg.equals(expected.getMessage())) {
                    throw new UnexpectedJavascriptAlertException(msg);
                }
            }
        }
    });
    // Add Javascript Confirm Handler
    wc.setConfirmHandler(new ConfirmHandler() {
        @Override
        public boolean handleConfirm(Page page, String msg) {
            if (expectedJavascriptConfirms.size() < 1) {
                throw new UnexpectedJavascriptConfirmException(msg);
            } else {
                JavascriptConfirm expected = expectedJavascriptConfirms.remove(0);
                if (!msg.equals(expected.getMessage())) {
                    throw new UnexpectedJavascriptConfirmException(msg);
                } else {
                    return expected.getAction();
                }
            }
        }
    });
    // Add Javascript Prompt Handler
    wc.setPromptHandler(new PromptHandler() {
        @Override
        public String handlePrompt(Page page, String msg) {
            if (expectedJavascriptPrompts.size() < 1) {
                throw new UnexpectedJavascriptPromptException(msg);
            } else {
                JavascriptPrompt expected = expectedJavascriptPrompts.remove(0);
                if (!msg.equals(expected.getMessage())) {
                    throw new UnexpectedJavascriptPromptException(msg);
                } else {
                    return expected.getInput();
                }
            }
        }
    });
    // Deal with cookies
    for (javax.servlet.http.Cookie c : getTestContext().getCookies()) {
        // If Path==null, cookie is not send to the server.
        wc.getCookieManager().addCookie(new Cookie(c.getDomain() != null ? c.getDomain() : "", c.getName(),
                c.getValue(), c.getPath() != null ? c.getPath() : "", c.getMaxAge(), c.getSecure()));
    }
    // Deal with custom request header
    Map<String, String> requestHeaders = getTestContext().getRequestHeaders();

    for (Map.Entry<String, String> requestHeader : requestHeaders.entrySet()) {
        wc.addRequestHeader(requestHeader.getKey(), requestHeader.getValue());
    }
}

From source file:org.webservice.fotolia.FotoliaApi.java

/**
 * Construct and returns a usuable http client
 *
 * @param  auto_refresh_token//from  w w  w.  j  a  v a  2s .co  m
 * @return DefaultHttpClient
 */
private DefaultHttpClient _getHttpClient(final boolean auto_refresh_token) {
    DefaultHttpClient client;

    client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(
            new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
            new UsernamePasswordCredentials(this._api_key, this._getSessionId(auto_refresh_token)));

    HttpConnectionParams.setConnectionTimeout(client.getParams(), FotoliaApi.API_CONNECT_TIMEOUT * 1000);
    HttpConnectionParams.setSoTimeout(client.getParams(), FotoliaApi.API_PROCESS_TIMEOUT * 1000);

    return client;
}

From source file:de.escidoc.core.common.business.fedora.FedoraUtility.java

/**
 * Returns a HttpClient object configured with credentials to access Fedora URLs.
 * //from   w w  w .  ja  va  2 s . c  om
 * @return A HttpClient object configured with credentials to access Fedora URLs.
 * @throws de.escidoc.core.common.exceptions.system.WebserverSystemException
 */
DefaultHttpClient getHttpClient() throws WebserverSystemException {
    try {
        if (this.httpClient == null) {
            final HttpParams params = new BasicHttpParams();
            ConnManagerParams.setMaxTotalConnections(params, HTTP_MAX_TOTAL_CONNECTIONS);

            final ConnPerRoute connPerRoute = new ConnPerRouteBean(HTTP_MAX_CONNECTIONS_PER_HOST);
            ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute);

            final Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
            final SchemeRegistry sr = new SchemeRegistry();
            sr.register(http);
            final ClientConnectionManager cm = new ThreadSafeClientConnManager(params, sr);

            this.httpClient = new DefaultHttpClient(cm, params);
            final URL url = new URL(this.fedoraUrl);
            final CredentialsProvider credsProvider = new BasicCredentialsProvider();

            final AuthScope authScope = new AuthScope(url.getHost(), AuthScope.ANY_PORT, AuthScope.ANY_REALM);
            final Credentials creds = new UsernamePasswordCredentials(this.fedoraUser, this.fedoraPassword);
            credsProvider.setCredentials(authScope, creds);

            httpClient.setCredentialsProvider(credsProvider);
        }

        // don't wait for auth request
        final HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {

            @Override
            public void process(final HttpRequest request, final HttpContext context)
                    throws HttpException, IOException {

                final AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
                final CredentialsProvider credsProvider = (CredentialsProvider) context
                        .getAttribute(ClientContext.CREDS_PROVIDER);
                final HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

                // If not auth scheme has been initialized yet
                if (authState.getAuthScheme() == null) {
                    final AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                    // Obtain credentials matching the target host
                    final Credentials creds = credsProvider.getCredentials(authScope);
                    // If found, generate BasicScheme preemptively
                    if (creds != null) {
                        authState.setAuthScheme(new BasicScheme());
                        authState.setCredentials(creds);
                    }
                }
            }

        };

        httpClient.addRequestInterceptor(preemptiveAuth, 0);

        // try only BASIC auth; skip to test NTLM and DIGEST

        return this.httpClient;
    } catch (final MalformedURLException e) {
        throw new WebserverSystemException("Fedora URL from configuration malformed.", e);
    }
}