Search in sources :

Example 6 with ServiceException

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

the class BrokerMsalController method saveMsaAccountToCache.

/**
 * Checks if the account returns is a MSA Account and sets single on state in cache
 */
private void saveMsaAccountToCache(@NonNull final Bundle resultBundle, @SuppressWarnings(WarningType.rawtype_warning) @NonNull final MsalOAuth2TokenCache msalOAuth2TokenCache) throws BaseException {
    final String methodName = ":saveMsaAccountToCache";
    final BrokerResult brokerResult = new MsalBrokerResultAdapter().brokerResultFromBundle(resultBundle);
    if (resultBundle.getBoolean(AuthenticationConstants.Broker.BROKER_REQUEST_V2_SUCCESS) && AzureActiveDirectoryAudience.MSA_MEGA_TENANT_ID.equalsIgnoreCase(brokerResult.getTenantId())) {
        Logger.info(TAG + methodName, "Result returned for MSA Account, saving to cache");
        if (StringUtil.isEmpty(brokerResult.getClientInfo())) {
            Logger.error(TAG + methodName, "ClientInfo is empty.", null);
            throw new ClientException(ErrorStrings.UNKNOWN_ERROR, "ClientInfo is empty.");
        }
        try {
            final ClientInfo clientInfo = new ClientInfo(brokerResult.getClientInfo());
            final MicrosoftStsAccount microsoftStsAccount = new MicrosoftStsAccount(new IDToken(brokerResult.getIdToken()), clientInfo);
            microsoftStsAccount.setEnvironment(brokerResult.getEnvironment());
            final MicrosoftRefreshToken microsoftRefreshToken = new MicrosoftRefreshToken(brokerResult.getRefreshToken(), clientInfo, brokerResult.getScope(), brokerResult.getClientId(), brokerResult.getEnvironment(), brokerResult.getFamilyId());
            msalOAuth2TokenCacheSetSingleSignOnState(msalOAuth2TokenCache, microsoftStsAccount, microsoftRefreshToken);
        } catch (ServiceException e) {
            Logger.errorPII(TAG + methodName, "Exception while creating Idtoken or ClientInfo," + " cannot save MSA account tokens", e);
            throw new ClientException(ErrorStrings.INVALID_JWT, e.getMessage(), e);
        }
    }
}
Also used : BrokerResult(com.microsoft.identity.common.internal.broker.BrokerResult) MsalBrokerResultAdapter(com.microsoft.identity.common.internal.result.MsalBrokerResultAdapter) MicrosoftStsAccount(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsAccount) MicrosoftRefreshToken(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftRefreshToken) ServiceException(com.microsoft.identity.common.exception.ServiceException) IDToken(com.microsoft.identity.common.internal.providers.oauth2.IDToken) ClientException(com.microsoft.identity.common.exception.ClientException) ClientInfo(com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.ClientInfo)

Example 7 with ServiceException

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

the class ExceptionAdapter method exceptionFromAcquireTokenResult.

@Nullable
public static BaseException exceptionFromAcquireTokenResult(final AcquireTokenResult result, final CommandParameters commandParameters) {
    final String methodName = ":exceptionFromAcquireTokenResult";
    @SuppressWarnings(WarningType.rawtype_warning) final AuthorizationResult authorizationResult = result.getAuthorizationResult();
    if (null != authorizationResult) {
        final AuthorizationErrorResponse authorizationErrorResponse = authorizationResult.getAuthorizationErrorResponse();
        if (!authorizationResult.getSuccess()) {
            // THERE ARE CURRENTLY NO USAGES of INVALID_REQUEST
            switch(result.getAuthorizationResult().getAuthorizationStatus()) {
                case FAIL:
                    // Check if the error is to register device and throw DEVICE_REGISTRATION_NEEDED exception
                    if (authorizationErrorResponse instanceof MicrosoftAuthorizationErrorResponse) {
                        MicrosoftAuthorizationErrorResponse microsoftAuthorizationErrorResponse = (MicrosoftAuthorizationErrorResponse) authorizationErrorResponse;
                        if (microsoftAuthorizationErrorResponse.getError().equals(MicrosoftAuthorizationErrorResponse.DEVICE_REGISTRATION_NEEDED)) {
                            return new DeviceRegistrationRequiredException(microsoftAuthorizationErrorResponse.getError(), microsoftAuthorizationErrorResponse.getErrorDescription(), microsoftAuthorizationErrorResponse.getUserName());
                        }
                    }
                    return new ServiceException(authorizationErrorResponse.getError(), authorizationErrorResponse.getErrorDescription(), ServiceException.DEFAULT_STATUS_CODE, null);
                case SDK_CANCEL:
                    return new ClientException(authorizationErrorResponse.getError(), authorizationErrorResponse.getErrorDescription());
                case USER_CANCEL:
                    return new UserCancelException();
            }
        }
    } else {
        Logger.warn(TAG + methodName, "AuthorizationResult was null -- expected for ATS cases.");
    }
    return exceptionFromTokenResult(result.getTokenResult(), commandParameters);
}
Also used : MicrosoftAuthorizationErrorResponse(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftAuthorizationErrorResponse) AuthorizationErrorResponse(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationErrorResponse) MicrosoftAuthorizationErrorResponse(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftAuthorizationErrorResponse) ServiceException(com.microsoft.identity.common.exception.ServiceException) DeviceRegistrationRequiredException(com.microsoft.identity.common.exception.DeviceRegistrationRequiredException) UserCancelException(com.microsoft.identity.common.exception.UserCancelException) ClientException(com.microsoft.identity.common.exception.ClientException) AuthorizationResult(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult) Nullable(androidx.annotation.Nullable)

Example 8 with ServiceException

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

the class ExceptionAdapter method getExceptionFromTokenErrorResponse.

/**
 * Get an exception object from the given oAuth values.
 *
 * @param errorResponse
 * @return ServiceException, UiRequiredException
 */
public static ServiceException getExceptionFromTokenErrorResponse(@NonNull final TokenErrorResponse errorResponse) {
    final ServiceException outErr;
    if (shouldBeConvertedToUiRequiredException(errorResponse.getError())) {
        outErr = new UiRequiredException(errorResponse.getError(), errorResponse.getErrorDescription());
    } else {
        outErr = new ServiceException(errorResponse.getError(), errorResponse.getErrorDescription(), null);
    }
    outErr.setOauthSubErrorCode(errorResponse.getSubError());
    setHttpResponseUsingTokenErrorResponse(outErr, errorResponse);
    return outErr;
}
Also used : ServiceException(com.microsoft.identity.common.exception.ServiceException) UiRequiredException(com.microsoft.identity.common.exception.UiRequiredException)

Example 9 with ServiceException

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

the class ExceptionAdapter method exceptionFromTokenResult.

/**
 * Get an exception out of a TokenResult object.
 *
 * @param tokenResult
 * @return ServiceException, UiRequiredException
 */
public static ServiceException exceptionFromTokenResult(final TokenResult tokenResult, final CommandParameters commandParameters) {
    final String methodName = ":exceptionFromTokenResult";
    ServiceException outErr;
    if (tokenResult != null && !tokenResult.getSuccess() && tokenResult.getErrorResponse() != null && !StringUtil.isEmpty(tokenResult.getErrorResponse().getError())) {
        outErr = getExceptionFromTokenErrorResponse(commandParameters, tokenResult.getErrorResponse());
        applyCliTelemInfo(tokenResult.getCliTelemInfo(), outErr);
    } else {
        Logger.warn(TAG + methodName, "Unknown error, Token result is null [" + (tokenResult == null) + "]");
        outErr = new ServiceException(ServiceException.UNKNOWN_ERROR, "Request failed, but no error returned back from service.", null);
    }
    return outErr;
}
Also used : ServiceException(com.microsoft.identity.common.exception.ServiceException)

Example 10 with ServiceException

use of com.microsoft.identity.common.exception.ServiceException 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)

Aggregations

ServiceException (com.microsoft.identity.common.exception.ServiceException)23 ClientInfo (com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.ClientInfo)8 IDToken (com.microsoft.identity.common.internal.providers.oauth2.IDToken)7 ClientException (com.microsoft.identity.common.exception.ClientException)4 Nullable (androidx.annotation.Nullable)3 IOException (java.io.IOException)3 URL (java.net.URL)3 NonNull (androidx.annotation.NonNull)2 ArgumentException (com.microsoft.identity.common.exception.ArgumentException)2 BaseException (com.microsoft.identity.common.exception.BaseException)2 BrokerResult (com.microsoft.identity.common.internal.broker.BrokerResult)2 AuthorizationResult (com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult)2 OAuth2Strategy (com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy)2 OAuth2StrategyParameters (com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters)2 ApiEndEvent (com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent)2 ApiStartEvent (com.microsoft.identity.common.internal.telemetry.events.ApiStartEvent)2 JSONException (org.json.JSONException)2 Bundle (android.os.Bundle)1 JsonObject (com.google.gson.JsonObject)1 JWSBuilder (com.microsoft.identity.common.adal.internal.JWSBuilder)1