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