Example usage for org.apache.http.auth AUTH PROXY_AUTH_RESP

List of usage examples for org.apache.http.auth AUTH PROXY_AUTH_RESP

Introduction

In this page you can find the example usage for org.apache.http.auth AUTH PROXY_AUTH_RESP.

Prototype

String PROXY_AUTH_RESP

To view the source code for org.apache.http.auth AUTH PROXY_AUTH_RESP.

Click Source Link

Document

The proxy authenticate response header.

Usage

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

public void generateAuthResponse(final HttpRoute route, final HttpRequest request, final HttpContext context)
        throws HttpException, IOException {
    if (!request.containsHeader(AUTH.WWW_AUTH_RESP)) {
        final AuthState targetAuthState = this.getTargetAuthState(context);
        if (this.log.isDebugEnabled()) {
            this.log.debug("Target auth state: " + targetAuthState.getState());
        }//from w w  w  .  jav a  2s  .  c  o m
        this.generateAuthResponse(request, targetAuthState, context);
    }
    if (!request.containsHeader(AUTH.PROXY_AUTH_RESP) && !route.isTunnelled()) {
        final AuthState proxyAuthState = this.getProxyAuthState(context);
        if (this.log.isDebugEnabled()) {
            this.log.debug("Proxy auth state: " + proxyAuthState.getState());
        }
        this.generateAuthResponse(request, proxyAuthState, context);
    }
}

From source file:com.androidquery.test.NTLMScheme.java

public Header authenticate(final Credentials credentials, final HttpRequest request)
        throws AuthenticationException {
    NTCredentials ntcredentials = null;/*from  w  w  w  .  ja  v a 2 s  . co m*/
    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);
}

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

public boolean needAuthentication(final HttpRoute route, final HttpRequest request, final HttpResponse response,
        final HttpContext context) throws HttpException, IOException {
    final AuthState targetAuthState = getTargetAuthState(context);
    final AuthState proxyAuthState = getProxyAuthState(context);
    HttpHost target = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST);
    if (target == null) {
        target = route.getTargetHost();//from   w  w w.  j  a  v a  2s. c o m
    }
    HttpHost proxy = route.getProxyHost();
    if (this.needAuthentication(target, proxy, targetAuthState, proxyAuthState, response, context)) {
        // discard previous auth headers
        request.removeHeaders(AUTH.WWW_AUTH_RESP);
        request.removeHeaders(AUTH.PROXY_AUTH_RESP);
        return true;
    } else {
        return false;
    }
}

From source file:freeipa.client.negotiation.JBossNegotiateScheme.java

/**
 * 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
 */// ww w.  java  2  s  .com
@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.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 = ExecutionContext.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();
        }

        System.out.println("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));
        System.out.println("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());
    }
}

From source file:com.aliyun.oss.common.comm.DefaultServiceClient.java

private void setProxyAuthorizationIfNeed(HttpRequestBase httpRequest) {
    if (this.credentialsProvider != null) {
        String auth = this.config.getProxyUsername() + ":" + this.config.getProxyPassword();
        byte[] encodedAuth = Base64.encodeBase64(auth.getBytes());
        String authHeader = "Basic " + new String(encodedAuth);
        httpRequest.addHeader(AUTH.PROXY_AUTH_RESP, authHeader);
    }/* w  w w .ja v a2s  .c o  m*/
}

From source file:org.odk.collect.android.utilities.EnhancedDigestScheme.java

/**
 * Creates digest-response header as defined in RFC2617.
 * //from w ww. ja va 2s .c o  m
 * @param credentials
 *            User credentials
 * 
 * @return The digest-response as String.
 */
private Header createDigestHeader(final Credentials credentials) throws AuthenticationException {
    String uri = getParameter("uri");
    String realm = getParameter("realm");
    String nonce = getParameter("nonce");
    String opaque = getParameter("opaque");
    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");
    }

    // TODO: add support for QOP_INT
    int qop = QOP_UNKNOWN;
    String qoplist = getParameter("qop");
    if (qoplist != null) {
        StringTokenizer tok = new StringTokenizer(qoplist, ",");
        while (tok.hasMoreTokens()) {
            String variant = tok.nextToken().trim();
            if (variant.equals("auth")) {
                qop = QOP_AUTH;
                break;
            }
        }
    } else {
        qop = QOP_MISSING;
    }

    if (qop == QOP_UNKNOWN) {
        throw new AuthenticationException("None of the qop methods is supported: " + qoplist);
    }

    // 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";
    }

    String digAlg = algorithm;
    if (digAlg.equalsIgnoreCase("MD5-sess")) {
        digAlg = "MD5";
    }

    MessageDigest digester;
    try {
        digester = createMessageDigest(digAlg);
    } catch (UnsupportedDigestAlgorithmException ex) {
        throw new AuthenticationException("Unsuppported digest algorithm: " + digAlg);
    }

    String uname = credentials.getUserPrincipal().getName();
    String pwd = credentials.getPassword();

    if (nonce.equals(this.lastNonce)) {
        nounceCount++;
    } else {
        nounceCount = 1;
        cnonce = null;
        lastNonce = nonce;
    }
    StringBuilder sb = new StringBuilder(256);
    Formatter formatter = new Formatter(sb, Locale.US);
    formatter.format("%08x", nounceCount);
    String nc = sb.toString();

    if (cnonce == null) {
        cnonce = createCnonce();
    }

    a1 = null;
    a2 = null;
    // 3.2.2.2: Calculating digest
    if (algorithm.equalsIgnoreCase("MD5-sess")) {
        // H( unq(username-value) ":" unq(realm-value) ":" passwd )
        // ":" unq(nonce-value)
        // ":" unq(cnonce-value)

        // calculated one per session
        sb.setLength(0);
        sb.append(uname).append(':').append(realm).append(':').append(pwd);
        String checksum = encode(digester.digest(EncodingUtils.getBytes(sb.toString(), charset)));
        sb.setLength(0);
        sb.append(checksum).append(':').append(nonce).append(':').append(cnonce);
        a1 = sb.toString();
    } else {
        // unq(username-value) ":" unq(realm-value) ":" passwd
        sb.setLength(0);
        sb.append(uname).append(':').append(realm).append(':').append(pwd);
        a1 = sb.toString();
    }

    String hasha1 = encode(digester.digest(EncodingUtils.getBytes(a1, charset)));

    if (qop == QOP_AUTH) {
        // Method ":" digest-uri-value
        a2 = method + ':' + uri;
    } else if (qop == QOP_AUTH_INT) {
        // Method ":" digest-uri-value ":" H(entity-body)
        // TODO: calculate entity hash if entity is repeatable
        throw new AuthenticationException("qop-int method is not suppported");
    } else {
        a2 = method + ':' + uri;
    }

    String hasha2 = encode(digester.digest(EncodingUtils.getBytes(a2, charset)));

    // 3.2.2.1

    String digestValue;
    if (qop == QOP_MISSING) {
        sb.setLength(0);
        sb.append(hasha1).append(':').append(nonce).append(':').append(hasha2);
        digestValue = sb.toString();
    } else {
        sb.setLength(0);
        sb.append(hasha1).append(':').append(nonce).append(':').append(nc).append(':').append(cnonce)
                .append(':').append(qop == QOP_AUTH_INT ? "auth-int" : "auth").append(':').append(hasha2);
        digestValue = sb.toString();
    }

    String digest = encode(digester.digest(EncodingUtils.getAsciiBytes(digestValue)));

    CharArrayBuffer buffer = new CharArrayBuffer(128);
    if (isProxy()) {
        buffer.append(AUTH.PROXY_AUTH_RESP);
    } else {
        buffer.append(AUTH.WWW_AUTH_RESP);
    }
    buffer.append(": Digest ");

    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(20);
    params.add(new BasicNameValuePair("username", uname));
    params.add(new BasicNameValuePair("realm", realm));
    params.add(new BasicNameValuePair("nonce", nonce));
    params.add(new BasicNameValuePair("uri", uri));
    params.add(new BasicNameValuePair("response", digest));

    if (qop != QOP_MISSING) {
        params.add(new BasicNameValuePair("qop", qop == QOP_AUTH_INT ? "auth-int" : "auth"));
        params.add(new BasicNameValuePair("nc", nc));
        params.add(new BasicNameValuePair("cnonce", cnonce));
    }
    if (algorithm != null) {
        params.add(new BasicNameValuePair("algorithm", algorithm));
    }
    if (opaque != null) {
        params.add(new BasicNameValuePair("opaque", opaque));
    }

    for (int i = 0; i < params.size(); i++) {
        BasicNameValuePair param = params.get(i);
        if (i > 0) {
            buffer.append(", ");
        }
        boolean noQuotes = "nc".equals(param.getName()) || "qop".equals(param.getName());
        BasicHeaderValueFormatter.DEFAULT.formatNameValuePair(buffer, param, !noQuotes);
    }
    return new BufferedHeader(buffer);
}

From source file:org.apache.http.client.protocol.RequestProxyAuthentication.java

public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException {
    if (request == null) {
        throw new IllegalArgumentException("HTTP request may not be null");
    }// w  w  w. ja v a2  s  . c  o  m
    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());
            }
        }
    }
}

From source file:org.apache.http.impl.auth.BasicScheme.java

/**
 * Produces basic authorization header for the given set of {@link Credentials}.
 *
 * @param credentials The set of credentials to be used for authentication
 * @param request The request being authenticated
 * @throws org.apache.http.auth.InvalidCredentialsException if authentication
 *   credentials are not valid or not applicable for this authentication scheme
 * @throws AuthenticationException if authorization string cannot
 *   be generated due to an authentication failure
 *
 * @return a basic authorization string//from  w  ww. j  a  v a 2s .  c om
 */
@Override
public Header authenticate(final Credentials credentials, final HttpRequest request, final HttpContext context)
        throws AuthenticationException {

    Args.notNull(credentials, "Credentials");
    Args.notNull(request, "HTTP request");
    final StringBuilder tmp = new StringBuilder();
    tmp.append(credentials.getUserPrincipal().getName());
    tmp.append(":");
    tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword());

    final byte[] base64password = base64codec
            .encode(EncodingUtils.getBytes(tmp.toString(), getCredentialsCharset(request)));

    final CharArrayBuffer buffer = new CharArrayBuffer(32);
    if (isProxy()) {
        buffer.append(AUTH.PROXY_AUTH_RESP);
    } else {
        buffer.append(AUTH.WWW_AUTH_RESP);
    }
    buffer.append(": Basic ");
    buffer.append(base64password, 0, base64password.length);

    return new BufferedHeader(buffer);
}

From source file:org.apache.http.impl.auth.BasicScheme.java

/**
 * Returns a basic <tt>Authorization</tt> header value for the given
 * {@link Credentials} and charset.//from w  w  w.  ja  v a  2  s. c o m
 *
 * @param credentials The credentials to encode.
 * @param charset The charset to use for encoding the credentials
 *
 * @return a basic authorization header
 *
 * @deprecated (4.3) use {@link #authenticate(Credentials, HttpRequest, HttpContext)}.
 */
@Deprecated
public static Header authenticate(final Credentials credentials, final String charset, final boolean proxy) {
    Args.notNull(credentials, "Credentials");
    Args.notNull(charset, "charset");

    final StringBuilder tmp = new StringBuilder();
    tmp.append(credentials.getUserPrincipal().getName());
    tmp.append(":");
    tmp.append((credentials.getPassword() == null) ? "null" : credentials.getPassword());

    final byte[] base64password = Base64.encodeBase64(EncodingUtils.getBytes(tmp.toString(), charset), false);

    final CharArrayBuffer buffer = new CharArrayBuffer(32);
    if (proxy) {
        buffer.append(AUTH.PROXY_AUTH_RESP);
    } else {
        buffer.append(AUTH.WWW_AUTH_RESP);
    }
    buffer.append(": Basic ");
    buffer.append(base64password, 0, base64password.length);

    return new BufferedHeader(buffer);
}