Example usage for org.apache.commons.httpclient.auth AuthenticationException AuthenticationException

List of usage examples for org.apache.commons.httpclient.auth AuthenticationException AuthenticationException

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.auth AuthenticationException AuthenticationException.

Prototype

public AuthenticationException(String paramString, Throwable paramThrowable) 

Source Link

Usage

From source file:davmail.http.SpNegoScheme.java

/**
 * Produces Negotiate authorization string for the given set of
 * {@link Credentials}./*from  w  ww . j a v a  2  s  .  com*/
 *
 * @param credentials The set of credentials to be used for authentication
 * @param httpMethod  The method being authenticated
 * @return an Negotiate authorization string
 * @throws org.apache.commons.httpclient.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
 */
public String authenticate(Credentials credentials, HttpMethod httpMethod) throws AuthenticationException {
    if (this.state == UNINITIATED) {
        throw new IllegalStateException("Negotiate authentication process has not been initiated");
    }
    String host = null;
    try {
        host = httpMethod.getURI().getHost();
    } catch (URIException e) {
        // ignore
    }
    if (host == null) {
        Header header = httpMethod.getRequestHeader("Host");
        if (header != null) {
            host = header.getValue();
            if (host.indexOf(':') >= 0) {
                host = host.substring(0, host.indexOf(':'));
            }
        }
    }
    if (host == null) {
        throw new IllegalStateException("Negotiate authentication failed: empty host");
    }

    // no credentials needed
    String response;
    try {
        if (this.state == INITIATED || this.state == FAILED) {
            // send initial token to server
            response = EncodingUtil.getAsciiString(
                    Base64.encodeBase64(KerberosHelper.initSecurityContext("HTTP", host, new byte[0])));
            this.state = TYPE1_MSG_GENERATED;
        } else {
            // send challenge response
            response = EncodingUtil.getAsciiString(
                    Base64.encodeBase64(KerberosHelper.initSecurityContext("HTTP", host, serverToken)));
            this.state = TYPE3_MSG_GENERATED;
        }
    } catch (GSSException gsse) {
        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 CredentialsNotAvailableException(gsse.getMessage(), gsse);
        if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN
                || gsse.getMajor() == GSSException.OLD_TOKEN)
            throw new AuthChallengeException(gsse.getMessage(), gsse);
        // other error
        throw new AuthenticationException(gsse.getMessage(), gsse);
    } catch (LoginException e) {
        state = FAILED;
        throw new InvalidCredentialsException(e.getMessage(), e);
    }
    return "Negotiate " + response;
}

From source file:org.apache.abdera.ext.oauth.OAuthScheme.java

private String generateSignature(OAuthCredentials credentials, HttpMethod method, String nonce, long timestamp)
        throws AuthenticationException {
    try {//from  w  w  w . j a  va 2 s  . c om
        String baseString = method.getName().toUpperCase() + method.getURI().toString()
                + OAUTH_KEYS.OAUTH_CONSUMER_KEY.toLowerCase() + "=" + credentials.getConsumerKey()
                + OAUTH_KEYS.OAUTH_TOKEN.toLowerCase() + "=" + credentials.getToken()
                + OAUTH_KEYS.OAUTH_SIGNATURE_METHOD.toLowerCase() + "=" + credentials.getSignatureMethod()
                + OAUTH_KEYS.OAUTH_TIMESTAMP.toLowerCase() + "=" + timestamp
                + OAUTH_KEYS.OAUTH_NONCE.toLowerCase() + "=" + nonce + OAUTH_KEYS.OAUTH_VERSION.toLowerCase()
                + "=" + credentials.getVersion();
        return sign(credentials.getSignatureMethod(), URLEncoder.encode(baseString, "UTF-8"),
                credentials.getCert());
    } catch (URIException e) {
        throw new AuthenticationException(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        throw new AuthenticationException(e.getMessage(), e);
    }
}

From source file:org.apache.abdera.ext.oauth.OAuthScheme.java

private String generateNonce() throws AuthenticationException {
    try {//w w  w  .jav a2s .  c o m
        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
        byte[] temp = new byte[NONCE_LENGTH];
        sr.nextBytes(temp);
        String n = new String(Hex.encodeHex(temp));
        return n;
    } catch (Exception e) {
        throw new AuthenticationException(e.getMessage(), e);
    }
}

From source file:org.apache.abdera.ext.oauth.OAuthScheme.java

private String sign(String method, String baseString, Certificate cert) throws AuthenticationException {
    if (method.equalsIgnoreCase("HMAC-MD5") || method.equalsIgnoreCase("HMAC-SHA1")) {
        try {/*from w  ww  .  j a v a2  s  . c om*/
            String[] tokens = method.split("-");
            String methodName = tokens[0].substring(0, 1).toUpperCase() + tokens[0].substring(1).toLowerCase()
                    + tokens[1];
            KeyGenerator kg = KeyGenerator.getInstance(methodName);

            Mac mac = Mac.getInstance(kg.getAlgorithm());
            mac.init(kg.generateKey());
            byte[] result = mac.doFinal(baseString.getBytes());

            return new String(Base64.encodeBase64(result));
        } catch (Exception e) {
            throw new AuthenticationException(e.getMessage(), e);
        }
    } else if (method.equalsIgnoreCase("md5")) {
        return new String(Base64.encodeBase64(DigestUtils.md5(baseString)));
    } else if (method.equalsIgnoreCase("sha1")) {
        return new String(Base64.encodeBase64(DigestUtils.sha(baseString)));
    } else if (method.equalsIgnoreCase("RSA-SHA1")) {
        if (cert == null) {
            throw new AuthenticationException("a cert is mandatory to use SHA1 with RSA");
        }
        try {
            Cipher cipher = Cipher.getInstance("SHA1withRSA");
            cipher.init(Cipher.ENCRYPT_MODE, cert);
            byte[] result = cipher.doFinal(baseString.getBytes());
            return new String(Base64.encodeBase64(result));
        } catch (Exception e) {
            throw new AuthenticationException(e.getMessage(), e);
        }
    } else {
        throw new AuthenticationException("unsupported algorithm method: " + method);
    }
}

From source file:org.apache.abdera.ext.wsse.WSSEAuthScheme.java

private String generatePasswordDigest(String password, String nonce, AtomDate date)
        throws AuthenticationException {
    String temp = nonce + date.getValue() + password;
    try {/*from w  w w  . j  av a  2 s.  c  o m*/
        MessageDigest md = MessageDigest.getInstance("SHA1");
        return new String(Base64.encodeBase64(md.digest(temp.getBytes())));
    } catch (Exception e) {
        throw new AuthenticationException(e.getMessage(), e);
    }
}

From source file:org.jetbrains.tfsIntegration.webservice.auth.NTLM2Scheme.java

protected String getType3MessageResponse(String type2message, NTCredentials ntcredentials,
        HttpMethodParams params) throws AuthenticationException {
    Type2Message t2m;/*from  w w  w  . jav  a  2s .  c  o  m*/
    try {
        t2m = new Type2Message(Base64.decode(type2message));
    } catch (IOException ex) {
        throw new AuthenticationException("Invalid Type2 message", ex);
    }
    Type3Message t3m = new Type3Message(t2m, ntcredentials.getPassword(), ntcredentials.getDomain(),
            ntcredentials.getUserName(), Workstation.getComputerName(), MESSAGE_3_DEFAULT_FLAGS);
    return Base64.encode(t3m.toByteArray());
}

From source file:org.wso2.carbon.integration.core.ServerLogin.java

public void logout() throws Exception {
    try {//from www. j a va 2s.c o  m
        log.debug("Logout method called in authentication class");
        authenticationAdminStub.logout();
    } catch (Exception e) {
        String msg = "Error occurred while logging out";
        log.debug(msg);
        throw new AuthenticationException(msg, e);
    }
}

From source file:org.wso2.carbon.integration.framework.LoginLogoutUtil.java

/**
 * Log out from a Carbon server you logged in to by calling the {@link #login} method
 * @param carbonManagementContext context of the application
 * @throws Exception If an error occurs while logging out
 *///w  ww  .j a va2  s  .  c o  m
public void logout(String carbonManagementContext) throws Exception {
    AuthenticationAdminStub authenticationAdminStub;
    if (carbonManagementContext == null || carbonManagementContext.trim().equals("")) {
        authenticationAdminStub = getAuthAdminStub();
    } else {
        authenticationAdminStub = getAuthAdminStub(carbonManagementContext);
    }
    try {
        Options options = authenticationAdminStub._getServiceClient().getOptions();
        options.setProperty(org.apache.axis2.transport.http.HTTPConstants.COOKIE_STRING, sessionCookie);
        authenticationAdminStub.logout();
    } catch (Exception e) {
        String msg = "Error occurred while logging out";
        log.error(msg, e);
        throw new AuthenticationException(msg, e);
    }
}

From source file:org.wso2.carbon.mediator.ntlm.CustomNTLMAuthScheme.java

/**
 * Produces NTLM authorization string for the given set of
 * {@link Credentials}./*  w  w w .  ja v a  2 s  .c o  m*/
 *
 * @param credentials
 *            The set of credentials to be used for athentication
 * @param method
 *            The method being authenticated
 *
 * @throws 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 an NTLM authorization string
 *
 * @since 3.0
 */
public String authenticate(Credentials credentials, HttpMethod method) throws AuthenticationException {
    LOG.trace("enter NTLMScheme.authenticate (Credentials, HttpMethod)");

    if (this.state == UNINITIATED) {
        throw new IllegalStateException("NTLM authentication process has not been initiated");
    }

    NTCredentials ntcredentials = null;
    try {
        ntcredentials = (NTCredentials) credentials;
    } catch (ClassCastException e) {
        throw new InvalidCredentialsException(
                "Credentials cannot be used for NTLM authentication: " + credentials.getClass().getName());
    }
    byte[] msgBytes = null;
    String response = null;
    if (this.state == INITIATED) {
        Type1Message msg = new Type1Message();
        // @see http://davenport.sourceforge.net/ntlm.html#theType1Message
        // dont' support Unicode
        // negotiate OEM
        // request authentication realm in Type2 response
        // not signed
        // not encrypted
        // not authenticated
        // no lan manager key
        // negotiate NTLM
        msg.setFlags(0x5206);
        msg.setSuppliedWorkstation(ntcredentials.getHost());
        msg.setSuppliedDomain(ntcredentials.getDomain());
        msgBytes = msg.toByteArray();
        this.state = TYPE1_MSG_GENERATED;
    } else if (this.state == TYPE2_MSG_RECEIVED) {
        byte[] msg2Bytes = Base64.decodeBase64(
                EncodingUtil.getBytes(this.ntlmChallenge, method.getParams().getCredentialCharset()));
        try {
            Type2Message msg2 = new Type2Message(msg2Bytes);
            int flags = Type3Message.NTLMSSP_NEGOTIATE_OEM | Type3Message.NTLMSSP_NEGOTIATE_LM_KEY;

            Type3Message msg3 = new Type3Message(msg2, ntcredentials.getPassword(), ntcredentials.getDomain(),
                    ntcredentials.getUserName(), ntcredentials.getHost(), flags);

            msgBytes = msg3.toByteArray();
        } catch (IOException ex) {
            throw new AuthenticationException("unable to parse Type2Message", ex);
        }
        this.state = TYPE3_MSG_GENERATED;
    } else {
        throw new RuntimeException("failed to authenticate");
    }
    response = EncodingUtil.getAsciiString(Base64.encodeBase64(msgBytes));
    return "NTLM " + response;
}

From source file:org.zaproxy.zap.network.ZapNTLMEngineImpl.java

/** Calculates RC4 */
static byte[] RC4(final byte[] value, final byte[] key) throws AuthenticationException {
    try {//from   w  w w  .j a  v  a2 s .c  o m
        final Cipher rc4 = Cipher.getInstance("RC4");
        rc4.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "RC4"));
        return rc4.doFinal(value);
    } catch (Exception e) {
        throw new AuthenticationException(e.getMessage(), e);
    }
}