Search in sources :

Example 11 with ServiceException

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

the class MsalBrokerResultAdapter method bundleFromBaseException.

@Override
@NonNull
public Bundle bundleFromBaseException(@NonNull final BaseException exception, @Nullable final String negotiatedBrokerProtocolVersion) {
    Logger.info(TAG, "Constructing result bundle from ClientException");
    final BrokerResult.Builder builder = new BrokerResult.Builder().success(false).errorCode(exception.getErrorCode()).errorMessage(exception.getMessage()).exceptionType(exception.getExceptionName()).correlationId(exception.getCorrelationId()).cliTelemErrorCode(exception.getCliTelemErrorCode()).cliTelemSubErrorCode(exception.getCliTelemSubErrorCode()).speRing(exception.getSpeRing()).refreshTokenAge(exception.getRefreshTokenAge());
    if (exception instanceof ServiceException) {
        builder.oauthSubErrorCode(((ServiceException) exception).getOAuthSubErrorCode()).httpStatusCode(((ServiceException) exception).getHttpStatusCode()).httpResponseHeaders(HeaderSerializationUtil.toJson(((ServiceException) exception).getHttpResponseHeaders())).httpResponseBody(sRequestAdapterGsonInstance.toJson(((ServiceException) exception).getHttpResponseBody()));
    }
    if (exception instanceof IntuneAppProtectionPolicyRequiredException) {
        builder.userName(((IntuneAppProtectionPolicyRequiredException) exception).getAccountUpn()).localAccountId(((IntuneAppProtectionPolicyRequiredException) exception).getAccountUserId()).authority(((IntuneAppProtectionPolicyRequiredException) exception).getAuthorityUrl()).tenantId(((IntuneAppProtectionPolicyRequiredException) exception).getTenantId());
    }
    final Bundle resultBundle = bundleFromBrokerResult(builder.build(), negotiatedBrokerProtocolVersion);
    resultBundle.putBoolean(AuthenticationConstants.Broker.BROKER_REQUEST_V2_SUCCESS, false);
    return resultBundle;
}
Also used : BrokerResult(com.microsoft.identity.common.internal.broker.BrokerResult) ServiceException(com.microsoft.identity.common.exception.ServiceException) Bundle(android.os.Bundle) IntuneAppProtectionPolicyRequiredException(com.microsoft.identity.common.exception.IntuneAppProtectionPolicyRequiredException) NonNull(androidx.annotation.NonNull)

Example 12 with ServiceException

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

the class MsalBrokerResultAdapter method getServiceException.

/**
 * Helper method to retrieve ServiceException from BrokerResult
 */
@NonNull
private ServiceException getServiceException(@NonNull final BrokerResult brokerResult) {
    final ServiceException serviceException = new ServiceException(brokerResult.getErrorCode(), brokerResult.getErrorMessage(), null);
    serviceException.setOauthSubErrorCode(brokerResult.getSubErrorCode());
    try {
        serviceException.setHttpResponseBody(brokerResult.getHttpResponseBody() != null ? HashMapExtensions.jsonStringAsMap(brokerResult.getHttpResponseBody()) : null);
        serviceException.setHttpResponseHeaders(brokerResult.getHttpResponseHeaders() != null ? HeaderSerializationUtil.fromJson(brokerResult.getHttpResponseHeaders()) : null);
    } catch (JSONException e) {
        Logger.warn(TAG, "Unable to parse json");
    }
    return serviceException;
}
Also used : ServiceException(com.microsoft.identity.common.exception.ServiceException) JSONException(org.json.JSONException) NonNull(androidx.annotation.NonNull)

Example 13 with ServiceException

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

the class OpenIdProviderConfigurationClient method loadOpenIdProviderConfiguration.

/**
 * Get OpenID provider configuration.
 *
 * @return OpenIdProviderConfiguration
 */
public synchronized OpenIdProviderConfiguration loadOpenIdProviderConfiguration() throws ServiceException {
    final String methodName = ":loadOpenIdProviderConfiguration";
    try {
        final URL configUrl = new URL(mIssuer + sWellKnownConfig);
        // Check first for a cached copy...
        final OpenIdProviderConfiguration cacheResult = sConfigCache.get(configUrl);
        // If we found a result, return it...
        if (null != cacheResult) {
            Logger.info(TAG + methodName, "Using cached metadata result.");
            return cacheResult;
        }
        Logger.verbose(TAG + methodName, "Config URL is valid.");
        Logger.verbosePII(TAG + methodName, "Using request URL: " + configUrl);
        final HttpResponse providerConfigResponse = httpClient.get(configUrl, new HashMap<String, String>());
        final int statusCode = providerConfigResponse.getStatusCode();
        if (HttpURLConnection.HTTP_OK != statusCode || TextUtils.isEmpty(providerConfigResponse.getBody())) {
            throw new ServiceException(OPENID_PROVIDER_CONFIGURATION_FAILED_TO_LOAD, "OpenId Provider Configuration metadata failed to load with status: " + statusCode, null);
        }
        final OpenIdProviderConfiguration parsedConfig = parseMetadata(providerConfigResponse.getBody());
        // Cache our config in memory for later
        cacheConfiguration(configUrl, parsedConfig);
        return parsedConfig;
    } catch (IOException e) {
        throw new ServiceException(OPENID_PROVIDER_CONFIGURATION_FAILED_TO_LOAD, "IOException while requesting metadata", e);
    }
}
Also used : ServiceException(com.microsoft.identity.common.exception.ServiceException) HttpResponse(com.microsoft.identity.common.internal.net.HttpResponse) IOException(java.io.IOException) URL(java.net.URL)

Example 14 with ServiceException

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

the class CoreAdapter method asAuthenticationException.

public static AuthenticationException asAuthenticationException(BaseException ex) {
    AuthenticationException newException = ADALError.fromCommon(ex);
    if (ex instanceof ServiceException) {
        ServiceException serviceException = (ServiceException) ex;
        newException.setHttpResponseBody(serviceException.getHttpResponseBody());
        newException.setHttpResponseHeaders(serviceException.getHttpResponseHeaders());
        newException.setServiceStatusCode(serviceException.getHttpStatusCode());
    }
    return newException;
}
Also used : ServiceException(com.microsoft.identity.common.exception.ServiceException)

Example 15 with ServiceException

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

the class Oauth2 method processUIResponseParams.

public AuthenticationResult processUIResponseParams(Map<String, String> response) throws AuthenticationException {
    final AuthenticationResult result;
    // Protocol error related
    if (response.containsKey(AuthenticationConstants.OAuth2.ERROR)) {
        // Error response from the server
        // CorrelationID will be same as in request headers. This is
        // retrieved in result in case it was not set.
        String correlationInResponse = response.get(AuthenticationConstants.AAD.CORRELATION_ID);
        if (!StringExtensions.isNullOrBlank(correlationInResponse)) {
            try {
                final UUID correlationId = UUID.fromString(correlationInResponse);
                Logger.setCorrelationId(correlationId);
            } catch (IllegalArgumentException ex) {
                Logger.e(TAG, "CorrelationId is malformed: " + correlationInResponse, "", ADALError.CORRELATION_ID_FORMAT);
            }
        }
        Logger.i(TAG, "OAuth2 error:" + response.get(AuthenticationConstants.OAuth2.ERROR), " Description:" + response.get(AuthenticationConstants.OAuth2.ERROR_DESCRIPTION));
        result = new AuthenticationResult(response.get(AuthenticationConstants.OAuth2.ERROR), response.get(AuthenticationConstants.OAuth2.ERROR_DESCRIPTION), response.get(AuthenticationConstants.OAuth2.ERROR_CODES));
        if (null != response.get(AuthenticationConstants.OAuth2.HTTP_RESPONSE_BODY)) {
            HashMap<String, String> responseBody = null;
            try {
                extractJsonObjects(responseBody, response.get(AuthenticationConstants.OAuth2.HTTP_RESPONSE_BODY));
                result.setHttpResponseBody(responseBody);
            } catch (final JSONException exception) {
                Logger.e(TAG, "Json exception", ExceptionExtensions.getExceptionMessage(exception), ADALError.SERVER_INVALID_JSON_RESPONSE);
            }
        }
        if (null != response.get(AuthenticationConstants.OAuth2.HTTP_RESPONSE_HEADER)) {
            HashMap<String, List<String>> responseHeaders = null;
            try {
                responseHeaders = HashMapExtensions.jsonStringAsMapList(response.get(AuthenticationConstants.OAuth2.HTTP_RESPONSE_HEADER));
                result.setHttpResponseHeaders(responseHeaders);
            } catch (final JSONException exception) {
                Logger.e(TAG, "Json exception", ExceptionExtensions.getExceptionMessage(exception), ADALError.SERVER_INVALID_JSON_RESPONSE);
            }
        }
        if (null != response.get(AuthenticationConstants.OAuth2.HTTP_STATUS_CODE)) {
            result.setServiceStatusCode(Integer.parseInt(response.get(AuthenticationConstants.OAuth2.HTTP_STATUS_CODE)));
        }
    } else if (response.containsKey(AuthenticationConstants.OAuth2.CODE)) {
        // The header cloud_instance_host_name points to the right sovereign cloud to use for the given user
        // Using this host name we construct the authority that will get the token request and we use this authority
        // to save the token in the cache. The app should reinitialize AuthenticationContext with this authority for
        // all subsequent requests.
        result = new AuthenticationResult(mRequest.getClientId(), response.get(AuthenticationConstants.OAuth2.CODE));
        final String cloudInstanceHostName = response.get(AuthenticationConstants.OAuth2.CLOUD_INSTANCE_HOST_NAME);
        if (!StringExtensions.isNullOrBlank(cloudInstanceHostName)) {
            final URL authorityUrl = StringExtensions.getUrl(mRequest.getAuthority());
            final String newAuthorityUrlString = new Uri.Builder().scheme(HTTPS_PROTOCOL_STRING).authority(cloudInstanceHostName).path(authorityUrl.getPath()).build().toString();
            setTokenEndpoint(newAuthorityUrlString + DEFAULT_TOKEN_ENDPOINT);
            result.setAuthority(newAuthorityUrlString);
        }
    } else if (response.containsKey(AuthenticationConstants.OAuth2.ACCESS_TOKEN)) {
        // Token response
        boolean isMultiResourceToken = false;
        String expiresIn = response.get(AuthenticationConstants.OAuth2.EXPIRES_IN);
        Long expiresInLong;
        Calendar expires = new GregorianCalendar();
        expiresInLong = (expiresIn == null || expiresIn.isEmpty() ? ((long) AuthenticationConstants.DEFAULT_EXPIRATION_TIME_SEC) : Long.parseLong(expiresIn));
        // Compute token expiration
        expires.add(Calendar.SECOND, expiresIn == null || expiresIn.isEmpty() ? AuthenticationConstants.DEFAULT_EXPIRATION_TIME_SEC : Integer.parseInt(expiresIn));
        final String refreshToken = response.get(AuthenticationConstants.OAuth2.REFRESH_TOKEN);
        String resource = null;
        if (response.containsKey(AuthenticationConstants.AAD.RESOURCE) && !StringExtensions.isNullOrBlank(refreshToken)) {
            isMultiResourceToken = true;
            resource = response.get(AuthenticationConstants.AAD.RESOURCE);
        }
        UserInfo userinfo = null;
        String tenantId = null;
        String rawIdToken = null;
        if (response.containsKey(AuthenticationConstants.OAuth2.ID_TOKEN)) {
            // IDtoken is related to Azure AD and returned with token
            // response. ADFS does not return that.
            rawIdToken = response.get(AuthenticationConstants.OAuth2.ID_TOKEN);
            if (!StringExtensions.isNullOrBlank(rawIdToken)) {
                Logger.v(TAG, "Id token was returned, parsing id token.");
                final IdToken tokenParsed = new IdToken(rawIdToken);
                if (tokenParsed != null) {
                    tenantId = tokenParsed.getTenantId();
                    userinfo = new UserInfo(tokenParsed);
                }
            } else {
                Logger.v(TAG, "IdToken was not returned from token request.");
            }
        }
        String familyClientId = null;
        if (response.containsKey(AuthenticationConstants.OAuth2.ADAL_CLIENT_FAMILY_ID)) {
            familyClientId = response.get(AuthenticationConstants.OAuth2.ADAL_CLIENT_FAMILY_ID);
        }
        ClientInfo clientInfo = null;
        if (response.containsKey(AuthenticationConstants.OAuth2.CLIENT_INFO)) {
            final String rawClientInfo = response.get(AuthenticationConstants.OAuth2.CLIENT_INFO);
            try {
                clientInfo = new ClientInfo(rawClientInfo);
            } catch (ServiceException e) {
                Logger.w(TAG, "ClientInfo decoding/parsing failed.");
            }
        }
        result = new AuthenticationResult(response.get(AuthenticationConstants.OAuth2.ACCESS_TOKEN), refreshToken, expires.getTime(), isMultiResourceToken, userinfo, tenantId, rawIdToken, null, mRequest.getClientId());
        result.setResource(resource);
        result.setClientInfo(clientInfo);
        result.setExpiresIn(expiresInLong);
        result.setResponseReceived(System.currentTimeMillis());
        if (response.containsKey(AuthenticationConstants.OAuth2.EXT_EXPIRES_IN)) {
            final String extendedExpiresIn = response.get(AuthenticationConstants.OAuth2.EXT_EXPIRES_IN);
            final Calendar extendedExpires = new GregorianCalendar();
            // Compute extended token expiration
            extendedExpires.add(Calendar.SECOND, StringExtensions.isNullOrBlank(extendedExpiresIn) ? AuthenticationConstants.DEFAULT_EXPIRATION_TIME_SEC : Integer.parseInt(extendedExpiresIn));
            result.setExtendedExpiresOn(extendedExpires.getTime());
        }
        // Set family client id on authentication result for TokenCacheItem to pick up
        result.setFamilyClientId(familyClientId);
    } else {
        result = null;
    }
    return result;
}
Also used : JWSBuilder(com.microsoft.identity.common.adal.internal.JWSBuilder) Calendar(java.util.Calendar) GregorianCalendar(java.util.GregorianCalendar) GregorianCalendar(java.util.GregorianCalendar) JSONException(org.json.JSONException) URL(java.net.URL) ServiceException(com.microsoft.identity.common.exception.ServiceException) List(java.util.List) ClientInfo(com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.ClientInfo) UUID(java.util.UUID)

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