Example usage for org.apache.http.auth AuthenticationException AuthenticationException

List of usage examples for org.apache.http.auth AuthenticationException AuthenticationException

Introduction

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

Prototype

public AuthenticationException(final String message, final Throwable cause) 

Source Link

Document

Creates a new AuthenticationException with the specified detail message and cause.

Usage

From source file:org.ohmage.app.OhmageErrorHandler.java

@Override
public Throwable handleError(RetrofitError cause) {

    Response r = cause.getResponse();
    if (r != null && r.getStatus() == 401) {
        // invalidate the access token
        AccountManager accountManager = AccountManager.get(Ohmage.app());
        Account[] accounts = accountManager.getAccountsByType(AuthUtil.ACCOUNT_TYPE);
        if (accounts.length != 0) {
            String token = accountManager.peekAuthToken(accounts[0], AuthUtil.AUTHTOKEN_TYPE);
            if (token != null) {
                accountManager.invalidateAuthToken(AuthUtil.ACCOUNT_TYPE, token);
                Log.e(TAG, "Invalidated " + token);
            }//from   w  w w .j  a  v  a2s.  c om
        }
        return new AuthenticationException("Error authenticating with ohmage", cause);
    }

    return cause;
}

From source file:net.oauth.client.httpclient4.OAuthScheme.java

public Header authenticate(Credentials credentials, HttpRequest request) throws AuthenticationException {
    String uri;/*from  w  w w.  j a va2 s. c  o m*/
    String method;
    HttpUriRequest uriRequest = getHttpUriRequest(request);
    if (uriRequest != null) {
        uri = uriRequest.getURI().toString();
        method = uriRequest.getMethod();
    } else {
        // Some requests don't include the server name in the URL.
        RequestLine requestLine = request.getRequestLine();
        uri = requestLine.getUri();
        method = requestLine.getMethod();
    }
    try {
        OAuthMessage message = new OAuthMessage(method, uri, null);
        OAuthAccessor accessor = getAccessor(credentials);
        message.addRequiredParameters(accessor);
        String authorization = message.getAuthorizationHeader(getRealm());
        return new BasicHeader("Authorization", authorization);
    } catch (Exception e) {
        throw new AuthenticationException(null, e);
    }
}

From source file:com.soundcloud.playerapi.OAuth2Scheme.java

@Override
public Header authenticate(Credentials credentials, HttpRequest request) throws AuthenticationException {
    final String usedToken = extractToken(request);
    // make sure only one refresh request gets sent out
    synchronized (OAuth2Scheme.class) {
        final Token apiToken = mApi.getToken();
        if (apiToken == null || apiToken.access == null || apiToken.access.equals(usedToken)) {
            if (mApi.invalidateToken() == null) {
                // we actually need to refresh it ourselves
                try {
                    mApi.refreshToken();
                } catch (IOException e) {
                    throw new AuthenticationException("Error refreshing token", e);
                } catch (IllegalStateException e) {
                    throw new AuthenticationException("Error refreshing token", e);
                }//  ww w. j  a  v a 2s. c o  m
            }
        }
        return ApiWrapper.createOAuthHeader(mApi.getToken());
    }
}

From source file:com.joyent.http.signature.apache.httpclient.HttpSignatureCache.java

/**
 * Method that attempts to get a valid cached signature based on the
 * specified parameters. If a cached credential is not valid, then
 * a new signature will be generated and stored for later use in caching.
 *
 * @param stringDate date to use for HTTP signature
 * @param signer signer class to use for generating signature
 * @param keyPair cryptographic key pair to use for generating signature
 *
 * @return a valid HTTP signature string to be passed as a header value
 *
 * @throws AuthenticationException thrown if there is a problem authenticating the signature
 *///from ww  w . j a v a 2 s . c o  m
synchronized String updateAndGetSignature(final String stringDate, final Signer signer, final KeyPair keyPair)
        throws AuthenticationException {

    // Signing date time is equal, so we returned cached signature
    // stringDate parameter should *never* be null or blank
    if (lastDate.equals(stringDate)) {
        return lastSignature;
    }

    lastDate = stringDate;

    final String login = credentials.getUserPrincipal().getName();

    // If date didn't match, then we calculate signature and store it
    try {
        final String authz = signer.createAuthorizationHeader(login, keyPair, stringDate);
        lastSignature = authz;

        return authz;
    } catch (HttpSignatureException e) {
        String details = String.format("Unable to authenticate [%s] " + "using keypair [%s]", login, keyPair);
        throw new AuthenticationException(details, e);
    }
}

From source file:com.example.jumpnote.android.jsonrpc.AuthenticatedJsonRpcJavaClient.java

public void blockingAuthenticateAccount(final Account account, final int needAuthAction,
        boolean forceReauthenticate) throws AuthenticationException, OperationCanceledException,
        RequestedUserAuthenticationException, InvalidAuthTokenException {

    String existingToken = mTokenStoreHelper.getToken(account);
    if (!forceReauthenticate && existingToken != null) {
        BasicClientCookie c = new BasicClientCookie("ACSID", existingToken);
        try {//from w ww .ja  va 2s .  c om
            c.setDomain(new URI(Config.SERVER_BASE_URL).getHost());
            mHttpClient.getCookieStore().addCookie(c);
            return;
        } catch (URISyntaxException e) {
        }
    }

    // Get an auth token for this account.
    AccountManager am = AccountManager.get(mContext);
    Bundle authBundle = null;
    String authToken = null;

    // Block on getting the auth token result.
    try {
        authBundle = am.getAuthToken(account, APPENGINE_SERVICE_NAME, needAuthAction == NEED_AUTH_NOTIFICATION,
                null, null).getResult();
    } catch (IOException e) {
        throw new AuthenticationException("IOException while getting auth token.", e);
    } catch (AuthenticatorException e) {
        throw new AuthenticationException("AuthenticatorException while getting auth token.", e);
    }

    if (authBundle.containsKey(AccountManager.KEY_INTENT) && needAuthAction == NEED_AUTH_INTENT) {
        Intent authRequestIntent = (Intent) authBundle.get(AccountManager.KEY_INTENT);
        mContext.startActivity(authRequestIntent);
        throw new RequestedUserAuthenticationException();
    } else if (authBundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
        authToken = authBundle.getString(AccountManager.KEY_AUTHTOKEN);
    }

    if (authToken == null) {
        throw new AuthenticationException("Retrieved auth token was null.");
    }

    try {
        blockingAuthenticateWithToken(account, authToken);
    } catch (InvalidAuthTokenException e) {
        am.invalidateAuthToken(account.type, authToken);
        throw e;
    }
}

From source file:com.samsung.android.remindme.jsonrpc.AuthenticatedJsonRpcJavaClient.java

public void blockingAuthenticateAccount(final Account account, final int needAuthAction,
        boolean forceReauthenticate) throws AuthenticationException, OperationCanceledException,
        RequestedUserAuthenticationException, InvalidAuthTokenException {

    String existingToken = mTokenStoreHelper.getToken(account);
    if (!forceReauthenticate && existingToken != null) {
        BasicClientCookie c = new BasicClientCookie("ACSID", existingToken);
        try {/*from  w ww  . j av  a2  s .  c o m*/
            c.setDomain(new URI(Config.SERVER_BASE_URL).getHost());
            mHttpClient.getCookieStore().addCookie(c);
            return;
        } catch (URISyntaxException e) {
        }
    }

    // Get an auth token for this account.
    AccountManager am = AccountManager.get(mContext);
    Bundle authBundle = null;
    String authToken = null;

    // Block on getting the auth token result.
    try {
        authBundle = am.getAuthToken(account, APPENGINE_SERVICE_NAME, needAuthAction == NEED_AUTH_NOTIFICATION,
                null, null).getResult();
    } catch (IOException e) {
        throw new AuthenticationException("IOException while getting auth token.", e);
    } catch (AuthenticatorException e) {
        throw new AuthenticationException("AuthenticatorException while getting auth token.", e);
    }

    if (authBundle.containsKey(AccountManager.KEY_INTENT) && needAuthAction == NEED_AUTH_INTENT) {
        Intent authRequestIntent = (Intent) authBundle.get(AccountManager.KEY_INTENT);
        mContext.startActivity(authRequestIntent);
        throw new RequestedUserAuthenticationException();
    } else if (authBundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
        authToken = authBundle.getString(AccountManager.KEY_AUTHTOKEN);
        System.out.println(authToken);
        System.out.println(AccountManager.KEY_AUTHTOKEN);
    }

    if (authToken == null) {
        throw new AuthenticationException("Retrieved auth token was null.");
    }

    try {
        blockingAuthenticateWithToken(account, authToken);
    } catch (InvalidAuthTokenException e) {
        am.invalidateAuthToken(account.type, authToken);
        throw e;
    }
}

From source file:nl.esciencecenter.octopus.webservice.mac.MacScheme.java

/**
 * Computes RFC 2104-compliant HMAC signature.
 *
 * @param data//from w  ww . j a  v  a2s .co  m
 *            The data to be signed.
 * @param key
 *            The signing key.
 * @param algorithm
 *            MAC algorithm implemented by javax.crypto.MAC
 * @return The Base64-encoded RFC 2104-compliant HMAC signature.
 * @throws AuthenticationException
 *             when signature generation fails
 */
private String calculateRFC2104HMAC(String data, String key, String algorithm) throws AuthenticationException {
    try {
        Mac mac = Mac.getInstance(algorithm);
        SecretKeySpec macKey = new SecretKeySpec(key.getBytes(), "RAW");
        mac.init(macKey);
        byte[] signature = mac.doFinal(data.getBytes());
        return Base64.encodeBase64String(signature);
    } catch (InvalidKeyException e) {
        throw new AuthenticationException("Failed to generate HMAC: " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new AuthenticationException("Algorithm is not supported", e);
    }
}

From source file:nl.esciencecenter.osmium.mac.MacScheme.java

/**
 * Computes RFC 2104-compliant HMAC signature.
 *
 * @param data//from  w ww . j a v a2 s  . c  o m
 *            The data to be signed.
 * @param key
 *            The signing key.
 * @param algorithm
 *            MAC algorithm implemented by javax.crypto.MAC
 * @return The Base64-encoded RFC 2104-compliant HMAC signature.
 * @throws AuthenticationException
 *             when signature generation fails
 */
private String calculateRFC2104HMAC(String data, String key, String algorithm) throws AuthenticationException {
    try {
        Mac mac = Mac.getInstance(algorithm);
        SecretKeySpec macKey = new SecretKeySpec(key.getBytes(StandardCharsets.US_ASCII), "RAW");
        mac.init(macKey);
        byte[] signature = mac.doFinal(data.getBytes(StandardCharsets.US_ASCII));
        return Base64.encodeBase64String(signature);
    } catch (InvalidKeyException e) {
        throw new AuthenticationException("Failed to generate HMAC: " + e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new AuthenticationException("Algorithm is not supported", e);
    }
}

From source file:com.example.jumpnote.android.jsonrpc.AuthenticatedJsonRpcJavaClient.java

private void blockingAuthenticateWithToken(Account account, String authToken)
        throws AuthenticationException, InvalidAuthTokenException {
    // Promote the given auth token into an App Engine ACSID token.
    HttpGet httpGet = new HttpGet(String.format(mAuthUrlTemplate, authToken));
    String acsidToken = null;//from  ww  w  .j a  v  a 2s  . co  m

    try {
        HttpResponse response = mHttpClient.execute(httpGet);
        if (response.getStatusLine().getStatusCode() == 403) {
            throw new InvalidAuthTokenException();
        }

        List<Cookie> cookies = mHttpClient.getCookieStore().getCookies();
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("ACSID")) {
                acsidToken = cookie.getValue();
                break;
            }
        }

        if (acsidToken == null && response.getStatusLine().getStatusCode() == 500) {
            // If no ACSID cookie was passed, it usually means the auth token was invalid;
            throw new InvalidAuthTokenException("ACSID cookie not found in HTTP response: "
                    + response.getStatusLine().toString() + "; assuming invalid auth token.");
        }

        mTokenStoreHelper.putToken(account, acsidToken);
    } catch (ClientProtocolException e) {
        throw new AuthenticationException("HTTP Protocol error authenticating to App Engine", e);
    } catch (IOException e) {
        throw new AuthenticationException("IOException authenticating to App Engine", e);
    }
}

From source file:org.apache.http.contrib.auth.AWSScheme.java

/**
 * Computes RFC 2104-compliant HMAC signature.
 *
 * @param data/*from   ww w  .  j ava 2s.c o  m*/
 *            The data to be signed.
 * @param key
 *            The signing key.
 * @return The Base64-encoded RFC 2104-compliant HMAC signature.
 * @throws RuntimeException
 *             when signature generation fails
 */
private static String calculateRFC2104HMAC(final String data, final String key) throws AuthenticationException {
    try {
        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);

        // get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);

        // compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(data.getBytes());

        // base64-encode the hmac
        return Base64.encodeBase64String(rawHmac);

    } catch (InvalidKeyException ex) {
        throw new AuthenticationException("Failed to generate HMAC: " + ex.getMessage(), ex);
    } catch (NoSuchAlgorithmException ex) {
        throw new AuthenticationException(HMAC_SHA1_ALGORITHM + " algorithm is not supported", ex);
    }
}