Search in sources :

Example 6 with AcquireTokenResult

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;
}
Also used : AcquireTokenResult(com.microsoft.identity.common.internal.result.AcquireTokenResult) SilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.SilentTokenCommandParameters) ICacheRecord(com.microsoft.identity.common.internal.cache.ICacheRecord) OAuth2StrategyParameters(com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters) OAuth2Strategy(com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy) AbstractAuthenticationScheme(com.microsoft.identity.common.internal.authscheme.AbstractAuthenticationScheme) OAuth2TokenCache(com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache) ApiEndEvent(com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent) ApiStartEvent(com.microsoft.identity.common.internal.telemetry.events.ApiStartEvent) AccountRecord(com.microsoft.identity.common.internal.dto.AccountRecord) ClientException(com.microsoft.identity.common.exception.ClientException) LocalAuthenticationResult(com.microsoft.identity.common.internal.result.LocalAuthenticationResult)

Example 7 with AcquireTokenResult

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;
}
Also used : AcquireTokenResult(com.microsoft.identity.common.internal.result.AcquireTokenResult) MicrosoftStsAuthorizationResponse(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsAuthorizationResponse) BaseController(com.microsoft.identity.common.internal.controllers.BaseController) DeviceCodeFlowCommandParameters(com.microsoft.identity.common.internal.commands.parameters.DeviceCodeFlowCommandParameters) AuthorizationResult(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult) Date(java.util.Date)

Example 8 with AcquireTokenResult

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;
}
Also used : AcquireTokenResult(com.microsoft.identity.common.internal.result.AcquireTokenResult) SilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.SilentTokenCommandParameters) BaseController(com.microsoft.identity.common.internal.controllers.BaseController) UiRequiredException(com.microsoft.identity.common.exception.UiRequiredException) ClientException(com.microsoft.identity.common.exception.ClientException)

Aggregations

AcquireTokenResult (com.microsoft.identity.common.internal.result.AcquireTokenResult)8 ClientException (com.microsoft.identity.common.exception.ClientException)4 ICacheRecord (com.microsoft.identity.common.internal.cache.ICacheRecord)4 LocalAuthenticationResult (com.microsoft.identity.common.internal.result.LocalAuthenticationResult)4 ApiEndEvent (com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent)4 ApiStartEvent (com.microsoft.identity.common.internal.telemetry.events.ApiStartEvent)4 OAuth2Strategy (com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy)3 OAuth2StrategyParameters (com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters)3 TokenResult (com.microsoft.identity.common.internal.providers.oauth2.TokenResult)3 BaseException (com.microsoft.identity.common.exception.BaseException)2 SilentTokenCommandParameters (com.microsoft.identity.common.internal.commands.parameters.SilentTokenCommandParameters)2 BaseController (com.microsoft.identity.common.internal.controllers.BaseController)2 MicrosoftStsAuthorizationResponse (com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsAuthorizationResponse)2 AuthorizationResult (com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult)2 ExecutionException (java.util.concurrent.ExecutionException)2 Intent (android.content.Intent)1 Bundle (android.os.Bundle)1 ArgumentException (com.microsoft.identity.common.exception.ArgumentException)1 BrokerCommunicationException (com.microsoft.identity.common.exception.BrokerCommunicationException)1 IntuneAppProtectionPolicyRequiredException (com.microsoft.identity.common.exception.IntuneAppProtectionPolicyRequiredException)1