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

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

Introduction

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

Prototype

public DigestScheme() 

Source Link

Usage

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 .  j  a v  a 2s . c  o  m
     * 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:io.milton.httpclient.Host.java

protected HttpContext newContext() {
    HttpContext context = new BasicHttpContext();
    AuthScheme authScheme;//from ww  w .  j  a va  2 s. c o m
    if (useDigestForPreemptiveAuth) {
        authScheme = new DigestScheme();
    } else {
        authScheme = new BasicScheme();
    }
    context.setAttribute("preemptive-auth", authScheme);
    return context;
}

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";
    }/*  w  w  w. j  av  a2 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:org.apache.syncope.installer.utilities.HttpUtils.java

public int postWithStringEntity(final String url, final String stringEntity) {
    int status = 0;
    try {/*  w  ww .  j a v a 2 s. c  o m*/
        final HttpPost httPost = httpPost(url, new StringEntity(stringEntity));
        httPost.addHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType());
        try (CloseableHttpResponse response = httpClient.execute(targetHost, httPost,
                setAuth(targetHost, new DigestScheme()))) {
            status = response.getStatusLine().getStatusCode();
            handler.logOutput("Http status: " + status, true);
            InstallLog.getInstance().info("Http status: " + status);
        }
    } catch (final IOException ioe) {
        final String messageError = "Error calling " + url + ": " + ioe.getMessage();
        handler.emitError(messageError, messageError);
        InstallLog.getInstance().error(messageError);

    }
    return status;
}

From source file:org.echocat.jomon.net.http.client.HttpClientAuth.java

@Nonnull
protected AuthScheme parseSchemeOf(@Nonnull Matcher matcher) {
    final String plainAuthScheme = matcher.group(4);
    final AuthScheme authScheme;
    if ("digest".equalsIgnoreCase(plainAuthScheme)) {
        authScheme = new DigestScheme();
    } else if ("negotiate".equalsIgnoreCase(plainAuthScheme)) {
        // noinspection deprecation
        authScheme = new NegotiateScheme();
    } else if ("basic".equalsIgnoreCase(plainAuthScheme) || isEmpty(plainAuthScheme)) {
        authScheme = new BasicScheme();
    } else {/*w w w .  j  av  a2s  . c om*/
        throw new IllegalArgumentException(
                "Unknown authScheme '" + plainAuthScheme + "' of: " + matcher.group());
    }
    return authScheme;
}

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.
 * /* w w w  .j  a  va2s .  com*/
 * @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   ww  w .j a  v a  2s . 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;
}