Search in sources :

Example 31 with ClientException

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

the class LocalMSALController method acquireDeviceCodeFlowToken.

@Override
public AcquireTokenResult acquireDeviceCodeFlowToken(@SuppressWarnings(WarningType.rawtype_warning) final AuthorizationResult authorizationResult, final DeviceCodeFlowCommandParameters parameters) throws ServiceException, ClientException, IOException {
    // Logging start of method
    final String methodName = ":acquireDeviceCodeFlowToken";
    Logger.verbose(TAG + methodName, "Device Code Flow: Polling for token...");
    // Start telemetry with LOCAL_DEVICE_CODE_FLOW_POLLING
    Telemetry.emit(new ApiStartEvent().putApiId(TelemetryEventStrings.Api.LOCAL_DEVICE_CODE_FLOW_POLLING));
    // Create empty AcquireTokenResult object
    final AcquireTokenResult acquireTokenResult = new AcquireTokenResult();
    // Assign authorization result
    acquireTokenResult.setAuthorizationResult(authorizationResult);
    // Fetch the Authorization Response
    final MicrosoftStsAuthorizationResponse authorizationResponse = (MicrosoftStsAuthorizationResponse) authorizationResult.getAuthorizationResponse();
    // DCF protocol step 2: Poll for token
    TokenResult tokenResult = null;
    try {
        // Create OAuth2Strategy using commandParameters and strategyParameters
        final OAuth2StrategyParameters strategyParameters = new OAuth2StrategyParameters();
        strategyParameters.setContext(parameters.getAndroidApplicationContext());
        @SuppressWarnings(WarningType.rawtype_warning) final OAuth2Strategy oAuth2Strategy = parameters.getAuthority().createOAuth2Strategy(strategyParameters);
        // Create token request outside of loop so it isn't re-created after every loop
        // Suppressing unchecked warnings due to casting of AuthorizationRequest to GenericAuthorizationRequest and MicrosoftStsAuthorizationResponse to GenericAuthorizationResponse in the arguments of call to createTokenRequest method
        @SuppressWarnings(WarningType.unchecked_warning) final MicrosoftStsTokenRequest tokenRequest = (MicrosoftStsTokenRequest) oAuth2Strategy.createTokenRequest(mAuthorizationRequest, authorizationResponse, parameters.getAuthenticationScheme());
        // Fetch wait interval
        final int intervalInMilliseconds = Integer.parseInt(authorizationResponse.getInterval()) * 1000;
        String errorCode = ErrorStrings.DEVICE_CODE_FLOW_AUTHORIZATION_PENDING_ERROR_CODE;
        // Loop to send multiple requests checking for token
        while (authorizationPending(errorCode)) {
            // Wait between polls
            ThreadUtils.sleepSafely(intervalInMilliseconds, TAG, "Attempting to sleep thread during Device Code Flow token polling...");
            // Reset error code
            errorCode = "";
            // Execute Token Request
            // Suppressing unchecked warnings due to casting of MicrosoftStsTokenRequest to GenericTokenRequest in the arguments of call to requestToken method
            @SuppressWarnings(WarningType.unchecked_warning) TokenResult tokenResultFromRequestToken = oAuth2Strategy.requestToken(tokenRequest);
            tokenResult = tokenResultFromRequestToken;
            // Fetch error if the request failed
            if (tokenResult.getErrorResponse() != null) {
                errorCode = tokenResult.getErrorResponse().getError();
            }
        }
        // Validate request success, may throw MsalServiceException
        validateServiceResult(tokenResult);
        // Assign token result
        acquireTokenResult.setTokenResult(tokenResult);
        // If the token is valid, save it into token cache
        final List<ICacheRecord> records = saveTokens(oAuth2Strategy, mAuthorizationRequest, acquireTokenResult.getTokenResult().getTokenResponse(), parameters.getOAuth2TokenCache());
        // Once the token is stored, fetch and assign the authentication result
        final ICacheRecord newestRecord = records.get(0);
        acquireTokenResult.setLocalAuthenticationResult(new LocalAuthenticationResult(finalizeCacheRecordForResult(newestRecord, parameters.getAuthenticationScheme()), records, SdkType.MSAL, false));
    } catch (Exception error) {
        Telemetry.emit(new ApiEndEvent().putException(error).putApiId(TelemetryEventStrings.Api.LOCAL_DEVICE_CODE_FLOW_POLLING));
        throw error;
    }
    logResult(TAG, tokenResult);
    // End telemetry with LOCAL_DEVICE_CODE_FLOW_POLLING
    Telemetry.emit(new ApiEndEvent().putResult(acquireTokenResult).putApiId(TelemetryEventStrings.Api.LOCAL_DEVICE_CODE_FLOW_POLLING));
    return acquireTokenResult;
}
Also used : AcquireTokenResult(com.microsoft.identity.common.internal.result.AcquireTokenResult) ICacheRecord(com.microsoft.identity.common.internal.cache.ICacheRecord) TokenResult(com.microsoft.identity.common.internal.providers.oauth2.TokenResult) AcquireTokenResult(com.microsoft.identity.common.internal.result.AcquireTokenResult) OAuth2StrategyParameters(com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters) OAuth2Strategy(com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy) ServiceException(com.microsoft.identity.common.exception.ServiceException) ClientException(com.microsoft.identity.common.exception.ClientException) IOException(java.io.IOException) ArgumentException(com.microsoft.identity.common.exception.ArgumentException) ExecutionException(java.util.concurrent.ExecutionException) MicrosoftStsAuthorizationResponse(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsAuthorizationResponse) ApiEndEvent(com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent) MicrosoftStsTokenRequest(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsTokenRequest) ApiStartEvent(com.microsoft.identity.common.internal.telemetry.events.ApiStartEvent) LocalAuthenticationResult(com.microsoft.identity.common.internal.result.LocalAuthenticationResult)

Example 32 with ClientException

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

the class DeviceKeyManager method getCertificateChain.

@Override
public Certificate[] getCertificateChain() throws ClientException {
    final Exception exception;
    final String errCode;
    try {
        return mKeyStore.getCertificateChain(mKeyAlias);
    } catch (final KeyStoreException e) {
        exception = e;
        errCode = KEYSTORE_NOT_INITIALIZED;
    }
    final ClientException clientException = new ClientException(errCode, exception.getMessage(), exception);
    Logger.error(TAG, clientException.getMessage(), clientException);
    throw clientException;
}
Also used : KeyStoreException(java.security.KeyStoreException) ClientException(com.microsoft.identity.common.exception.ClientException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) KeyStoreException(java.security.KeyStoreException) UnrecoverableEntryException(java.security.UnrecoverableEntryException) ClientException(com.microsoft.identity.common.exception.ClientException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 33 with ClientException

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

the class MsalBrokerResultAdapter method getBaseExceptionFromBundle.

@Override
@NonNull
public BaseException getBaseExceptionFromBundle(@NonNull final Bundle resultBundle) {
    Logger.info(TAG, "Constructing exception from result bundle");
    final BrokerResult brokerResult;
    try {
        brokerResult = brokerResultFromBundle(resultBundle);
    } catch (final ClientException e) {
        return e;
    }
    final String exceptionType = brokerResult.getExceptionType();
    if (!StringUtil.isEmpty(exceptionType)) {
        return getBaseExceptionFromExceptionType(exceptionType, brokerResult);
    } else {
        // This code is here for legacy purposes where old versions of broker (3.1.8 or below)
        // wouldn't return exception type in the result.
        Logger.info(TAG, "Exception type is not returned from the broker, " + "using error codes to transform to the right exception");
        return getBaseExceptionFromErrorCodes(brokerResult);
    }
}
Also used : BrokerResult(com.microsoft.identity.common.internal.broker.BrokerResult) ClientException(com.microsoft.identity.common.exception.ClientException) GzipUtil.compressString(com.microsoft.identity.common.internal.util.GzipUtil.compressString) NonNull(androidx.annotation.NonNull)

Example 34 with ClientException

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

the class MsalBrokerResultAdapter method getBaseExceptionFromErrorCodes.

/**
 * Method to get the right base exception based on error codes.
 * Note : In newer versions of Broker, exception type will be sent and is used to determine the right exception.
 * <p>
 * This method is to support legacy broker versions (3.1.8 or below)
 *
 * @return {@link BaseException}
 */
@NonNull
private BaseException getBaseExceptionFromErrorCodes(@NonNull final BrokerResult brokerResult) {
    final String errorCode = brokerResult.getErrorCode();
    final BaseException baseException;
    // INTERACTION_REQUIRED is marked as deprecated
    if (AuthenticationConstants.OAuth2ErrorCode.INTERACTION_REQUIRED.equalsIgnoreCase(errorCode) || AuthenticationConstants.OAuth2ErrorCode.INVALID_GRANT.equalsIgnoreCase(errorCode) || ErrorStrings.INVALID_BROKER_REFRESH_TOKEN.equalsIgnoreCase(errorCode) || ErrorStrings.NO_TOKENS_FOUND.equalsIgnoreCase(errorCode)) {
        Logger.warn(TAG, "Received a UIRequired exception from Broker : " + errorCode);
        baseException = new UiRequiredException(errorCode, brokerResult.getErrorMessage());
    } else if (AuthenticationConstants.OAuth2ErrorCode.UNAUTHORIZED_CLIENT.equalsIgnoreCase(errorCode) && AuthenticationConstants.OAuth2SubErrorCode.PROTECTION_POLICY_REQUIRED.equalsIgnoreCase(brokerResult.getSubErrorCode())) {
        Logger.warn(TAG, "Received a IntuneAppProtectionPolicyRequiredException exception from Broker : " + errorCode);
        baseException = getIntuneProtectionRequiredException(brokerResult);
    } else if (ErrorStrings.USER_CANCELLED.equalsIgnoreCase(errorCode)) {
        Logger.warn(TAG, "Received a User cancelled exception from Broker : " + errorCode);
        baseException = new UserCancelException();
    } else if (ArgumentException.ILLEGAL_ARGUMENT_ERROR_CODE.equalsIgnoreCase(errorCode)) {
        Logger.warn(TAG, "Received a Argument exception from Broker : " + errorCode);
        baseException = new ArgumentException(ArgumentException.BROKER_TOKEN_REQUEST_OPERATION_NAME, errorCode, brokerResult.getErrorMessage());
    } else if (!StringUtil.isEmpty(brokerResult.getHttpResponseHeaders()) || !StringUtil.isEmpty(brokerResult.getHttpResponseBody())) {
        Logger.warn(TAG, "Received a Service exception from Broker : " + errorCode);
        baseException = getServiceException(brokerResult);
    } else {
        Logger.warn(TAG, "Received a Client exception from Broker : " + errorCode);
        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) GzipUtil.compressString(com.microsoft.identity.common.internal.util.GzipUtil.compressString) ArgumentException(com.microsoft.identity.common.exception.ArgumentException) ClientException(com.microsoft.identity.common.exception.ClientException) NonNull(androidx.annotation.NonNull)

Example 35 with ClientException

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

the class MsalBrokerResultAdapter method brokerResultFromBundle.

@NonNull
public BrokerResult brokerResultFromBundle(@NonNull final Bundle resultBundle) throws ClientException {
    String brokerResultString;
    byte[] compressedBytes = resultBundle.getByteArray(BROKER_RESULT_V2_COMPRESSED);
    if (compressedBytes != null) {
        try {
            brokerResultString = GzipUtil.decompressBytesToString(compressedBytes);
        } catch (IOException e) {
            // We should never hit this ideally unless the string/bytes are malformed for some unknown reason.
            // The caller should handle the null broker result
            Logger.error(TAG, "Failed to decompress broker result :", e);
            throw new ClientException(INVALID_BROKER_BUNDLE, "Failed to decompress broker result", e);
        }
    } else {
        brokerResultString = resultBundle.getString(AuthenticationConstants.Broker.BROKER_RESULT_V2);
    }
    if (StringUtil.isEmpty(brokerResultString)) {
        Logger.error(TAG, "Broker Result not returned from Broker", null);
        throw new ClientException(INVALID_BROKER_BUNDLE, "Broker Result not returned from Broker", null);
    }
    return JsonExtensions.getBrokerResultFromJsonString(brokerResultString);
}
Also used : GzipUtil.compressString(com.microsoft.identity.common.internal.util.GzipUtil.compressString) IOException(java.io.IOException) ClientException(com.microsoft.identity.common.exception.ClientException) NonNull(androidx.annotation.NonNull)

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