Search in sources :

Example 46 with ICacheRecord

use of com.microsoft.identity.common.internal.cache.ICacheRecord 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 47 with ICacheRecord

use of com.microsoft.identity.common.internal.cache.ICacheRecord in project microsoft-authentication-library-common-for-android by AzureAD.

the class LocalMSALController method getAccounts.

@Override
@WorkerThread
public List<ICacheRecord> getAccounts(@NonNull final CommandParameters parameters) {
    Telemetry.emit(new ApiStartEvent().putProperties(parameters).putApiId(TelemetryEventStrings.Api.LOCAL_GET_ACCOUNTS));
    @SuppressWarnings(WarningType.unchecked_warning) final List<ICacheRecord> accountsInCache = parameters.getOAuth2TokenCache().getAccountsWithAggregatedAccountData(// * wildcard
    null, parameters.getClientId());
    Telemetry.emit(new ApiEndEvent().putApiId(TelemetryEventStrings.Api.LOCAL_GET_ACCOUNTS).put(TelemetryEventStrings.Key.ACCOUNTS_NUMBER, Integer.toString(accountsInCache.size())).put(TelemetryEventStrings.Key.IS_SUCCESSFUL, TelemetryEventStrings.Value.TRUE));
    return accountsInCache;
}
Also used : ICacheRecord(com.microsoft.identity.common.internal.cache.ICacheRecord) ApiEndEvent(com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent) ApiStartEvent(com.microsoft.identity.common.internal.telemetry.events.ApiStartEvent) WorkerThread(androidx.annotation.WorkerThread)

Example 48 with ICacheRecord

use of com.microsoft.identity.common.internal.cache.ICacheRecord in project microsoft-authentication-library-common-for-android by AzureAD.

the class GetCurrentAccountCommand method execute.

@Override
public List<ICacheRecord> execute() throws Exception {
    final String methodName = ":execute";
    List<ICacheRecord> result = new ArrayList<>();
    for (int ii = 0; ii < getControllers().size(); ii++) {
        final BaseController controller = getControllers().get(ii);
        com.microsoft.identity.common.internal.logging.Logger.verbose(TAG + methodName, "Executing with controller: " + controller.getClass().getSimpleName());
        result.addAll(controller.getCurrentAccount(getParameters()));
    }
    return result;
}
Also used : ICacheRecord(com.microsoft.identity.common.internal.cache.ICacheRecord) BaseController(com.microsoft.identity.common.internal.controllers.BaseController) ArrayList(java.util.ArrayList)

Example 49 with ICacheRecord

use of com.microsoft.identity.common.internal.cache.ICacheRecord in project microsoft-authentication-library-common-for-android by AzureAD.

the class MsalBrokerResultAdapter method authenticationResultFromBundle.

@Override
@NonNull
public ILocalAuthenticationResult authenticationResultFromBundle(@NonNull final Bundle resultBundle) throws ClientException {
    final BrokerResult brokerResult = brokerResultFromBundle(resultBundle);
    Logger.info(TAG, "Broker Result returned from Bundle, constructing authentication result");
    final List<ICacheRecord> tenantProfileCacheRecords = brokerResult.getTenantProfileData();
    if (tenantProfileCacheRecords == null) {
        Logger.error(TAG, "getTenantProfileData is null", null);
        throw new ClientException(INVALID_BROKER_BUNDLE, "getTenantProfileData is null.");
    }
    return new LocalAuthenticationResult(tenantProfileCacheRecords.get(0), tenantProfileCacheRecords, SdkType.MSAL, brokerResult.isServicedFromCache());
}
Also used : BrokerResult(com.microsoft.identity.common.internal.broker.BrokerResult) ICacheRecord(com.microsoft.identity.common.internal.cache.ICacheRecord) ClientException(com.microsoft.identity.common.exception.ClientException) NonNull(androidx.annotation.NonNull)

Example 50 with ICacheRecord

use of com.microsoft.identity.common.internal.cache.ICacheRecord in project microsoft-authentication-library-common-for-android by AzureAD.

the class TokenShareUtility method getOrgIdFamilyRefreshTokenWithMetadata.

@Override
public ITokenShareResultInternal getOrgIdFamilyRefreshTokenWithMetadata(@NonNull final String identifier) throws BaseException {
    final ICacheRecord cacheRecord = getCacheRecordForIdentifier(identifier);
    throwIfCacheRecordIncomplete(identifier, cacheRecord);
    final ADALTokenCacheItem cacheItemToExport = adapt(cacheRecord.getIdToken(), cacheRecord.getRefreshToken());
    // Ship it
    return new TokenShareResultInternal(cacheRecord, SSOStateSerializer.serialize(cacheItemToExport), SSO_STATE_SERIALIZER_BLOB);
}
Also used : ICacheRecord(com.microsoft.identity.common.internal.cache.ICacheRecord) ADALTokenCacheItem(com.microsoft.identity.common.internal.cache.ADALTokenCacheItem)

Aggregations

ICacheRecord (com.microsoft.identity.common.internal.cache.ICacheRecord)51 Test (org.junit.Test)40 AccountRecord (com.microsoft.identity.common.internal.dto.AccountRecord)11 ArrayList (java.util.ArrayList)5 MsalOAuth2TokenCache (com.microsoft.identity.common.internal.cache.MsalOAuth2TokenCache)4 OAuth2TokenCache (com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache)4 AcquireTokenResult (com.microsoft.identity.common.internal.result.AcquireTokenResult)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 ClientException (com.microsoft.identity.common.exception.ClientException)3 BearerAuthenticationSchemeInternal (com.microsoft.identity.common.internal.authscheme.BearerAuthenticationSchemeInternal)3 BrokerApplicationMetadata (com.microsoft.identity.common.internal.cache.BrokerApplicationMetadata)3 BrokerOAuth2TokenCache (com.microsoft.identity.common.internal.cache.BrokerOAuth2TokenCache)3 MicrosoftFamilyOAuth2TokenCache (com.microsoft.identity.common.internal.cache.MicrosoftFamilyOAuth2TokenCache)3 IdTokenRecord (com.microsoft.identity.common.internal.dto.IdTokenRecord)3 RefreshTokenRecord (com.microsoft.identity.common.internal.dto.RefreshTokenRecord)3 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