Search in sources :

Example 36 with ClientException

use of com.microsoft.identity.common.exception.ClientException in project microsoft-authentication-library-common-for-android by AzureAD.

the class MsalBrokerResultAdapter method getBaseExceptionFromExceptionType.

@NonNull
private BaseException getBaseExceptionFromExceptionType(@NonNull final String exceptionType, @NonNull final BrokerResult brokerResult) {
    BaseException baseException;
    Logger.warn(TAG, "Received a " + exceptionType + " from Broker : " + brokerResult.getErrorCode());
    if (exceptionType.equalsIgnoreCase(UiRequiredException.sName)) {
        baseException = new UiRequiredException(brokerResult.getErrorCode(), brokerResult.getErrorMessage());
    } else if (exceptionType.equalsIgnoreCase(ServiceException.sName)) {
        baseException = getServiceException(brokerResult);
    } else if (exceptionType.equalsIgnoreCase(IntuneAppProtectionPolicyRequiredException.sName)) {
        baseException = getIntuneProtectionRequiredException(brokerResult);
    } else if (exceptionType.equalsIgnoreCase(UserCancelException.sName)) {
        baseException = new UserCancelException();
    } else if (exceptionType.equalsIgnoreCase(ClientException.sName)) {
        baseException = new ClientException(brokerResult.getErrorCode(), brokerResult.getErrorMessage());
    } else if (exceptionType.equalsIgnoreCase(ArgumentException.sName)) {
        baseException = new ArgumentException(ArgumentException.BROKER_TOKEN_REQUEST_OPERATION_NAME, brokerResult.getErrorCode(), brokerResult.getErrorMessage());
    } else {
        // Default to ClientException if null
        Logger.warn(TAG, " Exception type is unknown : " + exceptionType + brokerResult.getErrorCode() + ", defaulting to Client Exception ");
        baseException = new ClientException(brokerResult.getErrorCode(), brokerResult.getErrorMessage());
    }
    baseException.setCliTelemErrorCode(brokerResult.getCliTelemErrorCode());
    baseException.setCliTelemSubErrorCode(brokerResult.getCliTelemSubErrorCode());
    baseException.setCorrelationId(brokerResult.getCorrelationId());
    baseException.setSpeRing(brokerResult.getSpeRing());
    baseException.setRefreshTokenAge(brokerResult.getRefreshTokenAge());
    return baseException;
}
Also used : BaseException(com.microsoft.identity.common.exception.BaseException) UiRequiredException(com.microsoft.identity.common.exception.UiRequiredException) UserCancelException(com.microsoft.identity.common.exception.UserCancelException) ClientException(com.microsoft.identity.common.exception.ClientException) ArgumentException(com.microsoft.identity.common.exception.ArgumentException) NonNull(androidx.annotation.NonNull)

Example 37 with ClientException

use of com.microsoft.identity.common.exception.ClientException in project microsoft-authentication-library-common-for-android by AzureAD.

the class AzureActiveDirectoryWebViewClient method handleUrl.

/**
 * Interpret and take action on a redirect url.
 * This function will return true in every case save 1.  That is, when the URL is none of:
 * <ul><li>A urn containing an authorization challenge (starts with "urn:http-auth:PKeyAuth")</li>
 * <li>A url that starts with the same prefix as the tenant's redirect url</li>
 * <li>An explicit request to open the browser (starts with "browser://")</li>
 * <li>A request to install the auth broker (starts with "msauth://")</li>
 * <li>A request from WebCP (starts with "companyportal://")</li>
 * <li>It is a request that has the intent of starting the broker and the url starts with "browser://"</li>
 * <li>It <strong>does not</strong> begin with "https://".</li></ul>
 *
 * @param view The WebView that is initiating the callback.
 * @param url  The string representation of the url.
 * @return false if we will not take action on the url.
 */
private boolean handleUrl(final WebView view, final String url) {
    final String formattedURL = url.toLowerCase(Locale.US);
    if (isPkeyAuthUrl(formattedURL)) {
        Logger.info(TAG, "WebView detected request for pkeyauth challenge.");
        try {
            final PKeyAuthChallengeFactory factory = new PKeyAuthChallengeFactory();
            final PKeyAuthChallenge pKeyAuthChallenge = factory.getPKeyAuthChallenge(url);
            final PKeyAuthChallengeHandler pKeyAuthChallengeHandler = new PKeyAuthChallengeHandler(view, getCompletionCallback());
            pKeyAuthChallengeHandler.processChallenge(pKeyAuthChallenge);
        } catch (final ClientException exception) {
            Logger.error(TAG, exception.getErrorCode(), null);
            Logger.errorPII(TAG, exception.getMessage(), exception);
            returnError(exception.getErrorCode(), exception.getMessage());
            view.stopLoading();
        }
    } else if (isRedirectUrl(formattedURL)) {
        Logger.info(TAG, "Navigation starts with the redirect uri.");
        processRedirectUrl(view, url);
    } else if (isWebsiteRequestUrl(formattedURL)) {
        Logger.info(TAG, "It is an external website request");
        processWebsiteRequest(view, url);
    } else if (isInstallRequestUrl(formattedURL)) {
        Logger.info(TAG, "It is an install request");
        processInstallRequest(view, url);
    } else if (isWebCpUrl(formattedURL)) {
        Logger.info(TAG, "It is a request from WebCP");
        processWebCpRequest(view, url);
    } else if (isPlayStoreUrl(formattedURL)) {
        Logger.info(TAG, "Request to open PlayStore.");
        return processPlayStoreURL(view, url);
    } else if (isAuthAppMFAUrl(formattedURL)) {
        Logger.info(TAG, "Request to link account with Authenticator.");
        processAuthAppMFAUrl(url);
    } else if (isInvalidRedirectUri(url)) {
        Logger.info(TAG, "Check for Redirect Uri.");
        processInvalidRedirectUri(view, url);
    } else if (isBlankPageRequest(formattedURL)) {
        Logger.info(TAG, "It is an blank page request");
    } else if (isUriSSLProtected(formattedURL)) {
        Logger.info(TAG, "Check for SSL protection");
        processSSLProtectionCheck(view, url);
    } else {
        Logger.info(TAG, "This maybe a valid URI, but no special handling for this mentioned URI, hence deferring to WebView for loading.");
        processInvalidUrl(url);
        return false;
    }
    return true;
}
Also used : PKeyAuthChallenge(com.microsoft.identity.common.internal.ui.webview.challengehandlers.PKeyAuthChallenge) PKeyAuthChallengeFactory(com.microsoft.identity.common.internal.ui.webview.challengehandlers.PKeyAuthChallengeFactory) PKeyAuthChallengeHandler(com.microsoft.identity.common.internal.ui.webview.challengehandlers.PKeyAuthChallengeHandler) ClientException(com.microsoft.identity.common.exception.ClientException)

Example 38 with ClientException

use of com.microsoft.identity.common.exception.ClientException in project azure-activedirectory-library-for-android by AzureAD.

the class ChallengeResponseBuilder method getDeviceCertResponse.

private ChallengeResponse getDeviceCertResponse(ChallengeRequest request) throws AuthenticationException {
    ChallengeResponse response = getNoDeviceCertResponse(request);
    response.mSubmitUrl = request.mSubmitUrl;
    // If not device cert exists, alias or privatekey will not exist on the
    // device
    @SuppressWarnings("unchecked") Class<IDeviceCertificate> certClazz = (Class<IDeviceCertificate>) AuthenticationSettings.INSTANCE.getDeviceCertificateProxy();
    if (certClazz != null) {
        IDeviceCertificate deviceCertProxy = getWPJAPIInstance(certClazz);
        if (deviceCertProxy.isValidIssuer(request.mCertAuthorities) || deviceCertProxy.getThumbPrint() != null && deviceCertProxy.getThumbPrint().equalsIgnoreCase(request.mThumbprint)) {
            RSAPrivateKey privateKey = deviceCertProxy.getRSAPrivateKey();
            if (privateKey == null) {
                throw new AuthenticationException(ADALError.KEY_CHAIN_PRIVATE_KEY_EXCEPTION);
            }
            try {
                String jwt = mJWSBuilder.generateSignedJWT(request.mNonce, request.mSubmitUrl, privateKey, deviceCertProxy.getRSAPublicKey(), deviceCertProxy.getCertificate());
                response.mAuthorizationHeaderValue = String.format("%s AuthToken=\"%s\",Context=\"%s\",Version=\"%s\"", AuthenticationConstants.Broker.CHALLENGE_RESPONSE_TYPE, jwt, request.mContext, request.mVersion);
                Logger.v(TAG, "Receive challenge response. ", "Challenge response:" + response.mAuthorizationHeaderValue, null);
            } catch (final ClientException e) {
                final String errorCode = e.getErrorCode();
                ADALError which;
                switch(errorCode) {
                    case ErrorStrings.UNSUPPORTED_ENCODING:
                        which = ADALError.ENCODING_IS_NOT_SUPPORTED;
                        break;
                    case ErrorStrings.CERTIFICATE_ENCODING_ERROR:
                        which = ADALError.CERTIFICATE_ENCODING_ERROR;
                        break;
                    case ErrorStrings.KEY_CHAIN_PRIVATE_KEY_EXCEPTION:
                        which = ADALError.KEY_CHAIN_PRIVATE_KEY_EXCEPTION;
                        break;
                    case ErrorStrings.SIGNATURE_EXCEPTION:
                        which = ADALError.SIGNATURE_EXCEPTION;
                        break;
                    case ErrorStrings.NO_SUCH_ALGORITHM:
                        which = ADALError.DEVICE_NO_SUCH_ALGORITHM;
                        break;
                    default:
                        which = ADALError.DEVICE_CERTIFICATE_RESPONSE_FAILED;
                }
                throw new AuthenticationException(which, e.getMessage());
            }
        }
    }
    return response;
}
Also used : ClientException(com.microsoft.identity.common.exception.ClientException) RSAPrivateKey(java.security.interfaces.RSAPrivateKey)

Example 39 with ClientException

use of com.microsoft.identity.common.exception.ClientException in project microsoft-authentication-library-common-for-android by AzureAD.

the class AzureActiveDirectoryAuthorizationResultFactoryTest method testBrowserCodeAuthenticationException.

@Test
public void testBrowserCodeAuthenticationException() {
    Intent intent = new Intent();
    Bundle bundle = new Bundle();
    String mockError = "mockError";
    String mockErrorDescription = "mockErrorDescription";
    ClientException exception = new ClientException(mockError, mockErrorDescription);
    bundle.putSerializable(AuthenticationConstants.Browser.RESPONSE_AUTHENTICATION_EXCEPTION, exception);
    intent.putExtras(bundle);
    AuthorizationResult result = mAuthorizationResultFactory.createAuthorizationResult(AuthenticationConstants.UIResponse.BROWSER_CODE_AUTHENTICATION_EXCEPTION, intent, getAADRequest());
    assertNotNull(result);
    assertNull(result.getAuthorizationResponse());
    assertEquals(AuthorizationStatus.FAIL, result.getAuthorizationStatus());
    AuthorizationErrorResponse errorResponse = result.getAuthorizationErrorResponse();
    assertNotNull(errorResponse);
    assertEquals(mockError, errorResponse.getError());
    assertEquals(mockErrorDescription, errorResponse.getErrorDescription());
}
Also used : AuthorizationErrorResponse(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationErrorResponse) AzureActiveDirectoryAuthorizationErrorResponse(com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectoryAuthorizationErrorResponse) MicrosoftAuthorizationErrorResponse(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftAuthorizationErrorResponse) Bundle(android.os.Bundle) Intent(android.content.Intent) ClientException(com.microsoft.identity.common.exception.ClientException) AuthorizationResult(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult) AzureActiveDirectoryAuthorizationResult(com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectoryAuthorizationResult) MicrosoftAuthorizationResult(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftAuthorizationResult) Test(org.junit.Test)

Example 40 with ClientException

use of com.microsoft.identity.common.exception.ClientException in project microsoft-authentication-library-common-for-android by AzureAD.

the class DevicePopManager method encrypt.

@Override
public byte[] encrypt(@NonNull final Cipher cipher, @NonNull final byte[] plaintext) throws ClientException {
    String errCode;
    Exception exception;
    final String methodName = ":encrypt";
    try {
        // Load our key material
        final KeyStore.PrivateKeyEntry privateKeyEntry = mKeyManager.getEntry();
        // Get a ref to our public key
        final PublicKey publicKey = privateKeyEntry.getCertificate().getPublicKey();
        // Init our Cipher
        final javax.crypto.Cipher input = javax.crypto.Cipher.getInstance(cipher.toString());
        if (cipher.getParameters() != null) {
            input.init(javax.crypto.Cipher.ENCRYPT_MODE, publicKey, cipher.getParameters());
        } else {
            input.init(javax.crypto.Cipher.ENCRYPT_MODE, publicKey);
        }
        return input.doFinal(plaintext);
    } catch (final InvalidKeyException e) {
        errCode = INVALID_KEY;
        exception = e;
    } catch (final UnrecoverableEntryException e) {
        errCode = INVALID_PROTECTION_PARAMS;
        exception = e;
    } catch (final NoSuchAlgorithmException e) {
        errCode = NO_SUCH_ALGORITHM;
        exception = e;
    } catch (final KeyStoreException e) {
        errCode = KEYSTORE_NOT_INITIALIZED;
        exception = e;
    } catch (final NoSuchPaddingException e) {
        errCode = NO_SUCH_PADDING;
        exception = e;
    } catch (final InvalidAlgorithmParameterException e) {
        errCode = INVALID_ALG_PARAMETER;
        exception = e;
    } catch (final BadPaddingException e) {
        errCode = BAD_PADDING;
        exception = e;
    } catch (final IllegalBlockSizeException e) {
        errCode = INVALID_BLOCK_SIZE;
        exception = e;
    }
    final ClientException clientException = new ClientException(errCode, exception.getMessage(), exception);
    Logger.error(TAG + methodName, errCode, exception);
    throw clientException;
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) RSAPublicKey(java.security.interfaces.RSAPublicKey) PublicKey(java.security.PublicKey) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException) KeyStore(java.security.KeyStore) JOSEException(com.nimbusds.jose.JOSEException) KeyStoreException(java.security.KeyStoreException) JSONException(org.json.JSONException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) StrongBoxUnavailableException(android.security.keystore.StrongBoxUnavailableException) SignatureException(java.security.SignatureException) ProviderException(java.security.ProviderException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) KeyPermanentlyInvalidatedException(android.security.keystore.KeyPermanentlyInvalidatedException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) ClientException(com.microsoft.identity.common.exception.ClientException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) BadPaddingException(javax.crypto.BadPaddingException) NoSuchProviderException(java.security.NoSuchProviderException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) ClientException(com.microsoft.identity.common.exception.ClientException)

Aggregations

ClientException (com.microsoft.identity.common.exception.ClientException)74 IOException (java.io.IOException)23 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)23 InvalidKeyException (java.security.InvalidKeyException)18 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)17 KeyStoreException (java.security.KeyStoreException)17 BadPaddingException (javax.crypto.BadPaddingException)17 IllegalBlockSizeException (javax.crypto.IllegalBlockSizeException)17 NoSuchPaddingException (javax.crypto.NoSuchPaddingException)17 UnrecoverableEntryException (java.security.UnrecoverableEntryException)15 CertificateException (java.security.cert.CertificateException)13 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)12 SignatureException (java.security.SignatureException)11 KeyPermanentlyInvalidatedException (android.security.keystore.KeyPermanentlyInvalidatedException)10 StrongBoxUnavailableException (android.security.keystore.StrongBoxUnavailableException)10 NonNull (androidx.annotation.NonNull)10 JOSEException (com.nimbusds.jose.JOSEException)10 NoSuchProviderException (java.security.NoSuchProviderException)10 ProviderException (java.security.ProviderException)10 JSONException (org.json.JSONException)10