Search in sources :

Example 21 with ClientException

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

the class CommandDispatcherTest method testSubmitSilentWithTerminalException.

@Test
public void testSubmitSilentWithTerminalException() {
    final String errorCode = "anError";
    final CountDownLatch testLatch = new CountDownLatch(1);
    CommandDispatcher.submitSilent(new CommandThrowingIErrorInformationException(getEmptyTestParams(), new CommandCallback<String, Exception>() {

        @Override
        public void onCancel() {
            testLatch.countDown();
            Assert.fail();
        }

        @Override
        public void onError(Exception error) {
            Assert.assertEquals(ClientException.class, error.getClass());
            Assert.assertEquals(errorCode, ((ClientException) error).getErrorCode());
            testLatch.countDown();
        }

        @Override
        public void onTaskCompleted(String s) {
            testLatch.countDown();
            Assert.fail();
        }
    }, errorCode));
}
Also used : CountDownLatch(java.util.concurrent.CountDownLatch) CommandCallback(com.microsoft.identity.common.internal.commands.CommandCallback) TerminalException(com.microsoft.identity.common.exception.TerminalException) ClientException(com.microsoft.identity.common.exception.ClientException) Test(org.junit.Test)

Example 22 with ClientException

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

the class MsalCppOAuth2TokenCache method saveCredentials.

/**
 * @param accountRecord : AccountRecord associated with the input credentials, can be null.
 * @param credentials   : list of Credential which can include AccessTokenRecord, IdTokenRecord and RefreshTokenRecord.
 * @throws ClientException : If the supplied Account or Credential are null or schema invalid.
 */
public synchronized void saveCredentials(@Nullable final AccountRecord accountRecord, @NonNull final Credential... credentials) throws ClientException {
    if (credentials == null || credentials.length == 0) {
        throw new ClientException("Credential array passed in is null or empty");
    }
    RefreshTokenRecord refreshTokenRecord = null;
    for (final Credential credential : credentials) {
        if (credential instanceof RefreshTokenRecord) {
            refreshTokenRecord = (RefreshTokenRecord) credential;
        }
        if (credential instanceof AccessTokenRecord && !isAccessTokenSchemaCompliant((AccessTokenRecord) credential)) {
            throw new ClientException(CREDENTIAL_IS_SCHEMA_NONCOMPLIANT, "AT is missing a required property.");
        }
    }
    if (accountRecord != null && refreshTokenRecord != null) {
        // MSAL C++ writes credentials first and then the account.
        // For a new account, this will not be true as the accountRecord will be null.
        // For existing accounts, we would remove the old refresh token if present.
        removeRefreshTokenIfNeeded(accountRecord, refreshTokenRecord);
    }
    saveCredentialsInternal(credentials);
}
Also used : Credential(com.microsoft.identity.common.internal.dto.Credential) RefreshTokenRecord(com.microsoft.identity.common.internal.dto.RefreshTokenRecord) ClientException(com.microsoft.identity.common.exception.ClientException) AccessTokenRecord(com.microsoft.identity.common.internal.dto.AccessTokenRecord)

Example 23 with ClientException

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

the class BrokerValidator method verifySignatureHash.

private String verifySignatureHash(final List<X509Certificate> certs) throws NoSuchAlgorithmException, CertificateEncodingException, ClientException {
    final StringBuilder hashListStringBuilder = new StringBuilder();
    for (final X509Certificate x509Certificate : certs) {
        final MessageDigest messageDigest = MessageDigest.getInstance("SHA");
        messageDigest.update(x509Certificate.getEncoded());
        // Check the hash for signer cert is the same as what we hardcoded.
        final String signatureHash = Base64.encodeToString(messageDigest.digest(), Base64.NO_WRAP);
        hashListStringBuilder.append(signatureHash);
        hashListStringBuilder.append(',');
        for (final BrokerData brokerData : getValidBrokers()) {
            if (!TextUtils.isEmpty(brokerData.signatureHash) && brokerData.signatureHash.equals(signatureHash)) {
                return signatureHash;
            }
        }
    }
    throw new ClientException(BROKER_APP_VERIFICATION_FAILED, "SignatureHashes: " + hashListStringBuilder.toString());
}
Also used : ClientException(com.microsoft.identity.common.exception.ClientException) MessageDigest(java.security.MessageDigest) X509Certificate(java.security.cert.X509Certificate)

Example 24 with ClientException

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

the class BrokerValidator method getSelfSignedCert.

// Will throw if there is more than one self-signed cert found.
private X509Certificate getSelfSignedCert(final List<X509Certificate> certs) throws ClientException {
    int count = 0;
    X509Certificate selfSignedCert = null;
    for (final X509Certificate x509Certificate : certs) {
        if (x509Certificate.getSubjectDN().equals(x509Certificate.getIssuerDN())) {
            selfSignedCert = x509Certificate;
            count++;
        }
    }
    if (count > 1 || selfSignedCert == null) {
        throw new ClientException(BROKER_APP_VERIFICATION_FAILED, "Multiple self signed certs found or no self signed cert existed.");
    }
    return selfSignedCert;
}
Also used : ClientException(com.microsoft.identity.common.exception.ClientException) SuppressLint(android.annotation.SuppressLint) X509Certificate(java.security.cert.X509Certificate)

Example 25 with ClientException

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

the class ADALOAuth2TokenCache method save.

/**
 * Method responsible for saving tokens contained in the TokenResponse to storage.
 *
 * @param strategy
 * @param request
 * @param response
 */
@Override
public ICacheRecord save(final AzureActiveDirectoryOAuth2Strategy strategy, final AzureActiveDirectoryAuthorizationRequest request, final AzureActiveDirectoryTokenResponse response) {
    final String methodName = "save";
    Logger.info(TAG + ":" + methodName, "Saving Tokens...");
    final String issuerCacheIdentifier = strategy.getIssuerCacheIdentifier(request);
    final AzureActiveDirectoryAccount account = strategy.createAccount(response);
    final String msalEnvironment = Uri.parse(issuerCacheIdentifier).getAuthority();
    account.setEnvironment(msalEnvironment);
    final AzureActiveDirectoryRefreshToken refreshToken = strategy.getRefreshTokenFromResponse(response);
    refreshToken.setEnvironment(msalEnvironment);
    Logger.info(TAG, "Constructing new ADALTokenCacheItem");
    final ADALTokenCacheItem cacheItem = new ADALTokenCacheItem(strategy, request, response);
    logTokenCacheItem(cacheItem);
    // There is more than one valid user identifier for some accounts... AAD Accounts as of this writing have 3
    Logger.info(TAG + ":" + methodName, "Setting items to cache for user...");
    for (final String cacheIdentifier : account.getCacheIdentifiers()) {
        // Azure AD Uses Resource and Not Scope... but we didn't override... heads up
        final String scope = request.getScope();
        final String clientId = request.getClientId();
        Logger.infoPII(TAG + ":" + methodName, "issuerCacheIdentifier: [" + issuerCacheIdentifier + "]");
        Logger.infoPII(TAG + ":" + methodName, "scope: [" + scope + "]");
        Logger.infoPII(TAG + ":" + methodName, "clientId: [" + clientId + "]");
        Logger.infoPII(TAG + ":" + methodName, "cacheIdentifier: [" + cacheIdentifier + "]");
        setItemToCacheForUser(issuerCacheIdentifier, scope, clientId, cacheItem, cacheIdentifier);
    }
    // For legacy reasons creating a cache entry where the userid is null
    // ADAL supported a single user mode where it was not necessary for the developer to provide the user id
    // on calls to acquireTokenSilentAsync
    setItemToCacheForUser(issuerCacheIdentifier, request.getScope(), request.getClientId(), cacheItem, null);
    // TODO At some point, the type-safety of this call needs to get beefed-up
    Logger.info(TAG + ":" + methodName, "Syncing SSO state to caches...");
    for (final IShareSingleSignOnState<MicrosoftAccount, MicrosoftRefreshToken> sharedSsoCache : mSharedSSOCaches) {
        try {
            sharedSsoCache.setSingleSignOnState(account, refreshToken);
        } catch (ClientException e) {
            Logger.errorPII(TAG, "Exception setting single sign on state for account " + account.getUsername(), e);
        }
    }
    // Returning null, since the ADAL cache's schema doesn't support this return type.
    return null;
}
Also used : AzureActiveDirectoryAccount(com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectoryAccount) MicrosoftAccount(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftAccount) AzureActiveDirectoryRefreshToken(com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectoryRefreshToken) MicrosoftRefreshToken(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftRefreshToken) 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