Search in sources :

Example 16 with AuthenticationException

use of org.apache.http.auth.AuthenticationException in project wildfly by wildfly.

the class JBossNegotiateScheme method authenticate.

/**
     * Produces Negotiate authorization Header based on token created by processChallenge.
     *
     * @param credentials Never used be the Negotiate scheme but must be provided to satisfy common-httpclient API. Credentials
     *        from JAAS will be used instead.
     * @param request The request being authenticated
     *
     * @throws AuthenticationException if authorization string cannot be generated due to an authentication failure
     *
     * @return an Negotiate authorization Header
     */
@Override
public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context) throws AuthenticationException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }
    if (state == State.TOKEN_GENERATED) {
        // hack for auto redirects
        return new BasicHeader("X-dummy", "Token already generated");
    }
    if (state != State.CHALLENGE_RECEIVED) {
        throw new IllegalStateException("Negotiation authentication process has not been initiated");
    }
    try {
        String key = null;
        if (isProxy()) {
            key = ExecutionContext.HTTP_PROXY_HOST;
        } else {
            key = HttpCoreContext.HTTP_TARGET_HOST;
        }
        HttpHost host = (HttpHost) context.getAttribute(key);
        if (host == null) {
            throw new AuthenticationException("Authentication host is not set " + "in the execution context");
        }
        String authServer;
        if (!this.stripPort && host.getPort() > 0) {
            authServer = host.toHostString();
        } else {
            authServer = host.getHostName();
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("init " + authServer);
        }
        final Oid negotiationOid = new Oid(SPNEGO_OID);
        final GSSManager manager = GSSManager.getInstance();
        final GSSName serverName = manager.createName("HTTP@" + authServer, GSSName.NT_HOSTBASED_SERVICE);
        final GSSContext gssContext = manager.createContext(serverName.canonicalize(negotiationOid), negotiationOid, null, DEFAULT_LIFETIME);
        gssContext.requestMutualAuth(true);
        gssContext.requestCredDeleg(true);
        if (token == null) {
            token = new byte[0];
        }
        token = gssContext.initSecContext(token, 0, token.length);
        if (token == null) {
            state = State.FAILED;
            throw new AuthenticationException("GSS security context initialization failed");
        }
        state = State.TOKEN_GENERATED;
        String tokenstr = new String(base64codec.encode(token));
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Sending response '" + tokenstr + "' back to the auth server");
        }
        CharArrayBuffer buffer = new CharArrayBuffer(32);
        if (isProxy()) {
            buffer.append(AUTH.PROXY_AUTH_RESP);
        } else {
            buffer.append(AUTH.WWW_AUTH_RESP);
        }
        buffer.append(": Negotiate ");
        buffer.append(tokenstr);
        return new BufferedHeader(buffer);
    } catch (GSSException gsse) {
        state = State.FAILED;
        if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED)
            throw new InvalidCredentialsException(gsse.getMessage(), gsse);
        if (gsse.getMajor() == GSSException.NO_CRED)
            throw new InvalidCredentialsException(gsse.getMessage(), gsse);
        if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN || gsse.getMajor() == GSSException.OLD_TOKEN)
            throw new AuthenticationException(gsse.getMessage(), gsse);
        // other error
        throw new AuthenticationException(gsse.getMessage());
    }
}
Also used : GSSName(org.ietf.jgss.GSSName) AuthenticationException(org.apache.http.auth.AuthenticationException) BufferedHeader(org.apache.http.message.BufferedHeader) CharArrayBuffer(org.apache.http.util.CharArrayBuffer) Oid(org.ietf.jgss.Oid) GSSException(org.ietf.jgss.GSSException) InvalidCredentialsException(org.apache.http.auth.InvalidCredentialsException) HttpHost(org.apache.http.HttpHost) GSSManager(org.ietf.jgss.GSSManager) GSSContext(org.ietf.jgss.GSSContext) BasicHeader(org.apache.http.message.BasicHeader)

Example 17 with AuthenticationException

use of org.apache.http.auth.AuthenticationException in project androidquery by androidquery.

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 18 with AuthenticationException

use of org.apache.http.auth.AuthenticationException in project robolectric by robolectric.

the class DefaultRequestDirector method processChallenges.

// abortConnection
private void processChallenges(final Map<String, Header> challenges, final AuthState authState, final AuthenticationHandler authHandler, final HttpResponse response, final HttpContext context) throws MalformedChallengeException, AuthenticationException {
    AuthScheme authScheme = authState.getAuthScheme();
    if (authScheme == null) {
        // Authentication not attempted before
        authScheme = authHandler.selectScheme(challenges, response, context);
        authState.setAuthScheme(authScheme);
    }
    String id = authScheme.getSchemeName();
    Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH));
    if (challenge == null) {
        throw new AuthenticationException(id + " authorization challenge expected, but not found");
    }
    authScheme.processChallenge(challenge);
    this.log.debug("Authorization challenge processed");
}
Also used : Header(org.apache.http.Header) AuthenticationException(org.apache.http.auth.AuthenticationException) AuthScheme(org.apache.http.auth.AuthScheme)

Example 19 with AuthenticationException

use of org.apache.http.auth.AuthenticationException in project robolectric by robolectric.

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();
    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++;
        // Virtual host cannot be used any longer
        virtualHost = null;
        URI uri = this.redirectHandler.getLocationURI(response, context);
        HttpHost newTarget = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
        // Unset auth scope
        targetAuthState.setAuthScope(null);
        proxyAuthState.setAuthScope(null);
        // Invalidate auth states if redirecting to another host
        if (!route.getTargetHost().equals(newTarget)) {
            targetAuthState.invalidate();
            AuthScheme authScheme = proxyAuthState.getAuthScheme();
            if (authScheme != null && authScheme.isConnectionBased()) {
                proxyAuthState.invalidate();
            }
        }
        HttpRedirect redirect = new HttpRedirect(request.getMethod(), 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)) {
            HttpHost proxy = route.getProxyHost();
            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) CredentialsProvider(org.apache.http.client.CredentialsProvider) URI(java.net.URI) AuthScheme(org.apache.http.auth.AuthScheme) HttpRoute(org.apache.http.conn.routing.HttpRoute) HttpParams(org.apache.http.params.HttpParams) Header(org.apache.http.Header) HttpHost(org.apache.http.HttpHost) RequestWrapper(org.apache.http.impl.client.RequestWrapper) EntityEnclosingRequestWrapper(org.apache.http.impl.client.EntityEnclosingRequestWrapper) RoutedRequest(org.apache.http.impl.client.RoutedRequest) RedirectException(org.apache.http.client.RedirectException)

Example 20 with AuthenticationException

use of org.apache.http.auth.AuthenticationException in project robovm by robovm.

the class DefaultRequestDirector method processChallenges.

// abortConnection
private void processChallenges(final Map<String, Header> challenges, final AuthState authState, final AuthenticationHandler authHandler, final HttpResponse response, final HttpContext context) throws MalformedChallengeException, AuthenticationException {
    AuthScheme authScheme = authState.getAuthScheme();
    if (authScheme == null) {
        // Authentication not attempted before
        authScheme = authHandler.selectScheme(challenges, response, context);
        authState.setAuthScheme(authScheme);
    }
    String id = authScheme.getSchemeName();
    Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH));
    if (challenge == null) {
        throw new AuthenticationException(id + " authorization challenge expected, but not found");
    }
    authScheme.processChallenge(challenge);
    this.log.debug("Authorization challenge processed");
}
Also used : Header(org.apache.http.Header) AuthenticationException(org.apache.http.auth.AuthenticationException) AuthScheme(org.apache.http.auth.AuthScheme)

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