Example usage for org.apache.http.impl.auth BasicScheme BasicScheme

List of usage examples for org.apache.http.impl.auth BasicScheme BasicScheme

Introduction

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

Prototype

public BasicScheme() 

Source Link

Usage

From source file:org.fao.geonet.api.mapservers.GeoServerRest.java

/**
 * @param method      e.g. 'POST', 'GET', 'PUT' or 'DELETE'
 * @param urlParams   REST API parameter
 * @param postData    XML data//  w  ww . j av  a  2 s  .c om
 * @param file        File to upload
 * @param contentType type of content in case of post data or file updload.
 */
public @CheckReturnValue int sendREST(String method, String urlParams, String postData, Path file,
        String contentType, Boolean saveResponse) throws IOException {

    response = "";
    String url = this.restUrl + urlParams;
    if (Log.isDebugEnabled(LOGGER_NAME)) {
        Log.debug(LOGGER_NAME, "url:" + url);
        Log.debug(LOGGER_NAME, "method:" + method);
        if (postData != null)
            Log.debug(LOGGER_NAME, "postData:" + postData);
    }

    HttpRequestBase m;
    if (method.equals(METHOD_PUT)) {
        m = new HttpPut(url);
        if (file != null) {
            ((HttpPut) m)
                    .setEntity(new PathHttpEntity(file, ContentType.create(contentType, Constants.ENCODING)));
        }

        if (postData != null) {
            final StringEntity entity = new StringEntity(postData,
                    ContentType.create(contentType, Constants.ENCODING));
            ((HttpPut) m).setEntity(entity);
        }
    } else if (method.equals(METHOD_DELETE)) {
        m = new HttpDelete(url);
    } else if (method.equals(METHOD_POST)) {
        m = new HttpPost(url);
        if (postData != null) {
            final StringEntity entity = new StringEntity(postData,
                    ContentType.create(contentType, Constants.ENCODING));
            ((HttpPost) m).setEntity(entity);
        }
    } else {
        m = new HttpGet(url);
    }

    if (contentType != null && !"".equals(contentType)) {
        m.setHeader("Content-type", contentType);
    }

    m.setConfig(RequestConfig.custom().setAuthenticationEnabled(true).build());

    // apparently this is needed to preemptively send the auth, for servers that dont require it but
    // dont send the same data if you're authenticated or not.
    try {
        m.addHeader(new BasicScheme().authenticate(new UsernamePasswordCredentials(username, password), m));
    } catch (AuthenticationException a) {
        Log.warning(LOGGER_NAME, "Failed to add the authentication Header, error is: " + a.getMessage());
    }
    ;

    final ClientHttpResponse httpResponse = factory.execute(m,
            new UsernamePasswordCredentials(username, password), AuthScope.ANY);

    try {
        status = httpResponse.getRawStatusCode();
        if (Log.isDebugEnabled(LOGGER_NAME)) {
            Log.debug(LOGGER_NAME, "status:" + status);
        }
        if (saveResponse) {
            this.response = IOUtils.toString(httpResponse.getBody());
        }
    } finally {
        httpResponse.close();
    }

    return status;
}

From source file:nl.nn.adapterframework.http.HttpSenderBase.java

public void configure() throws ConfigurationException {
    super.configure();

    if (!getMethodType().equals("POST")) {
        if (!isParamsInUrl()) {
            throw new ConfigurationException(
                    getLogPrefix() + "paramsInUrl can only be set to false for methodType POST");
        }//from  w  w  w .  j  a v a 2 s  .  c o  m
        if (StringUtils.isNotEmpty(getInputMessageParam())) {
            throw new ConfigurationException(
                    getLogPrefix() + "inputMessageParam can only be set for methodType POST");
        }
    }

    /**
     * TODO find out if this really breaks proxy authentication or not.
     */
    //      httpClientBuilder.disableAuthCaching();
    httpClientBuilder.disableAutomaticRetries();

    Builder requestConfig = RequestConfig.custom();
    requestConfig.setConnectTimeout(getTimeout());
    requestConfig.setConnectionRequestTimeout(getTimeout());
    requestConfig.setSocketTimeout(getTimeout());

    if (paramList != null) {
        paramList.configure();
        if (StringUtils.isNotEmpty(getUrlParam())) {
            urlParameter = paramList.findParameter(getUrlParam());
            addParameterToSkip(urlParameter);
        }
    }
    if (getMaxConnections() <= 0) {
        throw new ConfigurationException(getLogPrefix() + "maxConnections is set to [" + getMaxConnections()
                + "], which is not enough for adequate operation");
    }
    try {
        if (urlParameter == null) {
            if (StringUtils.isEmpty(getUrl())) {
                throw new ConfigurationException(
                        getLogPrefix() + "url must be specified, either as attribute, or as parameter");
            }
            staticUri = getURI(getUrl());
        }

        URL certificateUrl = null;
        URL truststoreUrl = null;

        if (!StringUtils.isEmpty(getCertificate())) {
            certificateUrl = ClassUtils.getResourceURL(getClassLoader(), getCertificate());
            if (certificateUrl == null) {
                throw new ConfigurationException(
                        getLogPrefix() + "cannot find URL for certificate resource [" + getCertificate() + "]");
            }
            log.info(getLogPrefix() + "resolved certificate-URL to [" + certificateUrl.toString() + "]");
        }
        if (!StringUtils.isEmpty(getTruststore())) {
            truststoreUrl = ClassUtils.getResourceURL(getClassLoader(), getTruststore());
            if (truststoreUrl == null) {
                throw new ConfigurationException(
                        getLogPrefix() + "cannot find URL for truststore resource [" + getTruststore() + "]");
            }
            log.info(getLogPrefix() + "resolved truststore-URL to [" + truststoreUrl.toString() + "]");
        }

        HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
        if (!isVerifyHostname())
            hostnameVerifier = new NoopHostnameVerifier();

        // Add javax.net.ssl.SSLSocketFactory.getDefault() SSLSocketFactory if non has been set.
        // See: http://httpcomponents.10934.n7.nabble.com/Upgrading-commons-httpclient-3-x-to-HttpClient4-x-td19333.html
        // 
        // The first time this method is called, the security property "ssl.SocketFactory.provider" is examined. 
        // If it is non-null, a class by that name is loaded and instantiated. If that is successful and the 
        // object is an instance of SSLSocketFactory, it is made the default SSL socket factory.
        // Otherwise, this method returns SSLContext.getDefault().getSocketFactory(). If that call fails, an inoperative factory is returned.
        javax.net.ssl.SSLSocketFactory socketfactory = (javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory
                .getDefault();
        sslSocketFactory = new SSLConnectionSocketFactory(socketfactory, hostnameVerifier);

        if (certificateUrl != null || truststoreUrl != null || isAllowSelfSignedCertificates()) {
            try {
                CredentialFactory certificateCf = new CredentialFactory(getCertificateAuthAlias(), null,
                        getCertificatePassword());
                CredentialFactory truststoreCf = new CredentialFactory(getTruststoreAuthAlias(), null,
                        getTruststorePassword());

                SSLContext sslContext = AuthSSLConnectionSocket.createSSLContext(certificateUrl,
                        certificateCf.getPassword(), getKeystoreType(), getKeyManagerAlgorithm(), truststoreUrl,
                        truststoreCf.getPassword(), getTruststoreType(), getTrustManagerAlgorithm(),
                        isAllowSelfSignedCertificates(), isVerifyHostname(),
                        isIgnoreCertificateExpiredException(), getProtocol());

                sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
                log.debug(getLogPrefix() + "created custom SSLConnectionSocketFactory");

            } catch (Throwable t) {
                throw new ConfigurationException(getLogPrefix() + "cannot create or initialize SocketFactory",
                        t);
            }
        }

        // This method will be overwritten by the connectionManager when connectionPooling is enabled!
        // Can still be null when no default or an invalid system sslSocketFactory has been defined
        if (sslSocketFactory != null)
            httpClientBuilder.setSSLSocketFactory(sslSocketFactory);

        credentials = new CredentialFactory(getAuthAlias(), getUserName(), getPassword());
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        if (!StringUtils.isEmpty(credentials.getUsername())) {
            String uname;
            if (StringUtils.isNotEmpty(getAuthDomain())) {
                uname = getAuthDomain() + "\\" + credentials.getUsername();
            } else {
                uname = credentials.getUsername();
            }

            credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                    new UsernamePasswordCredentials(uname, credentials.getPassword()));

            requestConfig.setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC));
            requestConfig.setAuthenticationEnabled(true);
        }
        if (StringUtils.isNotEmpty(getProxyHost())) {
            HttpHost proxy = new HttpHost(getProxyHost(), getProxyPort());
            AuthScope scope = new AuthScope(proxy, getProxyRealm(), AuthScope.ANY_SCHEME);

            CredentialFactory pcf = new CredentialFactory(getProxyAuthAlias(), getProxyUserName(),
                    getProxyPassword());

            if (StringUtils.isNotEmpty(pcf.getUsername())) {
                Credentials credentials = new UsernamePasswordCredentials(pcf.getUsername(), pcf.getPassword());
                credentialsProvider.setCredentials(scope, credentials);
            }
            log.trace("setting credentialProvider [" + credentialsProvider.toString() + "]");

            if (prefillProxyAuthCache()) {
                requestConfig.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC));

                AuthCache authCache = httpClientContext.getAuthCache();
                if (authCache == null)
                    authCache = new BasicAuthCache();

                authCache.put(proxy, new BasicScheme());
                httpClientContext.setAuthCache(authCache);
            }

            requestConfig.setProxy(proxy);
            httpClientBuilder.setProxy(proxy);
        }

        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    } catch (URISyntaxException e) {
        throw new ConfigurationException(getLogPrefix() + "cannot interpret uri [" + getUrl() + "]");
    }

    if (StringUtils.isNotEmpty(getStyleSheetName())) {
        try {
            URL stylesheetURL = ClassUtils.getResourceURL(getClassLoader(), getStyleSheetName());
            if (stylesheetURL == null) {
                throw new ConfigurationException(
                        getLogPrefix() + "cannot find stylesheet [" + getStyleSheetName() + "]");
            }
            transformerPool = TransformerPool.getInstance(stylesheetURL);
        } catch (IOException e) {
            throw new ConfigurationException(getLogPrefix() + "cannot retrieve [" + getStyleSheetName() + "]",
                    e);
        } catch (TransformerConfigurationException te) {
            throw new ConfigurationException(
                    getLogPrefix() + "got error creating transformer from file [" + getStyleSheetName() + "]",
                    te);
        }
    }

    httpClientBuilder.setDefaultRequestConfig(requestConfig.build());

    // The redirect strategy used to only redirect GET, DELETE and HEAD.
    httpClientBuilder.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        protected boolean isRedirectable(String method) {
            return isFollowRedirects();
        }
    });
}

From source file:com.rabbitmq.http.client.Client.java

private HttpComponentsClientHttpRequestFactory getRequestFactory(final URL url, final String username,
        final String password, final SSLConnectionSocketFactory sslConnectionSocketFactory,
        final SSLContext sslContext) throws MalformedURLException {
    String theUser = username;//from w  ww  .java  2s.  c o  m
    String thePassword = password;
    String userInfo = url.getUserInfo();
    if (userInfo != null && theUser == null) {
        String[] userParts = userInfo.split(":");
        if (userParts.length > 0) {
            theUser = userParts[0];
        }
        if (userParts.length > 1) {
            thePassword = userParts[1];
        }
    }
    final HttpClientBuilder bldr = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(getCredentialsProvider(url, theUser, thePassword));
    bldr.setDefaultHeaders(Arrays.asList(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json")));
    if (sslConnectionSocketFactory != null) {
        bldr.setSSLSocketFactory(sslConnectionSocketFactory);
    }
    if (sslContext != null) {
        bldr.setSslcontext(sslContext);
    }

    HttpClient httpClient = bldr.build();

    // RabbitMQ HTTP API currently does not support challenge/response for PUT methods.
    AuthCache authCache = new BasicAuthCache();
    BasicScheme basicScheme = new BasicScheme();
    authCache.put(new HttpHost(rootUri.getHost(), rootUri.getPort(), rootUri.getScheme()), basicScheme);
    final HttpClientContext ctx = HttpClientContext.create();
    ctx.setAuthCache(authCache);
    return new HttpComponentsClientHttpRequestFactory(httpClient) {
        @Override
        protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
            return ctx;
        }
    };
}

From source file:com.lehman.ic9.net.httpClient.java

/**
 * Handles setting up client authentication when using 
 * authentication such as basic auth./*  w  ww  .ja  v a 2s  . c o  m*/
 * @param httpGet is the HttpRequest object.
 * @throws AuthenticationException Exception
 */
private void buildAuth(HttpRequest httpGet) throws AuthenticationException {
    if ((this.atype == authType.BASIC) && (this.creds != null)) {
        CredentialsProvider provider = new BasicCredentialsProvider();
        provider.setCredentials(new AuthScope(this.u.getHost(), this.u.getPort()), this.creds);
        this.hcb.setDefaultCredentialsProvider(provider);

        httpGet.addHeader(new BasicScheme().authenticate(creds, httpGet));
    }
}

From source file:org.sdntest.app.SDNTest.java

private boolean flowAllowed() {
    // get login info from file
    // TODO: get from somewhere else, or setup certs
    BufferedReader br = null;//w  w  w .  j  av a 2 s  .  c  o m
    String uname;
    String password;
    try {
        br = new BufferedReader(new FileReader(GLOBUS_LOGIN_FILE));
        uname = br.readLine();
        password = br.readLine();
    } catch (IOException e) {
        log.info("Error reading globus login file: {}", GLOBUS_LOGIN_FILE);
        return false;
    } finally {
        try {
            if (br != null) {
                br.close();
            }
        } catch (IOException ex) {
            log.info("Error closing globus login file");
        }
    }

    if (uname == null || password == null) {
        log.info("Error: could not get globus login from file");
        return false;
    } else {
        log.info("Got globus login un: {}, pw: {}", uname, password);
    }

    // use login info to get authentication token
    UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(uname, password);
    CloseableHttpClient httpclient = HttpClientBuilder.create().build();
    HttpGet authGet = new HttpGet(GLOBUS_AUTH_URL);
    try {
        authGet.addHeader(new BasicScheme().authenticate(credentials, authGet));
    } catch (AuthenticationException e1) {
        e1.printStackTrace();
    }
    authGet.addHeader("User-Agent", "onos");
    log.info(authGet.toString());

    CloseableHttpResponse response1;
    try {
        response1 = httpclient.execute(authGet);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    String authTok = "";
    try {
        log.info(response1.toString());
        String resStr = EntityUtils.toString(response1.getEntity());
        log.info(resStr);
        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(resStr);
        authTok = (String) jsonObject.get("access_token");
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } catch (ParseException e) {
        e.printStackTrace();
        return false;
    } catch (org.json.simple.parser.ParseException e) {
        e.printStackTrace();
    } finally {
        try {
            response1.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    log.info("Token: {}", authTok);
    return true;
}