Search in sources :

Example 16 with DigestScheme

use of org.apache.http.impl.auth.DigestScheme in project fabric8 by fabric8io.

the class DevOpsConnector method createGerritRepo.

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";
    }
    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();
    }
}
Also used : DigestScheme(org.apache.http.impl.auth.DigestScheme) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) AuthenticationException(org.apache.http.auth.AuthenticationException) HttpGet(org.apache.http.client.methods.HttpGet) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) HttpResponse(org.apache.http.HttpResponse) MalformedChallengeException(org.apache.http.auth.MalformedChallengeException) HttpResponseException(org.apache.http.client.HttpResponseException) SAXException(org.xml.sax.SAXException) WebApplicationException(javax.ws.rs.WebApplicationException) AuthenticationException(org.apache.http.auth.AuthenticationException) ConnectException(java.net.ConnectException) MalformedChallengeException(org.apache.http.auth.MalformedChallengeException) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) StringEntity(org.apache.http.entity.StringEntity) Header(org.apache.http.Header) CreateRepositoryDTO(io.fabric8.gerrit.CreateRepositoryDTO) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ConnectException(java.net.ConnectException)

Example 17 with DigestScheme

use of org.apache.http.impl.auth.DigestScheme in project fess by codelibs.

the class DataConfig method getAuthScheme.

private AuthScheme getAuthScheme(final Map<String, String> paramMap, final String webAuthName, final String scheme) {
    AuthScheme authScheme = null;
    if (Constants.BASIC.equals(scheme)) {
        authScheme = new BasicScheme();
    } else if (Constants.DIGEST.equals(scheme)) {
        authScheme = new DigestScheme();
    } else if (Constants.NTLM.equals(scheme)) {
        final Properties props = new Properties();
        paramMap.entrySet().stream().filter(e -> e.getKey().startsWith("jcifs.")).forEach(e -> {
            props.setProperty(e.getKey(), e.getValue());
        });
        authScheme = new NTLMScheme(new JcifsEngine(props));
    } else if (Constants.FORM.equals(scheme)) {
        final String prefix = CRAWLER_WEB_AUTH + "." + webAuthName + ".";
        final Map<String, String> parameterMap = paramMap.entrySet().stream().filter(e -> e.getKey().startsWith(prefix)).collect(Collectors.toMap(e -> e.getKey().substring(prefix.length()), Entry::getValue));
        authScheme = new FormScheme(parameterMap);
    }
    return authScheme;
}
Also used : DigestScheme(org.apache.http.impl.auth.DigestScheme) Arrays(java.util.Arrays) Constants(org.codelibs.fess.Constants) AuthenticationImpl(org.codelibs.fess.crawler.client.http.impl.AuthenticationImpl) HcHttpClient(org.codelibs.fess.crawler.client.http.HcHttpClient) HashMap(java.util.HashMap) FormScheme(org.codelibs.fess.crawler.client.http.form.FormScheme) FtpClient(org.codelibs.fess.crawler.client.ftp.FtpClient) Authentication(org.codelibs.fess.crawler.client.http.Authentication) JcifsEngine(org.codelibs.fess.crawler.client.http.ntlm.JcifsEngine) CrawlerSystemException(org.codelibs.fess.crawler.exception.CrawlerSystemException) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) NTCredentials(org.apache.http.auth.NTCredentials) Credentials(org.apache.http.auth.Credentials) Map(java.util.Map) AuthScheme(org.apache.http.auth.AuthScheme) ParameterUtil(org.codelibs.fess.util.ParameterUtil) BasicScheme(org.apache.http.impl.auth.BasicScheme) Properties(java.util.Properties) StringUtil(org.codelibs.core.lang.StringUtil) Collectors(java.util.stream.Collectors) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials) SmbAuthentication(org.codelibs.fess.crawler.client.smb.SmbAuthentication) List(java.util.List) Logger(org.apache.logging.log4j.Logger) NTLMScheme(org.apache.http.impl.auth.NTLMScheme) AuthScope(org.apache.http.auth.AuthScope) FtpAuthentication(org.codelibs.fess.crawler.client.ftp.FtpAuthentication) Entry(java.util.Map.Entry) DigestScheme(org.apache.http.impl.auth.DigestScheme) Pattern(java.util.regex.Pattern) BsDataConfig(org.codelibs.fess.es.config.bsentity.BsDataConfig) SmbClient(org.codelibs.fess.crawler.client.smb.SmbClient) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) CrawlerClientFactory(org.codelibs.fess.crawler.client.CrawlerClientFactory) BasicScheme(org.apache.http.impl.auth.BasicScheme) Entry(java.util.Map.Entry) NTLMScheme(org.apache.http.impl.auth.NTLMScheme) JcifsEngine(org.codelibs.fess.crawler.client.http.ntlm.JcifsEngine) Properties(java.util.Properties) HashMap(java.util.HashMap) Map(java.util.Map) FormScheme(org.codelibs.fess.crawler.client.http.form.FormScheme) AuthScheme(org.apache.http.auth.AuthScheme)

Example 18 with DigestScheme

use of org.apache.http.impl.auth.DigestScheme in project syncope by apache.

the class HttpUtils method postWithDigestAuth.

public String postWithDigestAuth(final String url, final String file) {
    String responseBodyAsString = "";
    try (CloseableHttpResponse response = httpClient.execute(targetHost, httpPost(url, MultipartEntityBuilder.create().addPart("bin", new FileBody(new File(file))).build()), setAuth(targetHost, new DigestScheme()))) {
        responseBodyAsString = IOUtils.toString(response.getEntity().getContent(), Charset.forName("UTF-8"));
        handler.logOutput("Http status: " + response.getStatusLine().getStatusCode(), true);
        InstallLog.getInstance().info("Http status: " + response.getStatusLine().getStatusCode());
    } catch (IOException e) {
        final String messageError = "Error calling " + url + ": " + e.getMessage();
        handler.emitError(messageError, messageError);
        InstallLog.getInstance().error(messageError);
    }
    return responseBodyAsString;
}
Also used : DigestScheme(org.apache.http.impl.auth.DigestScheme) FileBody(org.apache.http.entity.mime.content.FileBody) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) IOException(java.io.IOException) File(java.io.File)

Example 19 with DigestScheme

use of org.apache.http.impl.auth.DigestScheme in project opencast by opencast.

the class TrustedHttpClientImpl method manuallyHandleDigestAuthentication.

/**
 * Handles the necessary handshake for digest authenticaion in the case where it isn't a GET operation.
 *
 * @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, CloseableHttpClient 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)
            try {
                httpClient.close();
            } catch (IOException ex) {
                throw new TrustedHttpClientException(ex);
            }
            throw new TrustedHttpClientException(e);
        }
    }
}
Also used : DigestScheme(org.apache.http.impl.auth.DigestScheme) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) IOException(java.io.IOException) TrustedHttpClientException(org.opencastproject.security.api.TrustedHttpClientException) TrustedHttpClientException(org.opencastproject.security.api.TrustedHttpClientException) ClientProtocolException(org.apache.http.client.ClientProtocolException) UrlSigningException(org.opencastproject.security.urlsigning.exception.UrlSigningException) IOException(java.io.IOException) UsernamePasswordCredentials(org.apache.http.auth.UsernamePasswordCredentials)

Aggregations

DigestScheme (org.apache.http.impl.auth.DigestScheme)19 UsernamePasswordCredentials (org.apache.http.auth.UsernamePasswordCredentials)16 IOException (java.io.IOException)8 HttpGet (org.apache.http.client.methods.HttpGet)8 BasicHeader (org.apache.http.message.BasicHeader)6 AuthScope (org.apache.http.auth.AuthScope)5 ClientProtocolException (org.apache.http.client.ClientProtocolException)4 BasicScheme (org.apache.http.impl.auth.BasicScheme)4 ArrayList (java.util.ArrayList)3 Map (java.util.Map)3 AuthScheme (org.apache.http.auth.AuthScheme)3 Credentials (org.apache.http.auth.Credentials)3 NTCredentials (org.apache.http.auth.NTCredentials)3 NTLMScheme (org.apache.http.impl.auth.NTLMScheme)3 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 CreateRepositoryDTO (io.fabric8.gerrit.CreateRepositoryDTO)2 ConnectException (java.net.ConnectException)2 HashMap (java.util.HashMap)2 Properties (java.util.Properties)2