Search in sources :

Example 16 with OAuth2TokenCache

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

the class BrokerOAuth2TokenCacheTest method testGetAccountsMsal.

@Test
public void testGetAccountsMsal() throws ClientException {
    // Load up the 'other caches' which a bunch of test credentials, see if we can get them out...
    int ii = 0;
    for (final OAuth2TokenCache cache : mOtherAppTokenCaches) {
        configureMocks(mOtherCacheTestBundles.get(ii));
        final ICacheRecord cacheRecord = cache.save(mockStrategy, mockRequest, mockResponse);
        final BrokerApplicationMetadata applicationMetadata = new BrokerApplicationMetadata();
        applicationMetadata.setClientId(cacheRecord.getIdToken().getClientId());
        applicationMetadata.setEnvironment(cacheRecord.getIdToken().getEnvironment());
        applicationMetadata.setFoci(cacheRecord.getRefreshToken().getFamilyId());
        applicationMetadata.setUid(testAppUids[ii++]);
        mApplicationMetadataCache.insert(applicationMetadata);
    }
    final List<String> clientIds = new ArrayList<>();
    for (final MsalOAuth2TokenCacheTest.AccountCredentialTestBundle testBundle : mOtherCacheTestBundles) {
        clientIds.add(testBundle.mGeneratedRefreshToken.getClientId());
    }
    final List<AccountRecord> xAppAccounts = new ArrayList<>();
    for (final int testUid : testAppUids) {
        // Create the cache to query...
        mBrokerOAuth2TokenCache = new BrokerOAuth2TokenCache(InstrumentationRegistry.getContext(), testUid, mApplicationMetadataCache, new BrokerOAuth2TokenCache.ProcessUidCacheFactory() {

            @Override
            public MsalOAuth2TokenCache getTokenCache(Context context, int bindingProcessUid) {
                return initAppUidCache(context, bindingProcessUid);
            }
        }, mFociCache);
        for (final String clientId : clientIds) {
            final List<AccountRecord> accountsInCache = mBrokerOAuth2TokenCache.getAccounts(ENVIRONMENT, clientId);
            xAppAccounts.addAll(accountsInCache);
        }
    }
    assertEquals(clientIds.size(), xAppAccounts.size());
    final List<AccountRecord> xAppAccountsNoParam = new ArrayList<>(mBrokerOAuth2TokenCache.getAccounts());
    assertEquals(xAppAccounts.size(), xAppAccountsNoParam.size());
    final Context context = InstrumentationRegistry.getContext();
    final BrokerOAuth2TokenCache brokerOAuth2TokenCache = new BrokerOAuth2TokenCache(context, TEST_APP_UID, new SharedPreferencesBrokerApplicationMetadataCache(context));
    assertEquals(0, brokerOAuth2TokenCache.getAccounts(ENVIRONMENT, CLIENT_ID).size());
    final BrokerOAuth2TokenCache brokerOAuth2TokenCache2 = new BrokerOAuth2TokenCache(context, TEST_APP_UID, new SharedPreferencesBrokerApplicationMetadataCache(context));
    assertEquals(xAppAccounts.size(), brokerOAuth2TokenCache2.getAccounts().size());
}
Also used : Context(android.content.Context) ICacheRecord(com.microsoft.identity.common.internal.cache.ICacheRecord) BrokerApplicationMetadata(com.microsoft.identity.common.internal.cache.BrokerApplicationMetadata) ArrayList(java.util.ArrayList) OAuth2TokenCache(com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache) MicrosoftFamilyOAuth2TokenCache(com.microsoft.identity.common.internal.cache.MicrosoftFamilyOAuth2TokenCache) MsalOAuth2TokenCache(com.microsoft.identity.common.internal.cache.MsalOAuth2TokenCache) BrokerOAuth2TokenCache(com.microsoft.identity.common.internal.cache.BrokerOAuth2TokenCache) AccountRecord(com.microsoft.identity.common.internal.dto.AccountRecord) BrokerOAuth2TokenCache(com.microsoft.identity.common.internal.cache.BrokerOAuth2TokenCache) SharedPreferencesBrokerApplicationMetadataCache(com.microsoft.identity.common.internal.cache.SharedPreferencesBrokerApplicationMetadataCache) Test(org.junit.Test)

Example 17 with OAuth2TokenCache

use of com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache 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 18 with OAuth2TokenCache

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

the class LocalMSALController method generateSignedHttpRequest.

@Override
public GenerateShrResult generateSignedHttpRequest(@NonNull final GenerateShrCommandParameters parameters) throws Exception {
    final Context context = parameters.getAndroidApplicationContext();
    final IClockSkewManager clockSkewManager = new ClockSkewManager(context);
    final OAuth2TokenCache cache = parameters.getOAuth2TokenCache();
    final String clientId = parameters.getClientId();
    final String homeAccountId = parameters.getHomeAccountId();
    final IPoPAuthenticationSchemeParams popSchemeParams = parameters.getPopParameters();
    final GenerateShrResult result;
    if (userHasLocalAccountRecord(cache, clientId, homeAccountId)) {
        // Perform the signing locally...
        result = DevicePoPUtils.generateSignedHttpRequest(context, clockSkewManager, popSchemeParams);
    } else {
        // Populate the error on the result and return...
        result = new GenerateShrResult();
        result.setErrorCode(GenerateShrResult.Errors.NO_ACCOUNT_FOUND);
        result.setErrorMessage("Account does not exist.");
    }
    return result;
}
Also used : Context(android.content.Context) OAuth2TokenCache(com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache) GenerateShrResult(com.microsoft.identity.common.internal.result.GenerateShrResult) IClockSkewManager(com.microsoft.identity.common.internal.util.IClockSkewManager) IClockSkewManager(com.microsoft.identity.common.internal.util.IClockSkewManager) ClockSkewManager(com.microsoft.identity.common.internal.util.ClockSkewManager) IPoPAuthenticationSchemeParams(com.microsoft.identity.common.internal.authscheme.IPoPAuthenticationSchemeParams)

Example 19 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 getAccountWithAggregatedAccountDataByLocalAccountId.

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

Example 20 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 saveAndLoadAggregatedAccountData.

@Override
@SuppressWarnings(UNCHECKED)
public List<ICacheRecord> saveAndLoadAggregatedAccountData(@NonNull final GenericOAuth2Strategy oAuth2Strategy, @NonNull final GenericAuthorizationRequest request, @NonNull final GenericTokenResponse response) throws ClientException {
    synchronized (this) {
        final String methodName = ":saveAndLoadAggregatedAccountData";
        final boolean isFoci = !StringExtensions.isNullOrBlank(response.getFamilyId());
        OAuth2TokenCache targetCache;
        Logger.info(TAG + methodName, "Saving to FOCI cache? [" + isFoci + "]");
        if (isFoci) {
            targetCache = mFociCache;
        } else {
            targetCache = getTokenCacheForClient(request.getClientId(), oAuth2Strategy.getIssuerCacheIdentifier(request), mCallingProcessUid);
            if (null == targetCache) {
                Logger.warn(TAG + methodName, "Existing cache not found. A new one will be created.");
                targetCache = initializeProcessUidCache(getContext(), mCallingProcessUid);
            }
        }
        final List<ICacheRecord> result = targetCache.saveAndLoadAggregatedAccountData(oAuth2Strategy, request, response);
        // The 0th element contains the record we *just* saved. Other records are corollary data.
        final ICacheRecord justSavedRecord = result.get(0);
        updateApplicationMetadataCache(justSavedRecord.getRefreshToken().getClientId(), justSavedRecord.getRefreshToken().getEnvironment(), justSavedRecord.getRefreshToken().getFamilyId(), mCallingProcessUid);
        return result;
    }
}
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