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

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

Introduction

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

Prototype

@Override
public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context)
        throws AuthenticationException 

Source Link

Document

Produces a digest authorization string for the given set of Credentials , method name and URI.

Usage

From source file:io.fabric8.devops.connector.DevOpsConnector.java

protected void createGerritRepo(String repoName, String gerritUser, String gerritPwd,
        String gerritGitInitialCommit, String gerritGitRepoDescription) throws Exception {

    // lets add defaults if not env vars
    if (Strings.isNullOrBlank(gerritUser)) {
        gerritUser = "admin";
    }/*from  ww  w .ja v a 2  s  .  co m*/
    if (Strings.isNullOrBlank(gerritPwd)) {
        gerritPwd = "secret";
    }

    log.info("A Gerrit git repo will be created for this name : " + repoName);

    String gerritAddress = KubernetesHelper.getServiceURL(kubernetes, ServiceNames.GERRIT, namespace, "http",
            true);
    log.info("Found gerrit address: " + gerritAddress + " for namespace: " + namespace
            + " on Kubernetes address: " + kubernetes.getMasterUrl());

    if (Strings.isNullOrBlank(gerritAddress)) {
        throw new Exception("No address for service " + ServiceNames.GERRIT + " in namespace: " + namespace
                + " on Kubernetes address: " + kubernetes.getMasterUrl());
    }

    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpClient httpclientPost = HttpClients.createDefault();
    String GERRIT_URL = gerritAddress + "/a/projects/" + repoName;
    HttpGet httpget = new HttpGet(GERRIT_URL);
    System.out.println("Requesting : " + httpget.getURI());

    try {
        //Initial request without credentials returns "HTTP/1.1 401 Unauthorized"
        HttpResponse response = httpclient.execute(httpget);
        System.out.println(response.getStatusLine());

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            // Get current current "WWW-Authenticate" header from response
            // WWW-Authenticate:Digest realm="My Test Realm", qop="auth",
            // nonce="cdcf6cbe6ee17ae0790ed399935997e8", opaque="ae40d7c8ca6a35af15460d352be5e71c"
            Header authHeader = response.getFirstHeader(AUTH.WWW_AUTH);
            System.out.println("authHeader = " + authHeader);

            DigestScheme digestScheme = new DigestScheme();

            //Parse realm, nonce sent by server.
            digestScheme.processChallenge(authHeader);

            UsernamePasswordCredentials creds = new UsernamePasswordCredentials(gerritUser, gerritPwd);
            httpget.addHeader(digestScheme.authenticate(creds, httpget, null));

            HttpPost httpPost = new HttpPost(GERRIT_URL);
            httpPost.addHeader(digestScheme.authenticate(creds, httpPost, null));
            httpPost.addHeader("Content-Type", "application/json");

            CreateRepositoryDTO createRepoDTO = new CreateRepositoryDTO();
            createRepoDTO.setDescription(gerritGitRepoDescription);
            createRepoDTO.setName(repoName);
            createRepoDTO.setCreate_empty_commit(Boolean.valueOf(gerritGitInitialCommit));

            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(createRepoDTO);

            HttpEntity entity = new StringEntity(json);
            httpPost.setEntity(entity);

            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpclientPost.execute(httpPost, responseHandler);
            System.out.println("responseBody : " + responseBody);
        }

    } catch (MalformedChallengeException e) {
        e.printStackTrace();
    } catch (AuthenticationException e) {
        e.printStackTrace();
    } catch (ConnectException e) {
        System.out.println("Gerrit Server is not responding");
    } catch (HttpResponseException e) {
        System.out.println("Response from Gerrit Server : " + e.getMessage());
        throw new Exception("Repository " + repoName + " already exists !");
    } finally {
        httpclient.close();
        httpclientPost.close();
    }
}

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");
    /*/*from   w  w  w .jav a2  s .  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);
        }
    }
}