use of com.microsoft.identity.common.internal.result.AcquireTokenResult 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.internal.result.AcquireTokenResult in project microsoft-authentication-library-common-for-android by AzureAD.
the class DeviceCodeFlowCommand method execute.
@Override
public AcquireTokenResult execute() throws Exception {
final String methodName = ":execute";
Logger.verbose(TAG + methodName, "Device Code Flow command initiating...");
// Get the controller used to execute the command
final BaseController controller = getDefaultController();
// Fetch the parameters
final DeviceCodeFlowCommandParameters commandParameters = (DeviceCodeFlowCommandParameters) getParameters();
// Call deviceCodeFlowAuthRequest to get authorization result (Part 1 of DCF)
@SuppressWarnings(WarningType.rawtype_warning) final AuthorizationResult authorizationResult = controller.deviceCodeFlowAuthRequest(commandParameters);
// Fetch the authorization response
final MicrosoftStsAuthorizationResponse authorizationResponse = (MicrosoftStsAuthorizationResponse) authorizationResult.getAuthorizationResponse();
final Date expiredDate = new Date();
try {
long expiredInInMilliseconds = TimeUnit.SECONDS.toMillis(Long.parseLong(authorizationResponse.getExpiresIn()));
expiredDate.setTime(expiredDate.getTime() + expiredInInMilliseconds);
} catch (final NumberFormatException e) {
// Shouldn't happen, but if it does, we don't want to fail the request because of this.
Logger.error(TAG + methodName, "Failed to parse authorizationResponse.getExpiresIn()", e);
}
// Communicate with user app and provide authentication information
@SuppressWarnings(WarningType.rawtype_warning) final DeviceCodeFlowCommandCallback deviceCodeFlowCommandCallback = (DeviceCodeFlowCommandCallback) getCallback();
deviceCodeFlowCommandCallback.onUserCodeReceived(authorizationResponse.getVerificationUri(), authorizationResponse.getUserCode(), authorizationResponse.getMessage(), expiredDate);
// Call acquireDeviceCodeFlowToken to get token result (Part 2 of DCF)
final AcquireTokenResult tokenResult = controller.acquireDeviceCodeFlowToken(authorizationResult, commandParameters);
Logger.verbose(TAG + methodName, "Device Code Flow command exiting with token...");
return tokenResult;
}
use of com.microsoft.identity.common.internal.result.AcquireTokenResult 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