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;
}
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;
}
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);
}
}
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;
}
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);
}
Aggregations