Search in sources :

Example 56 with ClientException

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

the class BrokerMsalController method logOutFromBrowser.

/**
 * Invoke the logout endpoint on the specified browser.
 * If there are more than 1 session in the browser, an account picker will be displayed.
 * (Alternatively, we could pass the optional sessionID as one of the query string parameter, but we're not storing that at the moment).
 *
 * @param context    {@link Context} application context.
 * @param parameters a {@link RemoveAccountCommandParameters}.
 */
private void logOutFromBrowser(@NonNull final Context context, @NonNull final RemoveAccountCommandParameters parameters) {
    final String methodName = ":logOutFromBrowser";
    String browserPackageName = null;
    try {
        final Browser browser = BrowserSelector.select(context, parameters.getBrowserSafeList());
        browserPackageName = browser.getPackageName();
    } catch (final ClientException e) {
        // Best effort. If none is passed to broker, then it will let the OS decide.
        Logger.error(TAG, e.getErrorCode(), e);
    }
    try {
        final Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setData(Uri.parse(AuthenticationConstants.Browser.LOGOUT_ENDPOINT_V2));
        if (browserPackageName != null) {
            intent.setPackage(browserPackageName);
        }
        context.startActivity(intent);
    } catch (final ActivityNotFoundException e) {
        Logger.error(TAG + methodName, "Failed to launch browser sign out with browser=[" + browserPackageName + "]. Skipping.", e);
    }
}
Also used : ActivityNotFoundException(android.content.ActivityNotFoundException) Intent(android.content.Intent) ClientException(com.microsoft.identity.common.exception.ClientException) Browser(com.microsoft.identity.common.internal.ui.browser.Browser)

Example 57 with ClientException

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

the class LocalMSALController method acquireTokenSilent.

@Override
public AcquireTokenResult acquireTokenSilent(@NonNull final SilentTokenCommandParameters parameters) throws IOException, ClientException, ArgumentException, ServiceException {
    final String methodName = ":acquireTokenSilent";
    Logger.verbose(TAG + methodName, "Acquiring token silently...");
    Telemetry.emit(new ApiStartEvent().putProperties(parameters).putApiId(TelemetryEventStrings.Api.LOCAL_ACQUIRE_TOKEN_SILENT));
    final AcquireTokenResult acquireTokenSilentResult = new AcquireTokenResult();
    // Validate MSAL Parameters
    parameters.validate();
    // Add default scopes
    final Set<String> mergedScopes = addDefaultScopes(parameters);
    final SilentTokenCommandParameters parametersWithScopes = parameters.toBuilder().scopes(mergedScopes).build();
    @SuppressWarnings(WarningType.rawtype_warning) final OAuth2TokenCache tokenCache = parametersWithScopes.getOAuth2TokenCache();
    final AccountRecord targetAccount = getCachedAccountRecord(parametersWithScopes);
    // Build up params for Strategy construction
    final AbstractAuthenticationScheme authScheme = parametersWithScopes.getAuthenticationScheme();
    final OAuth2StrategyParameters strategyParameters = new OAuth2StrategyParameters();
    strategyParameters.setContext(parametersWithScopes.getAndroidApplicationContext());
    @SuppressWarnings(WarningType.rawtype_warning) final OAuth2Strategy strategy = parametersWithScopes.getAuthority().createOAuth2Strategy(strategyParameters);
    // Suppressing unchecked warning of converting List<ICacheRecord> to List due to generic type not provided for tokenCache
    @SuppressWarnings(WarningType.unchecked_warning) final List<ICacheRecord> cacheRecords = tokenCache.loadWithAggregatedAccountData(parametersWithScopes.getClientId(), TextUtils.join(" ", parametersWithScopes.getScopes()), targetAccount, authScheme);
    // The first element is the 'fully-loaded' CacheRecord which may contain the AccountRecord,
    // AccessTokenRecord, RefreshTokenRecord, and IdTokenRecord... (if all of those artifacts exist)
    // subsequent CacheRecords represent other profiles (projections) of this principal in
    // other tenants. Those tokens will be 'sparse', meaning that their AT/RT will not be loaded
    final ICacheRecord fullCacheRecord = cacheRecords.get(0);
    if (accessTokenIsNull(fullCacheRecord) || refreshTokenIsNull(fullCacheRecord) || parametersWithScopes.isForceRefresh() || !isRequestAuthorityRealmSameAsATRealm(parametersWithScopes.getAuthority(), fullCacheRecord.getAccessToken()) || !strategy.validateCachedResult(authScheme, fullCacheRecord)) {
        if (!refreshTokenIsNull(fullCacheRecord)) {
            // No AT found, but the RT checks out, so we'll use it
            Logger.verbose(TAG + methodName, "No access token found, but RT is available.");
            renewAccessToken(parametersWithScopes, acquireTokenSilentResult, tokenCache, strategy, fullCacheRecord);
        } else {
            // TODO need the refactor, should just throw the ui required exception, rather than
            // wrap the exception later in the exception wrapper.
            final ClientException exception = new ClientException(ErrorStrings.NO_TOKENS_FOUND, "No refresh token was found. ");
            Telemetry.emit(new ApiEndEvent().putException(exception).putApiId(TelemetryEventStrings.Api.LOCAL_ACQUIRE_TOKEN_SILENT));
            throw exception;
        }
    } else if (fullCacheRecord.getAccessToken().isExpired()) {
        Logger.warn(TAG + methodName, "Access token is expired. Removing from cache...");
        // Remove the expired token
        tokenCache.removeCredential(fullCacheRecord.getAccessToken());
        Logger.verbose(TAG + methodName, "Renewing access token...");
        // Request a new AT
        renewAccessToken(parametersWithScopes, acquireTokenSilentResult, tokenCache, strategy, fullCacheRecord);
    } else {
        Logger.verbose(TAG + methodName, "Returning silent result");
        // the result checks out, return that....
        acquireTokenSilentResult.setLocalAuthenticationResult(new LocalAuthenticationResult(finalizeCacheRecordForResult(fullCacheRecord, parametersWithScopes.getAuthenticationScheme()), cacheRecords, SdkType.MSAL, true));
    }
    Telemetry.emit(new ApiEndEvent().putResult(acquireTokenSilentResult).putApiId(TelemetryEventStrings.Api.LOCAL_ACQUIRE_TOKEN_SILENT));
    return acquireTokenSilentResult;
}
Also used : AcquireTokenResult(com.microsoft.identity.common.internal.result.AcquireTokenResult) SilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.SilentTokenCommandParameters) ICacheRecord(com.microsoft.identity.common.internal.cache.ICacheRecord) OAuth2StrategyParameters(com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters) OAuth2Strategy(com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy) AbstractAuthenticationScheme(com.microsoft.identity.common.internal.authscheme.AbstractAuthenticationScheme) OAuth2TokenCache(com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache) ApiEndEvent(com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent) ApiStartEvent(com.microsoft.identity.common.internal.telemetry.events.ApiStartEvent) AccountRecord(com.microsoft.identity.common.internal.dto.AccountRecord) ClientException(com.microsoft.identity.common.exception.ClientException) LocalAuthenticationResult(com.microsoft.identity.common.internal.result.LocalAuthenticationResult)

Example 58 with ClientException

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

the class LocalMSALController method deviceCodeFlowAuthRequest.

// Suppressing rawtype warnings due to the generic types AuthorizationResult and OAuth2Strategy
@SuppressWarnings(WarningType.rawtype_warning)
@Override
public AuthorizationResult deviceCodeFlowAuthRequest(final DeviceCodeFlowCommandParameters parameters) throws ServiceException, ClientException, IOException {
    // Logging start of method
    final String methodName = ":deviceCodeFlowAuthRequest";
    Logger.verbose(TAG + methodName, "Device Code Flow: Authorizing user code...");
    // Default scopes here
    final Set<String> mergedScopes = addDefaultScopes(parameters);
    final DeviceCodeFlowCommandParameters parametersWithScopes = parameters.toBuilder().scopes(mergedScopes).build();
    logParameters(TAG, parametersWithScopes);
    // Start telemetry with LOCAL_DEVICE_CODE_FLOW_ACQUIRE_URL_AND_CODE
    Telemetry.emit(new ApiStartEvent().putProperties(parametersWithScopes).putApiId(TelemetryEventStrings.Api.LOCAL_DEVICE_CODE_FLOW_ACQUIRE_URL_AND_CODE));
    final Authority.KnownAuthorityResult authorityResult = Authority.getKnownAuthorityResult(parametersWithScopes.getAuthority());
    // If not known throw resulting exception
    if (!authorityResult.getKnown()) {
        Telemetry.emit(new ApiEndEvent().putException(authorityResult.getClientException()).putApiId(TelemetryEventStrings.Api.LOCAL_DEVICE_CODE_FLOW_ACQUIRE_URL_AND_CODE));
        throw authorityResult.getClientException();
    }
    final AuthorizationResult authorizationResult;
    try {
        // Create OAuth2Strategy using commandParameters and strategyParameters
        final OAuth2StrategyParameters strategyParameters = new OAuth2StrategyParameters();
        strategyParameters.setContext(parametersWithScopes.getAndroidApplicationContext());
        final OAuth2Strategy oAuth2Strategy = parametersWithScopes.getAuthority().createOAuth2Strategy(strategyParameters);
        // DCF protocol step 1: Get user code
        // Populate global authorization request
        mAuthorizationRequest = getAuthorizationRequest(oAuth2Strategy, parametersWithScopes);
        // Call method defined in oAuth2Strategy to request authorization
        authorizationResult = oAuth2Strategy.getDeviceCode((MicrosoftStsAuthorizationRequest) mAuthorizationRequest);
        validateServiceResult(authorizationResult);
    } catch (Exception error) {
        Telemetry.emit(new ApiEndEvent().putException(error).putApiId(TelemetryEventStrings.Api.LOCAL_DEVICE_CODE_FLOW_ACQUIRE_URL_AND_CODE));
        throw error;
    }
    Logger.verbose(TAG + methodName, "Device Code Flow authorization step finished...");
    logResult(TAG, authorizationResult);
    // End telemetry with LOCAL_DEVICE_CODE_FLOW_ACQUIRE_URL_AND_CODE
    Telemetry.emit(new ApiEndEvent().putApiId(TelemetryEventStrings.Api.LOCAL_DEVICE_CODE_FLOW_ACQUIRE_URL_AND_CODE));
    return authorizationResult;
}
Also used : MicrosoftStsAuthorizationRequest(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsAuthorizationRequest) ApiEndEvent(com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent) Authority(com.microsoft.identity.common.internal.authorities.Authority) DeviceCodeFlowCommandParameters(com.microsoft.identity.common.internal.commands.parameters.DeviceCodeFlowCommandParameters) ApiStartEvent(com.microsoft.identity.common.internal.telemetry.events.ApiStartEvent) OAuth2StrategyParameters(com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters) OAuth2Strategy(com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy) AuthorizationResult(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult) 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)

Example 59 with ClientException

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

the class GenerateShrCommand method execute.

@Override
public GenerateShrResult execute() throws Exception {
    final String methodName = ":execute";
    GenerateShrResult result = null;
    final GenerateShrCommandParameters parameters = (GenerateShrCommandParameters) getParameters();
    // Iterate over our controllers, to service the request either locally or via the broker...
    // if the local (embedded) cache contains tokens for the supplied user, we will sign using
    // the embedded PoP keys. If no local user-state exists, the broker will be delegated to
    // where the same check is performed.
    BaseController controller;
    for (int ii = 0; ii < getControllers().size(); ii++) {
        controller = getControllers().get(ii);
        com.microsoft.identity.common.internal.logging.Logger.verbose(TAG + methodName, "Executing with controller: " + controller.getClass().getSimpleName());
        result = controller.generateSignedHttpRequest(parameters);
        if (null != result.getErrorCode()) {
            final String errorCode = result.getErrorCode();
            final String errorMessage = result.getErrorMessage();
            // of as thrown Exceptions
            if (NO_ACCOUNT_FOUND.equalsIgnoreCase(errorCode)) {
                if (getControllers().size() > ii + 1) {
                    // Try our next controller
                    continue;
                } else {
                    throw new UiRequiredException(errorCode, errorMessage);
                }
            } else {
                throw new ClientException(errorCode, errorMessage);
            }
        }
    }
    return result;
}
Also used : GenerateShrResult(com.microsoft.identity.common.internal.result.GenerateShrResult) BaseController(com.microsoft.identity.common.internal.controllers.BaseController) UiRequiredException(com.microsoft.identity.common.exception.UiRequiredException) ClientException(com.microsoft.identity.common.exception.ClientException) GenerateShrCommandParameters(com.microsoft.identity.common.internal.commands.parameters.GenerateShrCommandParameters)

Example 60 with ClientException

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

the class SilentTokenCommand method execute.

@Override
public AcquireTokenResult execute() throws Exception {
    AcquireTokenResult result = null;
    final String methodName = ":execute";
    for (int ii = 0; ii < this.getControllers().size(); ii++) {
        final BaseController controller = this.getControllers().get(ii);
        try {
            com.microsoft.identity.common.internal.logging.Logger.verbose(TAG + methodName, "Executing with controller: " + controller.getClass().getSimpleName());
            result = controller.acquireTokenSilent((SilentTokenCommandParameters) getParameters());
            if (result.getSucceeded()) {
                com.microsoft.identity.common.internal.logging.Logger.verbose(TAG + methodName, "Executing with controller: " + controller.getClass().getSimpleName() + ": Succeeded");
                return result;
            }
        } catch (UiRequiredException | ClientException e) {
            if (// was invalid_grant
            e.getErrorCode().equals(AuthenticationConstants.OAuth2ErrorCode.INVALID_GRANT) && this.getControllers().size() > ii + 1) {
                // isn't the last controller we can try
                continue;
            } else if ((e.getErrorCode().equals(ErrorStrings.NO_TOKENS_FOUND) || e.getErrorCode().equals(ErrorStrings.NO_ACCOUNT_FOUND)) && this.getControllers().size() > ii + 1) {
                // if no token or account for this silent call, we should continue to the next silent call.
                continue;
            } else {
                throw e;
            }
        }
    }
    return result;
}
Also used : AcquireTokenResult(com.microsoft.identity.common.internal.result.AcquireTokenResult) SilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.SilentTokenCommandParameters) BaseController(com.microsoft.identity.common.internal.controllers.BaseController) UiRequiredException(com.microsoft.identity.common.exception.UiRequiredException) 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