Example usage for org.apache.http.impl.auth DigestScheme overrideParamter

List of usage examples for org.apache.http.impl.auth DigestScheme overrideParamter

Introduction

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

Prototype

public void overrideParamter(final String name, final String value) 

Source Link

Usage

From source file:org.picketbox.test.config.ProtectedResourceManagerUnitTestCase.java

@Test
public void testDigestAuth() throws Exception {
    URL url = new URL(urlStr + "onlyManagers");

    DefaultHttpClient httpclient = null;
    try {/* w  ww. j  a  va2  s .co  m*/
        String user = "Aladdin";
        String pass = "Open Sesame";

        httpclient = new DefaultHttpClient();

        HttpGet httpget = new HttpGet(url.toExternalForm());
        HttpResponse response = httpclient.execute(httpget);
        assertEquals(401, response.getStatusLine().getStatusCode());
        Header[] headers = response.getHeaders(PicketBoxConstants.HTTP_WWW_AUTHENTICATE);

        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);

        Header header = headers[0];
        String value = header.getValue();
        value = value.substring(7).trim();

        String[] tokens = HTTPDigestUtil.quoteTokenize(value);
        DigestHolder digestHolder = HTTPDigestUtil.digest(tokens);

        DigestScheme digestAuth = new DigestScheme();
        digestAuth.overrideParamter("algorithm", "MD5");
        digestAuth.overrideParamter("realm", digestHolder.getRealm());
        digestAuth.overrideParamter("nonce", digestHolder.getNonce());
        digestAuth.overrideParamter("qop", "auth");
        digestAuth.overrideParamter("nc", "0001");
        digestAuth.overrideParamter("cnonce", DigestScheme.createCnonce());
        digestAuth.overrideParamter("opaque", digestHolder.getOpaque());

        httpget = new HttpGet(url.toExternalForm());
        Header auth = digestAuth.authenticate(new UsernamePasswordCredentials(user, pass), httpget);
        System.out.println(auth.getName());
        System.out.println(auth.getValue());

        httpget.setHeader(auth);

        System.out.println("executing request" + httpget.getRequestLine());
        response = httpclient.execute(httpget);
        entity = response.getEntity();

        System.out.println("----------------------------------------");
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine);
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        assertEquals(404, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.picketbox.test.config.ProtectedResourceManagerUnitTestCase.java

@Test
public void testNotAuthorizedResource() throws Exception {
    URL url = new URL(urlStr + "confidentialResource");

    DefaultHttpClient httpclient = null;
    try {/*www .ja  va 2  s .  c o m*/
        String user = "Aladdin";
        String pass = "Open Sesame";

        httpclient = new DefaultHttpClient();

        HttpGet httpget = new HttpGet(url.toExternalForm());
        HttpResponse response = httpclient.execute(httpget);
        assertEquals(401, response.getStatusLine().getStatusCode());
        Header[] headers = response.getHeaders(PicketBoxConstants.HTTP_WWW_AUTHENTICATE);

        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);

        Header header = headers[0];
        String value = header.getValue();
        value = value.substring(7).trim();

        String[] tokens = HTTPDigestUtil.quoteTokenize(value);
        DigestHolder digestHolder = HTTPDigestUtil.digest(tokens);

        DigestScheme digestAuth = new DigestScheme();
        digestAuth.overrideParamter("algorithm", "MD5");
        digestAuth.overrideParamter("realm", digestHolder.getRealm());
        digestAuth.overrideParamter("nonce", digestHolder.getNonce());
        digestAuth.overrideParamter("qop", "auth");
        digestAuth.overrideParamter("nc", "0001");
        digestAuth.overrideParamter("cnonce", DigestScheme.createCnonce());
        digestAuth.overrideParamter("opaque", digestHolder.getOpaque());

        httpget = new HttpGet(url.toExternalForm());
        Header auth = digestAuth.authenticate(new UsernamePasswordCredentials(user, pass), httpget);
        System.out.println(auth.getName());
        System.out.println(auth.getValue());

        httpget.setHeader(auth);

        System.out.println("executing request" + httpget.getRequestLine());
        response = httpclient.execute(httpget);
        entity = response.getEntity();

        System.out.println("----------------------------------------");
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine);
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        assertEquals(403, statusLine.getStatusCode());
        EntityUtils.consume(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:SubmitResults.java

public boolean sendFile(Main parent, String hostname, String instanceFilePath, String status, String user,
        String password, boolean encrypted, String newIdent) {

    boolean submit_status = false;
    File tempFile = null;//from   ww w .j  a  v  a2 s . c  om

    // XSLT if ident needs to be changed
    final String changeIdXSLT = "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">"
            + "<xsl:param name=\"surveyId\"/>" + "<xsl:template match=\"@*|node()\">" + "<xsl:copy>"
            + "<xsl:apply-templates select=\"@*|node()\"/>" + "</xsl:copy>" + "</xsl:template>"
            + "<xsl:template match=\"@id\">" + "<xsl:attribute name=\"id\">"
            + "<xsl:value-of select=\"$surveyId\"/>" + "</xsl:attribute>" + "</xsl:template>"
            + "</xsl:stylesheet>";

    //FileBody fb = null;
    ContentType ct = null;
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();

    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    String urlString = null;
    HttpHost targetHost = null;
    if (encrypted) {
        urlString = "https://" + hostname + "/submission";
        targetHost = new HttpHost(hostname, 443, "https");
        parent.appendToStatus("   Using https");
        //credsProvider.setCredentials(
        //        new AuthScope(hostname, 443, "smap", "digest"),
        //        new UsernamePasswordCredentials(user, password));
        credsProvider.setCredentials(new AuthScope(hostname, 443, "smap", "basic"),
                new UsernamePasswordCredentials(user, password));
    } else {
        urlString = "http://" + hostname + "/submission";
        targetHost = new HttpHost(hostname, 80, "http");
        parent.appendToStatus("   Using http (not encrypted)");
        credsProvider.setCredentials(new AuthScope(hostname, 80, "smap", "digest"),
                new UsernamePasswordCredentials(user, password));
    }

    CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

    // get instance file
    File instanceFile = new File(instanceFilePath);

    if (!instanceFile.exists()) {
        parent.appendToStatus("   Error: Submission file " + instanceFilePath + " does not exist");
    } else {

        HttpPost req = new HttpPost(URI.create(urlString));
        //req.setHeader("form_status", status);                  // smap add form_status header

        tempFile = populateRequest(parent, status, instanceFilePath, req, changeIdXSLT, ct, entityBuilder,
                newIdent);

        // find all files in parent directory
        /*
        File[] allFiles = instanceFile.getParentFile().listFiles();
                
        // add media files ignoring invisible files and the submission file
        List<File> files = new ArrayList<File>();
        for (File f : allFiles) {
           String fileName = f.getName();
           if (!fileName.startsWith(".") && !fileName.equals(instanceFile.getName())) {   // ignore invisible files and instance xml file    
         files.add(f);
           }
        }
        */

        // add the submission file first...

        /*
        ct = ContentType.create("text/xml");
         //fb = new FileBody(instanceFile, ct);
         entity.addBinaryBody("xml_submission_file", instanceFile, ct, instanceFile.getPath());
         //entity.addPart("xml_submission_file", fb);
        */

        /*
        for (int j = 0; j < files.size(); j++) {
                  
                
            File f = files.get(j);
            String fileName = f.getName();
            int idx = fileName.lastIndexOf(".");
            String extension = "";
            if (idx != -1) {
           extension = fileName.substring(idx + 1);
            }
                
            // we will be processing every one of these, so
            // we only need to deal with the content type determination...
            if (extension.equals("xml")) {
          ct = ContentType.create("text/xml");
            } else if (extension.equals("jpg")) {
          ct = ContentType.create("image/jpeg");
            } else if (extension.equals("3gp")) {
          ct = ContentType.create("video/3gp");
            } else if (extension.equals("3ga")) {
          ct = ContentType.create("audio/3ga");
            } else if (extension.equals("mp4")) {
          ct = ContentType.create("video/mp4");
            } else if (extension.equals("m4a")) {
            ct = ContentType.create("audio/m4a");
            }else if (extension.equals("csv")) {
          ct = ContentType.create("text/csv");
            } else if (f.getName().endsWith(".amr")) {
          ct = ContentType.create("audio/amr");
            } else if (extension.equals("xls")) {
          ct = ContentType.create("application/vnd.ms-excel");
            }  else {
          ct = ContentType.create("application/octet-stream");
          parent.appendToStatus("   Info: unrecognised content type for extension " + extension);
                  
            }
                
            //fb = new FileBody(f, ct);
            //entity.addPart(f.getName(), fb);
            entity.addBinaryBody(f.getName(), f, ct, f.getName());
                 
           parent.appendToStatus("   Info: added file " + f.getName());
                
        }
        */

        //req.setEntity(entity.build());

        // prepare response and return uploaded
        HttpResponse response = null;
        try {

            // Create AuthCache instance
            AuthCache authCache = new BasicAuthCache();

            // Generate DIGEST scheme object, initialize it and add it to the local auth cache
            DigestScheme digestAuth = new DigestScheme();
            // Suppose we already know the realm name
            digestAuth.overrideParamter("realm", "smap");
            // Suppose we already know the expected nonce value
            digestAuth.overrideParamter("nonce", "whatever");
            authCache.put(targetHost, digestAuth);

            // Generate Basic scheme object
            BasicScheme basicAuth = new BasicScheme();
            authCache.put(targetHost, basicAuth);

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

            parent.appendToStatus("   Info: submitting to: " + req.getURI().toString());
            response = httpclient.execute(targetHost, req, localContext);
            int responseCode = response.getStatusLine().getStatusCode();

            try {
                // have to read the stream in order to reuse the connection
                InputStream is = response.getEntity().getContent();
                // read to end of stream...
                final long count = 1024L;
                while (is.skip(count) == count)
                    ;
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

            // verify that the response was a 201 or 202.
            // If it wasn't, the submission has failed.
            parent.appendToStatus("   Info: Response code: " + responseCode + " : "
                    + response.getStatusLine().getReasonPhrase());
            if (responseCode != HttpStatus.SC_CREATED && responseCode != HttpStatus.SC_ACCEPTED) {
                parent.appendToStatus("   Error: upload failed: ");
            } else {
                submit_status = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            parent.appendToStatus("   Error: Generic Exception. " + e.toString());
        }
    }

    try {
        httpclient.close();
    } catch (Exception e) {

    } finally {

    }

    if (tempFile != null) {
        tempFile.delete();
    }

    return submit_status;
}

From source file:com.ge.research.semtk.sparqlX.SparqlEndpointInterface.java

/**
 * Execute an auth query using POST/*from www.ja va 2  s . c  om*/
 * @return a JSONObject wrapping the results. in the event the results were tabular, they can be obtained in the JsonArray "@Table". if the results were a graph, use "@Graph" for json-ld
 * @throws Exception
 */
private JSONObject executeQueryAuthPost(String query, SparqlResultTypes resultType) throws Exception {

    if (resultType == null) {
        resultType = getDefaultResultType();
    }

    DefaultHttpClient httpclient = new DefaultHttpClient();

    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(this.userName, this.password));

    String[] serverNoProtocol = this.server.split("://");
    //System.err.println("the new server name is: " + serverNoProtocol[1]);

    HttpHost targetHost = new HttpHost(serverNoProtocol[1], Integer.valueOf(this.port), "http");

    DigestScheme digestAuth = new DigestScheme();
    AuthCache authCache = new BasicAuthCache();
    digestAuth.overrideParamter("realm", "SPARQL");
    // Suppose we already know the expected nonce value
    digestAuth.overrideParamter("nonce", "whatever");
    authCache.put(targetHost, digestAuth);
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    // add new stuff
    HttpPost httppost = new HttpPost(getPostURL());
    String resultsFormat = this.getContentType(resultType);
    httppost.addHeader("Accept", resultsFormat);
    httppost.addHeader("X-Sparql-default-graph", this.dataset);

    // add params
    List<NameValuePair> params = new ArrayList<NameValuePair>(3);
    params.add(new BasicNameValuePair("query", query));
    params.add(new BasicNameValuePair("format", resultsFormat));
    params.add(new BasicNameValuePair("default-graph-uri", this.dataset));

    httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

    // finish new stuff

    HttpResponse response_http = httpclient.execute(targetHost, httppost, localcontext);
    HttpEntity entity = response_http.getEntity();
    String responseTxt = EntityUtils.toString(entity, "UTF-8");

    // some diagnostic output
    if (responseTxt == null) {
        System.err.println("the response text was null!");
    }

    if (responseTxt.trim().isEmpty()) {
        handleEmptyResponse(); // implementation-specific behavior
    }

    JSONObject resp;
    try {
        resp = (JSONObject) JSONValue.parse(responseTxt);
    } catch (Exception e) {
        entity.getContent().close();
        throw new Exception("Cannot parse query result into JSON: " + responseTxt);
    }

    if (resp == null) {
        System.err.println("the response could not be transformed into json");

        if (responseTxt.contains("Error")) {
            entity.getContent().close();
            throw new Exception(responseTxt);
        }
        entity.getContent().close();
        return null;
    } else {
        JSONObject procResp = getResultsFromResponse(resp, resultType);
        entity.getContent().close();

        return procResp;
    }
}

From source file:com.ge.research.semtk.sparqlX.SparqlEndpointInterface.java

/**
 * Execute an auth query using POST// w  ww.j a va  2s .  co  m
 * @return a JSONObject wrapping the results. in the event the results were tabular, they can be obtained in the JsonArray "@Table". if the results were a graph, use "@Graph" for json-ld
 * @throws Exception
 */

public JSONObject executeAuthUploadOwl(byte[] owl) throws Exception {

    DefaultHttpClient httpclient = new DefaultHttpClient();

    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(this.userName, this.password));

    String[] serverNoProtocol = this.server.split("://");
    //System.err.println("the new server name is: " + serverNoProtocol[1]);

    HttpHost targetHost = new HttpHost(serverNoProtocol[1], Integer.valueOf(this.port), "http");

    DigestScheme digestAuth = new DigestScheme();
    AuthCache authCache = new BasicAuthCache();
    digestAuth.overrideParamter("realm", "SPARQL");
    // Suppose we already know the expected nonce value
    digestAuth.overrideParamter("nonce", "whatever");
    authCache.put(targetHost, digestAuth);
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    // add new stuff
    HttpPost httppost = new HttpPost(getUploadURL());
    String resultsFormat = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
    httppost.addHeader("Accept", resultsFormat);
    httppost.addHeader("X-Sparql-default-graph", this.dataset);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();

    builder.addTextBody("graph-uri", this.dataset);
    builder.addBinaryBody("res-file", owl);
    HttpEntity entity = builder.build();
    httppost.setEntity(entity);

    /*  THIS IS THE MULTIPART FORMAT WE NEED TO SEND.
            
    Content-Type: multipart/form-data; boundary=---------------------------32932166721282
    Content-Length: 234
            
    -----------------------------32932166721282
    Content-Disposition: form-data; name="graph-uri"
            
    http://www.kdl.ge.com/changeme
    -----------------------------32932166721282
    Content-Disposition: form-data; name="res-file"; filename="employee.owl"
    Content-Type: application/octet-stream
            
    <rdf:RDF
        xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
        xmlns:owl="http://www.w3.org/2002/07/owl#"
        xmlns="http://kdl.ge.com/pd/employee#"
        xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
      .
      .
      .
    </rdf:RDF>
            
    -----------------------------32932166721282--
            
     */

    executeTestQuery();

    HttpResponse response_http = httpclient.execute(targetHost, httppost, localcontext);
    HttpEntity resp_entity = response_http.getEntity();
    // get response with HTML tags removed
    String responseTxt = EntityUtils.toString(resp_entity, "UTF-8").replaceAll("\\<.*?>", " ");

    SimpleResultSet ret = new SimpleResultSet();

    if (responseTxt.trim().isEmpty()) {
        // success or bad login :-(
        ret.setSuccess(true);
    } else {
        ret.setSuccess(false);
        ret.addRationaleMessage(responseTxt);
    }
    resp_entity.getContent().close();
    return ret.toJson();
}

From source file:com.ge.research.semtk.sparqlX.SparqlEndpointInterface.java

/**
 * Execute an auth query using GET (use should be rare - in cases where POST is not supported)
 * @return a JSONObject wrapping the results. in the event the results were tabular, they can be obtained in the JsonArray "@Table". if the results were a graph, use "@Graph" for json-ld
 * @throws Exception/*from  w ww  .j  a va  2s. c  o  m*/
 */
@SuppressWarnings("unused")
private JSONObject executeQueryAuthGet(String queryAndUrl, SparqlResultTypes resultType) throws Exception {

    if (resultType == null) {
        resultType = getDefaultResultType();
    }

    DefaultHttpClient httpclient = new DefaultHttpClient();

    //ResponseHandler<String> responseHandler = new BasicResponseHandler();

    System.err.println("the server name was " + this.server);
    System.err.println("the port id was " + this.port);
    System.err.println("the user name was " + "SPARQL/" + this.userName);
    System.err.println("the password was " + this.password);

    System.err.println(queryAndUrl);

    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(this.userName, this.password));

    String[] serverNoProtocol = this.server.split("://");
    System.err.println("the new server name is: " + serverNoProtocol[1]);

    HttpHost targetHost = new HttpHost(serverNoProtocol[1], Integer.valueOf(this.port), "http");

    DigestScheme digestAuth = new DigestScheme();
    AuthCache authCache = new BasicAuthCache();
    digestAuth.overrideParamter("realm", "SPARQL");
    // Suppose we already know the expected nonce value
    digestAuth.overrideParamter("nonce", "whatever");
    authCache.put(targetHost, digestAuth);
    BasicHttpContext localcontext = new BasicHttpContext();
    localcontext.setAttribute(ClientContext.AUTH_CACHE, authCache);

    HttpGet httpget = new HttpGet(queryAndUrl);
    String resultsFormat = this.getContentType(resultType);
    httpget.addHeader("Accept", resultsFormat);

    System.out.println("executing request" + httpget.getRequestLine());

    //        String responseTxt = httpclient.execute(httpget, responseHandler);
    HttpResponse response_http = httpclient.execute(targetHost, httpget, localcontext);
    HttpEntity entity = response_http.getEntity();
    String responseTxt = EntityUtils.toString(entity, "UTF-8");

    // some diagnostic output
    if (responseTxt == null) {
        System.err.println("the response text was null!");
    }

    if (responseTxt.trim().isEmpty()) {
        handleEmptyResponse(); // implementation-specific behavior
    }

    if (responseTxt.length() < 100) {
        System.err.println("SparqlEndpointInterface received: " + responseTxt);
    } else {
        System.err.println("SparqlEndpointInterface received: " + responseTxt.substring(0, 99) + "... ("
                + responseTxt.length() + " chars)");
    }

    JSONObject resp;
    try {
        resp = (JSONObject) new JSONParser().parse(responseTxt);
    } catch (Exception e) {
        throw new Exception("Cannot parse query result into JSON: " + responseTxt);
    }

    if (resp == null) {
        System.err.println("the response could not be transformed into json");

        if (responseTxt.contains("Error")) {
            throw new Exception(responseTxt);
        }
        return null;
    } else {
        JSONObject procResp = getResultsFromResponse(resp, resultType);

        return procResp;
    }
}

From source file:com.mirth.connect.connectors.http.HttpDispatcher.java

private void processDigestChallenge(AuthCache authCache, HttpHost target, Credentials credentials,
        HttpRequest request, HttpContext context) throws AuthenticationException {
    Header authHeader = request.getFirstHeader("Authorization");
    /*/*  w  w  w  . j  a va2s . c  om*/
     * Since we're going to be replacing the header, we remove it here. If the header is invalid
     * or the challenge fails, we still want to remove the header, because otherwise it will
     * interfere with reactive authentication.
     */
    request.removeHeaders("Authorization");

    if (authHeader != null) {
        String authValue = authHeader.getValue();

        // The Authorization header value will be in the form: Digest param1="value1", param2="value2"
        if (StringUtils.startsWithIgnoreCase(authValue, AuthSchemes.DIGEST)) {
            DigestScheme digestScheme = new DigestScheme();

            // Get the actual parameters by stripping off the "Digest"
            authValue = StringUtils.removeStartIgnoreCase(authValue, AuthSchemes.DIGEST).trim();
            Matcher matcher = AUTH_HEADER_PATTERN.matcher(authValue);

            while (matcher.find()) {
                // We found a param="value" group
                String group = matcher.group();
                int index = group.indexOf('=');
                String name = group.substring(0, index).trim();
                String value = group.substring(index + 1).trim();

                // Strip off any quotes in the value
                if (value.startsWith("\"")) {
                    value = value.substring(1);
                }
                if (value.endsWith("\"")) {
                    value = value.substring(0, value.length() - 1);
                }

                logger.debug("Overriding Digest Parameter: " + name + "=\"" + value + "\"");
                digestScheme.overrideParamter(name, value);
            }

            // Since this is preemptive, we need to actually process the challenge beforehand
            request.addHeader(digestScheme.authenticate(credentials, request, context));
            authCache.put(target, digestScheme);
        }
    }
}

From source file:org.opencastproject.kernel.security.TrustedHttpClientImpl.java

/**
 * Handles the necessary handshake for digest authenticaion in the case where it isn't a GET operation.
 * //  ww  w . jav a 2 s. c o m
 * @param httpUriRequest
 *          The request location to get the digest authentication for.
 * @param httpClient
 *          The client to send the request through.
 * @throws TrustedHttpClientException
 *           Thrown if the client cannot be shutdown.
 */
private void manuallyHandleDigestAuthentication(HttpUriRequest httpUriRequest, HttpClient httpClient)
        throws TrustedHttpClientException {
    HttpRequestBase digestRequest;
    try {
        digestRequest = (HttpRequestBase) httpUriRequest.getClass().newInstance();
    } catch (Exception e) {
        throw new IllegalStateException("Can not create a new " + httpUriRequest.getClass().getName());
    }
    digestRequest.setURI(httpUriRequest.getURI());
    digestRequest.setHeader(REQUESTED_AUTH_HEADER, DIGEST_AUTH);
    String[] realmAndNonce = getRealmAndNonce(digestRequest);

    if (realmAndNonce != null) {
        // Set the user/pass
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass);

        // Set up the digest authentication with the required values
        DigestScheme digestAuth = new DigestScheme();
        digestAuth.overrideParamter("realm", realmAndNonce[0]);
        digestAuth.overrideParamter("nonce", realmAndNonce[1]);

        // Add the authentication header
        try {
            httpUriRequest.setHeader(digestAuth.authenticate(creds, httpUriRequest));
        } catch (Exception e) {
            // close the http connection(s)
            httpClient.getConnectionManager().shutdown();
            throw new TrustedHttpClientException(e);
        }
    }
}

From source file:org.openhab.binding.fritzboxtr064.internal.Tr064Comm.java

/**
 * Creates an Apache HTTP Client object, ignoring SSL Exceptions like self signed
 * certificates, and sets Auth. Scheme to Digest Auth.
 *
 * @param fboxUrl/*from w  w  w .  j  a v  a2  s  .c o m*/
 *            the URL from config file of fbox to connect to
 * @return the ready-to-use httpclient for tr064 requests
 */
private synchronized CloseableHttpClient createTr064HttpClient(String fboxUrl) {
    CloseableHttpClient hc = null;
    // Convert URL String from config in easy explotable URI object
    URIBuilder uriFbox = null;
    try {
        uriFbox = new URIBuilder(fboxUrl);
    } catch (URISyntaxException e) {
        logger.error("Invalid FritzBox URL! {}", e.getMessage());
        return null;
    }
    // Create context of the http client
    _httpClientContext = HttpClientContext.create();
    CookieStore cookieStore = new BasicCookieStore();
    _httpClientContext.setCookieStore(cookieStore);

    // SETUP AUTH
    // Auth is specific for this target
    HttpHost target = new HttpHost(uriFbox.getHost(), uriFbox.getPort(), uriFbox.getScheme());
    // Add digest authentication with username/pw from global config
    CredentialsProvider credp = new BasicCredentialsProvider();
    credp.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
            new UsernamePasswordCredentials(_user, _pw));
    // Create AuthCache instance. Manages authentication based on server response
    AuthCache authCache = new BasicAuthCache();
    // Generate DIGEST scheme object, initialize it and add it to the local auth
    // cache. Digeste is standard for fbox auth SOAP
    DigestScheme digestAuth = new DigestScheme();
    digestAuth.overrideParamter("realm", "HTTPS Access"); // known from fbox specification
    digestAuth.overrideParamter("nonce", ""); // never known at first request
    authCache.put(target, digestAuth);
    // Add AuthCache to the execution context
    _httpClientContext.setAuthCache(authCache);

    // SETUP SSL TRUST
    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    SSLConnectionSocketFactory sslsf = null;
    try {
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); // accept self signed certs
        // dont verify hostname against cert CN
        sslsf = new SSLConnectionSocketFactory(sslContextBuilder.build(), null, null,
                new NoopHostnameVerifier());
    } catch (Exception ex) {
        logger.error(ex.getMessage());
    }

    // Set timeout values
    RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setSocketTimeout(4000).setConnectTimeout(4000)
            .setConnectionRequestTimeout(4000).build();

    // BUILDER
    // setup builder with parameters defined before
    hc = HttpClientBuilder.create().setSSLSocketFactory(sslsf) // set the SSL options which trust every self signed
            // cert
            .setDefaultCredentialsProvider(credp) // set auth options using digest
            .setDefaultRequestConfig(rc) // set the request config specifying timeout
            .build();

    return hc;
}