Example usage for org.apache.commons.httpclient.params HttpClientParams PREEMPTIVE_AUTHENTICATION

List of usage examples for org.apache.commons.httpclient.params HttpClientParams PREEMPTIVE_AUTHENTICATION

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.params HttpClientParams PREEMPTIVE_AUTHENTICATION.

Prototype

String PREEMPTIVE_AUTHENTICATION

To view the source code for org.apache.commons.httpclient.params HttpClientParams PREEMPTIVE_AUTHENTICATION.

Click Source Link

Usage

From source file:davmail.exchange.ews.EwsExchangeSession.java

@Override
protected void buildSessionInfo(HttpMethod method) throws DavMailException {
    // no need to check logon method body
    if (method != null) {
        method.releaseConnection();/*from  w w  w . j  av a  2s. c o  m*/
    }
    boolean directEws = method == null || "/ews/services.wsdl".equalsIgnoreCase(method.getPath());

    // options page is not available in direct EWS mode
    if (!directEws) {
        // retrieve email and alias from options page
        getEmailAndAliasFromOptions();
    }

    if (email == null || alias == null) {
        // OWA authentication failed, get email address from login
        if (userName.indexOf('@') >= 0) {
            // userName is email address
            email = userName;
            alias = userName.substring(0, userName.indexOf('@'));
        } else {
            // userName or domain\\username, rebuild email address
            alias = getAliasFromLogin();
            email = getAliasFromLogin() + getEmailSuffixFromHostname();
        }
    }

    currentMailboxPath = "/users/" + email.toLowerCase();

    // check EWS access
    try {
        checkEndPointUrl("/ews/exchange.asmx");
        // workaround for Exchange bug: send fake request
        internalGetFolder("");
    } catch (IOException e) {
        // first failover: retry with NTLM
        DavGatewayHttpClientFacade.addNTLM(httpClient);
        try {
            checkEndPointUrl("/ews/exchange.asmx");
            // workaround for Exchange bug: send fake request
            internalGetFolder("");
        } catch (IOException e2) {
            LOGGER.debug(e2.getMessage());
            try {
                // failover, try to retrieve EWS url from autodiscover
                checkEndPointUrl(getEwsUrlFromAutoDiscover());
                // workaround for Exchange bug: send fake request
                internalGetFolder("");
            } catch (IOException e3) {
                // autodiscover failed and initial exception was authentication failure => throw original exception
                if (e instanceof DavMailAuthenticationException) {
                    throw (DavMailAuthenticationException) e;
                }
                LOGGER.error(e2.getMessage());
                throw new DavMailAuthenticationException("EXCEPTION_EWS_NOT_AVAILABLE");
            }
        }
    }

    // enable preemptive authentication on non NTLM endpoints
    if (!DavGatewayHttpClientFacade.hasNTLM(httpClient)) {
        httpClient.getParams().setParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, true);
    }

    // direct EWS: get primary smtp email address with ResolveNames
    if (directEws) {
        try {
            ResolveNamesMethod resolveNamesMethod = new ResolveNamesMethod(alias);
            executeMethod(resolveNamesMethod);
            List<EWSMethod.Item> responses = resolveNamesMethod.getResponseItems();
            for (EWSMethod.Item response : responses) {
                if (alias.equalsIgnoreCase(response.get("Name"))) {
                    email = response.get("EmailAddress");
                    currentMailboxPath = "/users/" + email.toLowerCase();
                }
            }
        } catch (IOException e) {
            LOGGER.warn("Unable to get primary email address with ResolveNames", e);
        }
    }

    try {
        folderIdMap = new HashMap<String, String>();
        // load actual well known folder ids
        folderIdMap.put(internalGetFolder(INBOX).folderId.value, INBOX);
        folderIdMap.put(internalGetFolder(CALENDAR).folderId.value, CALENDAR);
        folderIdMap.put(internalGetFolder(CONTACTS).folderId.value, CONTACTS);
        folderIdMap.put(internalGetFolder(SENT).folderId.value, SENT);
        folderIdMap.put(internalGetFolder(DRAFTS).folderId.value, DRAFTS);
        folderIdMap.put(internalGetFolder(TRASH).folderId.value, TRASH);
        folderIdMap.put(internalGetFolder(JUNK).folderId.value, JUNK);
        folderIdMap.put(internalGetFolder(UNSENT).folderId.value, UNSENT);
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
        throw new DavMailAuthenticationException("EXCEPTION_EWS_NOT_AVAILABLE");
    }
    LOGGER.debug("Current user email is " + email + ", alias is " + alias + " on " + serverVersion);
}

From source file:davmail.exchange.ExchangeSession.java

/**
 * Create an exchange session for the given URL.
 * The session is established for given userName and password
 *
 * @param url      Exchange url/*from  w w w .j  a  v a2 s.c  o  m*/
 * @param userName user login name
 * @param password user password
 * @throws IOException on error
 */
public ExchangeSession(String url, String userName, String password) throws IOException {
    this.userName = userName;
    try {
        httpClient = DavGatewayHttpClientFacade.getInstance(url);
        // set private connection pool
        DavGatewayHttpClientFacade.createMultiThreadedHttpConnectionManager(httpClient);
        boolean isBasicAuthentication = isBasicAuthentication(httpClient, url);
        // clear cookies created by authentication test
        httpClient.getState().clearCookies();

        // The user may have configured an OTP pre-auth username. It is processed
        // so early because OTP pre-auth may disappear in the Exchange LAN and this
        // helps the user to not change is account settings in mail client at each network change.
        if (preAuthUsername == null) {
            // Searches for the delimiter in configured username for the pre-auth user. 
            // The double-quote is not allowed inside email addresses anyway.
            int doubleQuoteIndex = this.userName.indexOf('"');
            if (doubleQuoteIndex > 0) {
                preAuthUsername = this.userName.substring(0, doubleQuoteIndex);
                this.userName = this.userName.substring(doubleQuoteIndex + 1);
            } else {
                // No doublequote: the pre-auth user is the full username, or it is not used at all.
                preAuthUsername = this.userName;
            }
        }

        DavGatewayHttpClientFacade.setCredentials(httpClient, userName, password);

        // get webmail root url
        // providing credentials
        // manually follow redirect
        HttpMethod method = DavGatewayHttpClientFacade.executeFollowRedirects(httpClient, url);

        if (!this.isAuthenticated()) {
            if (isBasicAuthentication) {
                int status = method.getStatusCode();

                if (status == HttpStatus.SC_UNAUTHORIZED) {
                    method.releaseConnection();
                    throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED");
                } else if (status != HttpStatus.SC_OK) {
                    method.releaseConnection();
                    throw DavGatewayHttpClientFacade.buildHttpException(method);
                }
                // workaround for basic authentication on /exchange and form based authentication at /owa
                if ("/owa/auth/logon.aspx".equals(method.getPath())) {
                    method = formLogin(httpClient, method, userName, password);
                }
            } else {
                method = formLogin(httpClient, method, userName, password);
            }
        }

        // avoid 401 roundtrips, only if NTLM is disabled and basic authentication enabled
        if (isBasicAuthentication && !DavGatewayHttpClientFacade.hasNTLM(httpClient)) {
            httpClient.getParams().setParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, true);
        }

        buildSessionInfo(method);

    } catch (DavMailAuthenticationException exc) {
        LOGGER.error(exc.getMessage());
        throw exc;
    } catch (UnknownHostException exc) {
        BundleMessage message = new BundleMessage("EXCEPTION_CONNECT", exc.getClass().getName(),
                exc.getMessage());
        ExchangeSession.LOGGER.error(message);
        throw new DavMailException("EXCEPTION_DAVMAIL_CONFIGURATION", message);
    } catch (WebdavNotAvailableException exc) {
        throw exc;
    } catch (IOException exc) {
        LOGGER.error(BundleMessage.formatLog("EXCEPTION_EXCHANGE_LOGIN_FAILED", exc));
        throw new DavMailException("EXCEPTION_EXCHANGE_LOGIN_FAILED", exc);
    }
    LOGGER.debug("Session " + this + " created");
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Enable NTLM authentication on http client
 *
 * @param httpClient HttpClient instance
 *//* www . j a  v  a2 s. c  o m*/
public static void addNTLM(HttpClient httpClient) {
    // disable preemptive authentication
    httpClient.getParams().setParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, false);

    // register the jcifs based NTLMv2 implementation
    AuthPolicy.registerAuthScheme(AuthPolicy.NTLM, NTLMv2Scheme.class);

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

    // separate domain from username in credentials
    AuthScope authScope = new AuthScope(null, -1);
    NTCredentials credentials = (NTCredentials) httpClient.getState().getCredentials(authScope);
    String userName = credentials.getUserName();
    int backSlashIndex = userName.indexOf('\\');
    if (backSlashIndex >= 0) {
        String domain = userName.substring(0, backSlashIndex);
        userName = userName.substring(backSlashIndex + 1);
        credentials = new NTCredentials(userName, credentials.getPassword(), "UNKNOWN", domain);
        httpClient.getState().setCredentials(authScope, credentials);
    }

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

From source file:org.alfresco.repo.search.impl.solr.SolrAdminHTTPClient.java

public void init() {
    ParameterCheck.mandatory("baseUrl", baseUrl);

    StringBuilder sb = new StringBuilder();
    sb.append(baseUrl + "/admin/cores");
    this.adminUrl = sb.toString();

    httpClient = httpClientFactory.getHttpClient();
    HttpClientParams params = httpClient.getParams();
    params.setBooleanParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, true);
    httpClient.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("admin", "admin"));
}

From source file:org.alfresco.repo.solr.EmbeddedSolrTest.java

@Override
public void setUp() throws Exception {
    KeyStoreParameters keyStoreParameters = new KeyStoreParameters("SSL Key Store", "JCEKS", null,
            "ssl-keystore-passwords.properties", "ssl.keystore");
    KeyStoreParameters trustStoreParameters = new KeyStoreParameters("SSL Trust Store", "JCEKS", null,
            "ssl-truststore-passwords.properties", "ssl.truststore");

    SSLEncryptionParameters sslEncryptionParameters = new SSLEncryptionParameters(keyStoreParameters,
            trustStoreParameters);/*ww  w. jav a  2s  . co  m*/

    ClasspathKeyResourceLoader keyResourceLoader = new ClasspathKeyResourceLoader();
    HttpClientFactory httpClientFactory = new HttpClientFactory(SecureCommsType.getType("https"),
            sslEncryptionParameters, keyResourceLoader, null, null, "localhost", 8080, 8443, 40, 40, 0);

    StringBuilder sb = new StringBuilder();
    sb.append("/solr/admin/cores");
    this.baseUrl = sb.toString();

    httpClient = httpClientFactory.getHttpClient();
    HttpClientParams params = httpClient.getParams();
    params.setBooleanParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, true);
    httpClient.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials("admin", "admin"));
}

From source file:org.alfresco.repo.web.scripts.BaseWebScriptTest.java

@Override
protected void setUp() throws Exception {
    super.setUp();

    if (remoteServer != null) {
        httpClient = new HttpClient();
        httpClient.getParams().setBooleanParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, true);
        if (remoteServer.username != null) {
            httpClient.getState().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                    new UsernamePasswordCredentials(remoteServer.username, remoteServer.password));
        }/*  w w w  .  java  2  s  . c om*/
    }
}

From source file:org.apache.abdera.protocol.client.AbderaClient.java

private boolean mustRevalidate(RequestOptions options, CachedResponse response) {
    if (options.getRevalidateWithAuth()) {
        if (options.getAuthorization() != null)
            return true;
        if (client.getParams().getBooleanParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, false))
            return true;
        if (response != null) {
            if (response.isPublic())
                return false;
        }//from  w ww.  ja  v  a  2  s.co m
    }
    return false;
}

From source file:org.apache.maven.wagon.providers.webdav.AbstractHttpClientWagonTest.java

public void testSetPreemptiveAuthParamViaConfig() {
    HttpMethodConfiguration methodConfig = new HttpMethodConfiguration();
    methodConfig.addParam(HttpClientParams.PREEMPTIVE_AUTHENTICATION, "%b,true");

    HttpConfiguration config = new HttpConfiguration();
    config.setAll(methodConfig);/*  w w  w.j a v  a 2 s.co m*/

    TestWagon wagon = new TestWagon();
    wagon.setHttpConfiguration(config);

    HeadMethod method = new HeadMethod();
    wagon.setParameters(method);

    HttpMethodParams params = method.getParams();
    assertNotNull(params);
    assertTrue(params.isParameterTrue(HttpClientParams.PREEMPTIVE_AUTHENTICATION));
}