Example usage for org.apache.http.auth MalformedChallengeException getMessage

List of usage examples for org.apache.http.auth MalformedChallengeException getMessage

Introduction

In this page you can find the example usage for org.apache.http.auth MalformedChallengeException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:org.callimachusproject.client.HttpAuthenticator.java

private boolean handleAuthChallenge(final HttpHost host, final HttpResponse response,
        final AuthenticationStrategy authStrategy, final AuthState authState, final HttpContext context) {
    try {// w w w . jav a2s  .c o  m
        if (this.log.isDebugEnabled()) {
            this.log.debug(host.toHostString() + " requested authentication");
        }
        final Map<String, Header> challenges = authStrategy.getChallenges(host, response, context);
        if (challenges.isEmpty()) {
            this.log.debug("Response contains no authentication challenges");
            return false;
        }

        final AuthScheme authScheme = authState.getAuthScheme();
        switch (authState.getState()) {
        case FAILURE:
            return false;
        case SUCCESS:
            authState.reset();
            break;
        case CHALLENGED:
        case HANDSHAKE:
            if (authScheme == null) {
                this.log.debug("Auth scheme is null");
                authStrategy.authFailed(host, null, context);
                authState.reset();
                authState.setState(AuthProtocolState.FAILURE);
                return false;
            }
        case UNCHALLENGED:
            if (authScheme != null) {
                final String id = authScheme.getSchemeName();
                final Header challenge = challenges.get(id.toLowerCase(Locale.US));
                if (challenge != null) {
                    this.log.debug("Authorization challenge processed");
                    authScheme.processChallenge(challenge);
                    if (authScheme.isComplete()) {
                        this.log.debug("Authentication failed");
                        authStrategy.authFailed(host, authState.getAuthScheme(), context);
                        authState.reset();
                        authState.setState(AuthProtocolState.FAILURE);
                        return false;
                    } else {
                        authState.setState(AuthProtocolState.HANDSHAKE);
                        return true;
                    }
                } else {
                    authState.reset();
                    // Retry authentication with a different scheme
                }
            }
        }
        final Queue<AuthOption> authOptions = authStrategy.select(challenges, host, response, context);
        if (authOptions != null && !authOptions.isEmpty()) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Selected authentication options: " + authOptions);
            }
            authState.setState(AuthProtocolState.CHALLENGED);
            authState.update(authOptions);
            return true;
        } else {
            return false;
        }
    } catch (final MalformedChallengeException ex) {
        if (this.log.isWarnEnabled()) {
            this.log.warn("Malformed challenge: " + ex.getMessage());
        }
        authState.reset();
        return false;
    }
}

From source file:org.archive.modules.fetcher.FetchHTTP.java

protected AuthScheme chooseAuthScheme(Map<String, String> challenges, String challengeHeaderKey) {
    HashSet<String> authSchemesLeftToTry = new HashSet<String>(challenges.keySet());
    for (String authSchemeName : new String[] { "digest", "basic" }) {
        if (authSchemesLeftToTry.remove(authSchemeName)) {
            AuthScheme authScheme = AUTH_SCHEME_REGISTRY.lookup(authSchemeName).create(null);
            ;//from  w w  w .  j  av  a 2s .co  m
            BasicHeader challenge = new BasicHeader(challengeHeaderKey, challenges.get(authSchemeName));

            try {
                authScheme.processChallenge(challenge);
            } catch (MalformedChallengeException e) {
                logger.fine(e.getMessage() + " " + challenge);
                continue;
            }
            if (authScheme.isConnectionBased()) {
                logger.fine("Connection based " + authScheme);
                continue;
            }

            if (authScheme.getRealm() == null || authScheme.getRealm().length() <= 0) {
                logger.fine("Empty realm " + authScheme);
                continue;
            }

            return authScheme;
        }
    }

    for (String unsupportedSchemeName : authSchemesLeftToTry) {
        logger.fine("Unsupported http auth scheme: " + unsupportedSchemeName);
    }

    return null;
}

From source file:org.archive.modules.fetcher.FetchHTTP.java

/**
 * @param response/*  ww w .  j  a v  a 2s . c  o m*/
 * @param method
 *            Method that got a 401 or 407.
 * @param curi
 *            CrawlURI that got a 401 or 407.
 * @param authStrategy
 *            Either ProxyAuthenticationStrategy or
 *            TargetAuthenticationStrategy. Determines whether
 *            Proxy-Authenticate or WWW-Authenticate header is consulted.
 * 
 * @return Map<authSchemeName -> challenge header value>
 */
protected Map<String, String> extractChallenges(HttpResponse response, final CrawlURI curi,
        AuthenticationStrategy authStrategy) {
    Map<String, Header> hcChallengeHeaders = null;
    try {
        hcChallengeHeaders = authStrategy.getChallenges(null, response, null);
    } catch (MalformedChallengeException e) {
        logger.fine("Failed challenge parse: " + e.getMessage());
        hcChallengeHeaders = new HashMap<String, Header>();
    }
    if (hcChallengeHeaders.size() < 1) {
        curi.getNonFatalFailures().add(new IllegalStateException(
                "Missing auth challenge headers for uri with response status 401: " + curi));
    }

    // reorganize in non-library-specific way
    Map<String, String> challenges = new HashMap<String, String>();
    for (Entry<String, Header> challenge : hcChallengeHeaders.entrySet()) {
        challenges.put(challenge.getKey(), challenge.getValue().getValue());
    }

    return challenges;
}

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   w  w w. j  av  a2  s. c  om
    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.http.impl.auth.HttpAuthenticator.java

public boolean handleAuthChallenge(final HttpHost host, final HttpResponse response,
        final AuthenticationStrategy authStrategy, final AuthState authState, final HttpContext context) {
    try {//from ww w  .  j  av a 2s  .co m
        if (this.log.isDebugEnabled()) {
            this.log.debug(host.toHostString() + " requested authentication");
        }
        final Map<String, Header> challenges = authStrategy.getChallenges(host, response, context);
        if (challenges.isEmpty()) {
            this.log.debug("Response contains no authentication challenges");
            return false;
        }

        final AuthScheme authScheme = authState.getAuthScheme();
        switch (authState.getState()) {
        case FAILURE:
            return false;
        case SUCCESS:
            authState.reset();
            break;
        case CHALLENGED:
        case HANDSHAKE:
            if (authScheme == null) {
                this.log.debug("Auth scheme is null");
                authStrategy.authFailed(host, null, context);
                authState.reset();
                authState.setState(AuthProtocolState.FAILURE);
                return false;
            }
        case UNCHALLENGED:
            if (authScheme != null) {
                final String id = authScheme.getSchemeName();
                final Header challenge = challenges.get(id.toLowerCase(Locale.US));
                if (challenge != null) {
                    this.log.debug("Authorization challenge processed");
                    authScheme.processChallenge(challenge);
                    if (authScheme.isComplete()) {
                        this.log.debug("Authentication failed");
                        authStrategy.authFailed(host, authState.getAuthScheme(), context);
                        authState.reset();
                        authState.setState(AuthProtocolState.FAILURE);
                        return false;
                    } else {
                        authState.setState(AuthProtocolState.HANDSHAKE);
                        return true;
                    }
                } else {
                    authState.reset();
                    // Retry authentication with a different scheme
                }
            }
        }
        final Queue<AuthOption> authOptions = authStrategy.select(challenges, host, response, context);
        if (authOptions != null && !authOptions.isEmpty()) {
            if (this.log.isDebugEnabled()) {
                this.log.debug("Selected authentication options: " + authOptions);
            }
            authState.setState(AuthProtocolState.CHALLENGED);
            authState.update(authOptions);
            return true;
        } else {
            return false;
        }
    } catch (final MalformedChallengeException ex) {
        if (this.log.isWarnEnabled()) {
            this.log.warn("Malformed challenge: " + ex.getMessage());
        }
        authState.reset();
        return false;
    }
}