Search in sources :

Example 6 with OAuth2TokenCache

use of com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache in project microsoft-authentication-library-common-for-android by AzureAD.

the class BrokerOAuth2TokenCache method getAccounts.

/**
 * Broker-only API. Fetches AccountRecords from all provided caches - makes NO GUARANTEES
 * as to whether or not an AT/RT pair exists for these Accounts.
 *
 * @return A List of AccountRecords, may be empty but is never null.
 */
public List<AccountRecord> getAccounts() {
    final String methodName = ":getAccounts";
    final Set<AccountRecord> allAccounts = new HashSet<>();
    final List<BrokerApplicationMetadata> allMetadata = mApplicationMetadataCache.getAll();
    // TODO - Everything inside this loop can be parallelized... should it be?
    for (final BrokerApplicationMetadata metadata : allMetadata) {
        final OAuth2TokenCache candidateCache = getTokenCacheForClient(metadata);
        if (null != candidateCache) {
            allAccounts.addAll(((MsalOAuth2TokenCache) candidateCache).getAccountCredentialCache().getAccounts());
        }
    }
    // Hit the FOCI cache
    allAccounts.addAll(mFociCache.getAccountCredentialCache().getAccounts());
    final List<AccountRecord> allAccountsResult = new ArrayList<>(allAccounts);
    Logger.verbose(TAG + methodName, "Found [" + allAccountsResult.size() + "] accounts.");
    return allAccountsResult;
}
Also used : OAuth2TokenCache(com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache) AccountRecord(com.microsoft.identity.common.internal.dto.AccountRecord) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet)

Example 7 with OAuth2TokenCache

use of com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache in project microsoft-authentication-library-common-for-android by AzureAD.

the class BrokerOAuth2TokenCache method getAccountByHomeAccountId.

@Override
public AccountRecord getAccountByHomeAccountId(@Nullable final String environment, @NonNull final String clientId, @NonNull final String homeAccountId) {
    final String methodName = "getAccountByHomeAccountId";
    Logger.verbose(TAG + methodName, "Loading account by home account id.");
    if (null != environment) {
        OAuth2TokenCache targetCache = getTokenCacheForClient(clientId, environment, mCallingProcessUid);
        Logger.info(TAG + methodName, "Loading from FOCI cache? [" + (targetCache == null) + "]");
        if (null != targetCache) {
            return targetCache.getAccountByHomeAccountId(environment, clientId, homeAccountId);
        } else {
            return mFociCache.getAccountByHomeAccountId(environment, clientId, homeAccountId);
        }
    } else {
        AccountRecord result = null;
        final List<OAuth2TokenCache> cachesToInspect = getTokenCachesForClientId(clientId);
        final Iterator<OAuth2TokenCache> cacheIterator = cachesToInspect.iterator();
        while (null == result && cacheIterator.hasNext()) {
            result = cacheIterator.next().getAccountByHomeAccountId(environment, clientId, homeAccountId);
        }
        return result;
    }
}
Also used : OAuth2TokenCache(com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache) AccountRecord(com.microsoft.identity.common.internal.dto.AccountRecord)

Example 8 with OAuth2TokenCache

use of com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache in project microsoft-authentication-library-common-for-android by AzureAD.

the class BrokerOAuth2TokenCache method save.

@Override
public ICacheRecord save(@NonNull final GenericOAuth2Strategy oAuth2Strategy, @NonNull final GenericAuthorizationRequest request, @NonNull final GenericTokenResponse response) throws ClientException {
    final String methodName = ":save";
    final boolean isFoci = !StringExtensions.isNullOrBlank(response.getFamilyId());
    if (isFoci) {
        Logger.verbose(TAG + methodName, "Received FOCI value: [" + response.getFamilyId() + "]");
    }
    Logger.info(TAG + methodName, "Saving to FOCI cache? [" + isFoci + "]");
    OAuth2TokenCache targetCache;
    if (isFoci) {
        targetCache = mFociCache;
    } else {
        // Suppressing unchecked warning as the generic type was not provided for oAuth2Strategy and request of type GenericAuthorizationRequest
        @SuppressWarnings(WarningType.unchecked_warning) final String environment = oAuth2Strategy.getIssuerCacheIdentifier(request);
        // Try to find an existing cache for this application
        targetCache = getTokenCacheForClient(request.getClientId(), environment, mCallingProcessUid);
        if (null == targetCache) {
            // No existing cache could be found... Make a new one!
            Logger.warn(TAG + methodName, "Existing cache not found. A new one will be created.");
            targetCache = initializeProcessUidCache(getContext(), mCallingProcessUid);
        }
    }
    // Suppressing unchecked warnings due to casting of rawtypes to generic types of OAuth2TokenCache's instance targetCache while calling method save
    @SuppressWarnings(WarningType.unchecked_warning) final ICacheRecord result = targetCache.save(oAuth2Strategy, request, response);
    updateApplicationMetadataCache(result.getRefreshToken().getClientId(), result.getRefreshToken().getEnvironment(), result.getRefreshToken().getFamilyId(), mCallingProcessUid);
    return result;
}
Also used : OAuth2TokenCache(com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache)

Example 9 with OAuth2TokenCache

use of com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache in project microsoft-authentication-library-common-for-android by AzureAD.

the class BrokerOAuth2TokenCache method loadWithAggregatedAccountData.

/**
 * The caller of this method should inspect the result carefully.
 * <p>
 * If the result contains >1 element: tokens were found for the provided filter criteria and
 * additionally, tokens were found for this Account relative to a guest tenant.
 * <p>
 * If the result contains exactly 1 element, you may receive 1 of a few different
 * response payloads, depending on cache state...
 * <p>
 * If the result contains an AccountRecord, IdTokenRecord, AccessTokenRecord, and
 * RefreshTokenRecord then the result is OK to use. The caller should still check the expiry of
 * the AccessTokenRecord before returning the result to the caller, refreshing as necessary...
 * <p>
 * If the result contains only an AccountRecord then we had no tokens in the cache and the
 * library should do some equivalent of AUTH_REFRESH_FAILED_PROMPT_NOT_ALLOWED
 * <p>
 * If the result contains only an AccountRecord and RefreshTokenRecord then the caller should attempt to refresh
 * the access token. If it works, call BrokerOAuth2TokenCache#save() with the result. If it
 * fails, throw some equivalent of AUTH_REFRESH_FAILED_PROMPT_NOT_ALLOWED
 *
 * @param clientId The ClientId of the current app.
 * @param target   The 'target' (scopes) the requested token should contain.
 * @param account  The Account whose Credentials should be loaded.
 * @return A List of ICacheRecords for the supplied filter criteria.
 */
@SuppressWarnings(UNCHECKED)
@Override
public List<ICacheRecord> loadWithAggregatedAccountData(@NonNull final String clientId, @Nullable final String target, @NonNull final AccountRecord account, @NonNull final AbstractAuthenticationScheme authScheme) {
    synchronized (this) {
        final String methodName = ":loadWithAggregatedAccountData";
        final BrokerApplicationMetadata appMetadata = mApplicationMetadataCache.getMetadata(clientId, account.getEnvironment(), mCallingProcessUid);
        boolean isKnownFoci = false;
        if (null != appMetadata) {
            isKnownFoci = null != appMetadata.getFoci();
            Logger.info(TAG + methodName, "App is known foci? " + isKnownFoci);
        }
        final OAuth2TokenCache targetCache = getTokenCacheForClient(appMetadata);
        final boolean appIsUnknownUseFociAsFallback = null == targetCache;
        final List<ICacheRecord> resultRecords;
        Logger.info(TAG + methodName, "Loading from FOCI cache? [" + (isKnownFoci || appIsUnknownUseFociAsFallback) + "]");
        if (appIsUnknownUseFociAsFallback) {
            // We do not have a cache for this app or it is not yet known to be a member of the family
            // use the foci cache....
            // Load a sparse-record (if available) containing only the desired account and a
            // refresh token if available...
            resultRecords = new ArrayList<>();
            resultRecords.add(mFociCache.loadByFamilyId(clientId, target, account, authScheme));
        } else if (isKnownFoci) {
            resultRecords = mFociCache.loadByFamilyIdWithAggregatedAccountData(clientId, target, account, authScheme);
        } else {
            resultRecords = targetCache.loadWithAggregatedAccountData(clientId, target, account, authScheme);
        }
        final boolean resultFound = !resultRecords.isEmpty() && null != resultRecords.get(0).getRefreshToken();
        Logger.verbose(TAG + methodName, "Result found? [" + resultFound + "]");
        return resultRecords;
    }
}
Also used : OAuth2TokenCache(com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache)

Example 10 with OAuth2TokenCache

use of com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache in project microsoft-authentication-library-common-for-android by AzureAD.

the class BrokerOAuth2TokenCache method removeCredential.

@Override
public boolean removeCredential(@NonNull final Credential credential) {
    final String methodName = ":removeCredential";
    final OAuth2TokenCache targetCache = getTokenCacheForClient(credential.getClientId(), credential.getEnvironment(), mCallingProcessUid);
    boolean removed = false;
    if (null != targetCache) {
        removed = targetCache.removeCredential(credential);
    } else {
        Logger.warn(TAG + methodName, "Could not remove credential. Cache not found.");
    }
    Logger.verbose(TAG + methodName, "Credential removed? [" + removed + "]");
    return removed;
}
Also used : OAuth2TokenCache(com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache)

Aggregations

OAuth2TokenCache (com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache)20 AccountRecord (com.microsoft.identity.common.internal.dto.AccountRecord)11 ArrayList (java.util.ArrayList)6 ICacheRecord (com.microsoft.identity.common.internal.cache.ICacheRecord)5 Context (android.content.Context)3 Nullable (androidx.annotation.Nullable)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 MsalOAuth2TokenCache (com.microsoft.identity.common.internal.cache.MsalOAuth2TokenCache)3 Test (org.junit.Test)3 OAuth2StrategyParameters (com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters)2 TokenResult (com.microsoft.identity.common.internal.providers.oauth2.TokenResult)2 AcquireTokenResult (com.microsoft.identity.common.internal.result.AcquireTokenResult)2 LocalAuthenticationResult (com.microsoft.identity.common.internal.result.LocalAuthenticationResult)2 Uri (android.net.Uri)1 ClientException (com.microsoft.identity.common.exception.ClientException)1 AbstractAuthenticationScheme (com.microsoft.identity.common.internal.authscheme.AbstractAuthenticationScheme)1 IPoPAuthenticationSchemeParams (com.microsoft.identity.common.internal.authscheme.IPoPAuthenticationSchemeParams)1 AccountDeletionRecord (com.microsoft.identity.common.internal.cache.AccountDeletionRecord)1