Search in sources :

Example 11 with AuthenticationException

use of org.apache.http.auth.AuthenticationException in project platform_external_apache-http by android.

the class RequestProxyAuthentication method process.

public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }
    if (context == null) {
        throw new IllegalArgumentException("HTTP context may not be null");
    }
    if (request.containsHeader(AUTH.PROXY_AUTH_RESP)) {
        return;
    }
    // Obtain authentication state
    AuthState authState = (AuthState) context.getAttribute(ClientContext.PROXY_AUTH_STATE);
    if (authState == null) {
        return;
    }
    AuthScheme authScheme = authState.getAuthScheme();
    if (authScheme == null) {
        return;
    }
    Credentials creds = authState.getCredentials();
    if (creds == null) {
        this.log.debug("User credentials not available");
        return;
    }
    if (authState.getAuthScope() != null || !authScheme.isConnectionBased()) {
        try {
            request.addHeader(authScheme.authenticate(creds, request));
        } catch (AuthenticationException ex) {
            if (this.log.isErrorEnabled()) {
                this.log.error("Proxy authentication error: " + ex.getMessage());
            }
        }
    }
}
Also used : AuthState(org.apache.http.auth.AuthState) AuthenticationException(org.apache.http.auth.AuthenticationException) Credentials(org.apache.http.auth.Credentials) AuthScheme(org.apache.http.auth.AuthScheme)

Example 12 with AuthenticationException

use of org.apache.http.auth.AuthenticationException in project platform_external_apache-http by android.

the class DefaultRequestDirector method handleResponse.

/**
     * Analyzes a response to check need for a followup.
     *
     * @param roureq    the request and route. 
     * @param response  the response to analayze
     * @param context   the context used for the current request execution
     *
     * @return  the followup request and route if there is a followup, or
     *          <code>null</code> if the response should be returned as is
     *
     * @throws HttpException    in case of a problem
     * @throws IOException      in case of an IO problem
     */
protected RoutedRequest handleResponse(RoutedRequest roureq, HttpResponse response, HttpContext context) throws HttpException, IOException {
    HttpRoute route = roureq.getRoute();
    HttpHost proxy = route.getProxyHost();
    RequestWrapper request = roureq.getRequest();
    HttpParams params = request.getParams();
    if (HttpClientParams.isRedirecting(params) && this.redirectHandler.isRedirectRequested(response, context)) {
        if (redirectCount >= maxRedirects) {
            throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded");
        }
        redirectCount++;
        URI uri = this.redirectHandler.getLocationURI(response, context);
        HttpHost newTarget = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
        HttpGet redirect = new HttpGet(uri);
        HttpRequest orig = request.getOriginal();
        redirect.setHeaders(orig.getAllHeaders());
        RequestWrapper wrapper = new RequestWrapper(redirect);
        wrapper.setParams(params);
        HttpRoute newRoute = determineRoute(newTarget, wrapper, context);
        RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute);
        if (this.log.isDebugEnabled()) {
            this.log.debug("Redirecting to '" + uri + "' via " + newRoute);
        }
        return newRequest;
    }
    CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
    if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
        if (this.targetAuthHandler.isAuthenticationRequested(response, context)) {
            HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            if (target == null) {
                target = route.getTargetHost();
            }
            this.log.debug("Target requested authentication");
            Map<String, Header> challenges = this.targetAuthHandler.getChallenges(response, context);
            try {
                processChallenges(challenges, this.targetAuthState, this.targetAuthHandler, response, context);
            } catch (AuthenticationException ex) {
                if (this.log.isWarnEnabled()) {
                    this.log.warn("Authentication error: " + ex.getMessage());
                    return null;
                }
            }
            updateAuthState(this.targetAuthState, target, credsProvider);
            if (this.targetAuthState.getCredentials() != null) {
                // Re-try the same request via the same route
                return roureq;
            } else {
                return null;
            }
        } else {
            // Reset target auth scope
            this.targetAuthState.setAuthScope(null);
        }
        if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {
            this.log.debug("Proxy requested authentication");
            Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
            try {
                processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context);
            } catch (AuthenticationException ex) {
                if (this.log.isWarnEnabled()) {
                    this.log.warn("Authentication error: " + ex.getMessage());
                    return null;
                }
            }
            updateAuthState(this.proxyAuthState, proxy, credsProvider);
            if (this.proxyAuthState.getCredentials() != null) {
                // Re-try the same request via the same route
                return roureq;
            } else {
                return null;
            }
        } else {
            // Reset proxy auth scope
            this.proxyAuthState.setAuthScope(null);
        }
    }
    return null;
}
Also used : HttpRequest(org.apache.http.HttpRequest) BasicHttpRequest(org.apache.http.message.BasicHttpRequest) AbortableHttpRequest(org.apache.http.client.methods.AbortableHttpRequest) AuthenticationException(org.apache.http.auth.AuthenticationException) HttpGet(org.apache.http.client.methods.HttpGet) CredentialsProvider(org.apache.http.client.CredentialsProvider) URI(java.net.URI) HttpRoute(org.apache.http.conn.routing.HttpRoute) HttpParams(org.apache.http.params.HttpParams) Header(org.apache.http.Header) HttpHost(org.apache.http.HttpHost) RedirectException(org.apache.http.client.RedirectException)

Example 13 with AuthenticationException

use of org.apache.http.auth.AuthenticationException in project platform_external_apache-http by android.

the class DigestScheme method createDigest.

/**
     * Creates an MD5 response digest.
     * 
     * @return The created digest as string. This will be the response tag's
     *         value in the Authentication HTTP header.
     * @throws AuthenticationException when MD5 is an unsupported algorithm
     */
private String createDigest(final Credentials credentials) throws AuthenticationException {
    // Collecting required tokens
    String uri = getParameter("uri");
    String realm = getParameter("realm");
    String nonce = getParameter("nonce");
    String method = getParameter("methodname");
    String algorithm = getParameter("algorithm");
    if (uri == null) {
        throw new IllegalStateException("URI may not be null");
    }
    if (realm == null) {
        throw new IllegalStateException("Realm may not be null");
    }
    if (nonce == null) {
        throw new IllegalStateException("Nonce may not be null");
    }
    // If an algorithm is not specified, default to MD5.
    if (algorithm == null) {
        algorithm = "MD5";
    }
    // If an charset is not specified, default to ISO-8859-1.
    String charset = getParameter("charset");
    if (charset == null) {
        charset = "ISO-8859-1";
    }
    if (qopVariant == QOP_AUTH_INT) {
        throw new AuthenticationException("Unsupported qop in HTTP Digest authentication");
    }
    MessageDigest md5Helper = createMessageDigest("MD5");
    String uname = credentials.getUserPrincipal().getName();
    String pwd = credentials.getPassword();
    // 3.2.2.2: Calculating digest
    StringBuilder tmp = new StringBuilder(uname.length() + realm.length() + pwd.length() + 2);
    tmp.append(uname);
    tmp.append(':');
    tmp.append(realm);
    tmp.append(':');
    tmp.append(pwd);
    // unq(username-value) ":" unq(realm-value) ":" passwd
    String a1 = tmp.toString();
    //a1 is suitable for MD5 algorithm
    if (algorithm.equalsIgnoreCase("MD5-sess")) {
        // android-changed: ignore case
        // H( unq(username-value) ":" unq(realm-value) ":" passwd )
        //      ":" unq(nonce-value)
        //      ":" unq(cnonce-value)
        String cnonce = getCnonce();
        String tmp2 = encode(md5Helper.digest(EncodingUtils.getBytes(a1, charset)));
        StringBuilder tmp3 = new StringBuilder(tmp2.length() + nonce.length() + cnonce.length() + 2);
        tmp3.append(tmp2);
        tmp3.append(':');
        tmp3.append(nonce);
        tmp3.append(':');
        tmp3.append(cnonce);
        a1 = tmp3.toString();
    } else if (!algorithm.equalsIgnoreCase("MD5")) {
        // android-changed: ignore case
        throw new AuthenticationException("Unhandled algorithm " + algorithm + " requested");
    }
    String md5a1 = encode(md5Helper.digest(EncodingUtils.getBytes(a1, charset)));
    String a2 = null;
    if (qopVariant == QOP_AUTH_INT) {
    // Unhandled qop auth-int
    //we do not have access to the entity-body or its hash
    //TODO: add Method ":" digest-uri-value ":" H(entity-body)      
    } else {
        a2 = method + ':' + uri;
    }
    String md5a2 = encode(md5Helper.digest(EncodingUtils.getAsciiBytes(a2)));
    // 3.2.2.1
    String serverDigestValue;
    if (qopVariant == QOP_MISSING) {
        StringBuilder tmp2 = new StringBuilder(md5a1.length() + nonce.length() + md5a2.length());
        tmp2.append(md5a1);
        tmp2.append(':');
        tmp2.append(nonce);
        tmp2.append(':');
        tmp2.append(md5a2);
        serverDigestValue = tmp2.toString();
    } else {
        String qopOption = getQopVariantString();
        String cnonce = getCnonce();
        StringBuilder tmp2 = new StringBuilder(md5a1.length() + nonce.length() + NC.length() + cnonce.length() + qopOption.length() + md5a2.length() + 5);
        tmp2.append(md5a1);
        tmp2.append(':');
        tmp2.append(nonce);
        tmp2.append(':');
        tmp2.append(NC);
        tmp2.append(':');
        tmp2.append(cnonce);
        tmp2.append(':');
        tmp2.append(qopOption);
        tmp2.append(':');
        tmp2.append(md5a2);
        serverDigestValue = tmp2.toString();
    }
    String serverDigest = encode(md5Helper.digest(EncodingUtils.getAsciiBytes(serverDigestValue)));
    return serverDigest;
}
Also used : AuthenticationException(org.apache.http.auth.AuthenticationException) MessageDigest(java.security.MessageDigest)

Example 14 with AuthenticationException

use of org.apache.http.auth.AuthenticationException in project platform_external_apache-http by android.

the class NTLMScheme method authenticate.

public Header authenticate(final Credentials credentials, final HttpRequest request) throws AuthenticationException {
    NTCredentials ntcredentials = null;
    try {
        ntcredentials = (NTCredentials) credentials;
    } catch (ClassCastException e) {
        throw new InvalidCredentialsException("Credentials cannot be used for NTLM authentication: " + credentials.getClass().getName());
    }
    String response = null;
    if (this.state == State.CHALLENGE_RECEIVED || this.state == State.FAILED) {
        response = this.engine.generateType1Msg(ntcredentials.getDomain(), ntcredentials.getWorkstation());
        this.state = State.MSG_TYPE1_GENERATED;
    } else if (this.state == State.MSG_TYPE2_RECEVIED) {
        response = this.engine.generateType3Msg(ntcredentials.getUserName(), ntcredentials.getPassword(), ntcredentials.getDomain(), ntcredentials.getWorkstation(), this.challenge);
        this.state = State.MSG_TYPE3_GENERATED;
    } else {
        throw new AuthenticationException("Unexpected state: " + this.state);
    }
    CharArrayBuffer buffer = new CharArrayBuffer(32);
    if (isProxy()) {
        buffer.append(AUTH.PROXY_AUTH_RESP);
    } else {
        buffer.append(AUTH.WWW_AUTH_RESP);
    }
    buffer.append(": NTLM ");
    buffer.append(response);
    return new BufferedHeader(buffer);
}
Also used : InvalidCredentialsException(org.apache.http.auth.InvalidCredentialsException) AuthenticationException(org.apache.http.auth.AuthenticationException) BufferedHeader(org.apache.http.message.BufferedHeader) CharArrayBuffer(org.apache.http.util.CharArrayBuffer) NTCredentials(org.apache.http.auth.NTCredentials)

Example 15 with AuthenticationException

use of org.apache.http.auth.AuthenticationException in project platform_external_apache-http by android.

the class DefaultRequestDirector method createTunnelToTarget.

// establishConnection
/**
     * Creates a tunnel to the target server.
     * The connection must be established to the (last) proxy.
     * A CONNECT request for tunnelling through the proxy will
     * be created and sent, the response received and checked.
     * This method does <i>not</i> update the connection with
     * information about the tunnel, that is left to the caller.
     *
     * @param route     the route to establish
     * @param context   the context for request execution
     *
     * @return  <code>true</code> if the tunnelled route is secure,
     *          <code>false</code> otherwise.
     *          The implementation here always returns <code>false</code>,
     *          but derived classes may override.
     *
     * @throws HttpException    in case of a problem
     * @throws IOException      in case of an IO problem
     */
protected boolean createTunnelToTarget(HttpRoute route, HttpContext context) throws HttpException, IOException {
    HttpHost proxy = route.getProxyHost();
    HttpHost target = route.getTargetHost();
    HttpResponse response = null;
    boolean done = false;
    while (!done) {
        done = true;
        if (!this.managedConn.isOpen()) {
            this.managedConn.open(route, context, this.params);
        }
        HttpRequest connect = createConnectRequest(route, context);
        String agent = HttpProtocolParams.getUserAgent(params);
        if (agent != null) {
            connect.addHeader(HTTP.USER_AGENT, agent);
        }
        connect.addHeader(HTTP.TARGET_HOST, target.toHostString());
        AuthScheme authScheme = this.proxyAuthState.getAuthScheme();
        AuthScope authScope = this.proxyAuthState.getAuthScope();
        Credentials creds = this.proxyAuthState.getCredentials();
        if (creds != null) {
            if (authScope != null || !authScheme.isConnectionBased()) {
                try {
                    connect.addHeader(authScheme.authenticate(creds, connect));
                } catch (AuthenticationException ex) {
                    if (this.log.isErrorEnabled()) {
                        this.log.error("Proxy authentication error: " + ex.getMessage());
                    }
                }
            }
        }
        response = requestExec.execute(connect, this.managedConn, context);
        int status = response.getStatusLine().getStatusCode();
        if (status < 200) {
            throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine());
        }
        CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
        if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
            if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {
                this.log.debug("Proxy requested authentication");
                Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
                try {
                    processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context);
                } catch (AuthenticationException ex) {
                    if (this.log.isWarnEnabled()) {
                        this.log.warn("Authentication error: " + ex.getMessage());
                        break;
                    }
                }
                updateAuthState(this.proxyAuthState, proxy, credsProvider);
                if (this.proxyAuthState.getCredentials() != null) {
                    done = false;
                    // Retry request
                    if (this.reuseStrategy.keepAlive(response, context)) {
                        this.log.debug("Connection kept alive");
                        // Consume response content
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            entity.consumeContent();
                        }
                    } else {
                        this.managedConn.close();
                    }
                }
            } else {
                // Reset proxy auth scope
                this.proxyAuthState.setAuthScope(null);
            }
        }
    }
    int status = response.getStatusLine().getStatusCode();
    if (status > 299) {
        // Buffer response content
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            response.setEntity(new BufferedHttpEntity(entity));
        }
        this.managedConn.close();
        throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response);
    }
    this.managedConn.markReusable();
    // Leave it to derived classes, consider insecure by default here.
    return false;
}
Also used : HttpRequest(org.apache.http.HttpRequest) BasicHttpRequest(org.apache.http.message.BasicHttpRequest) AbortableHttpRequest(org.apache.http.client.methods.AbortableHttpRequest) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) AuthenticationException(org.apache.http.auth.AuthenticationException) HttpResponse(org.apache.http.HttpResponse) CredentialsProvider(org.apache.http.client.CredentialsProvider) AuthScheme(org.apache.http.auth.AuthScheme) Header(org.apache.http.Header) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) HttpHost(org.apache.http.HttpHost) AuthScope(org.apache.http.auth.AuthScope) HttpException(org.apache.http.HttpException) Credentials(org.apache.http.auth.Credentials)

Aggregations

AuthenticationException (org.apache.http.auth.AuthenticationException)31 AuthScheme (org.apache.http.auth.AuthScheme)17 Header (org.apache.http.Header)16 HttpHost (org.apache.http.HttpHost)9 Credentials (org.apache.http.auth.Credentials)9 HttpRequest (org.apache.http.HttpRequest)8 CredentialsProvider (org.apache.http.client.CredentialsProvider)8 AbortableHttpRequest (org.apache.http.client.methods.AbortableHttpRequest)8 BasicHttpRequest (org.apache.http.message.BasicHttpRequest)8 AuthState (org.apache.http.auth.AuthState)6 InvalidCredentialsException (org.apache.http.auth.InvalidCredentialsException)6 BufferedHeader (org.apache.http.message.BufferedHeader)5 CharArrayBuffer (org.apache.http.util.CharArrayBuffer)5 URI (java.net.URI)4 HttpEntity (org.apache.http.HttpEntity)4 HttpException (org.apache.http.HttpException)4 HttpResponse (org.apache.http.HttpResponse)4 NTCredentials (org.apache.http.auth.NTCredentials)4 RedirectException (org.apache.http.client.RedirectException)4 HttpGet (org.apache.http.client.methods.HttpGet)4