Search in sources :

Example 11 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 getAccountByLocalAccountId.

@Override
@Nullable
public AccountRecord getAccountByLocalAccountId(@Nullable final String environment, @NonNull final String clientId, @NonNull final String localAccountId) {
    final String methodName = ":getAccountByLocalAccountId";
    Logger.verbose(TAG + methodName, "Loading account by local 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.getAccountByLocalAccountId(environment, clientId, localAccountId);
        } else {
            return mFociCache.getAccountByLocalAccountId(environment, clientId, localAccountId);
        }
    } else {
        AccountRecord result = null;
        final List<OAuth2TokenCache> cachesToInspect = getTokenCachesForClientId(clientId);
        final Iterator<OAuth2TokenCache> cacheIterator = cachesToInspect.iterator();
        while (null == result && cacheIterator.hasNext()) {
            result = cacheIterator.next().getAccountByLocalAccountId(environment, clientId, localAccountId);
        }
        return result;
    }
}
Also used : OAuth2TokenCache(com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache) AccountRecord(com.microsoft.identity.common.internal.dto.AccountRecord) Nullable(androidx.annotation.Nullable)

Example 12 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.

@SuppressWarnings(UNCHECKED)
@Override
public List<AccountRecord> getAccounts(@Nullable final String environment, @NonNull final String clientId) {
    final String methodName = ":getAccounts (2 param)";
    final List<AccountRecord> result = new ArrayList<>();
    if (null != environment) {
        OAuth2TokenCache targetCache = getTokenCacheForClient(clientId, environment, mCallingProcessUid);
        if (null != targetCache) {
            result.addAll(targetCache.getAccounts(environment, clientId));
        } else {
            Logger.warn(TAG + methodName, "No caches to inspect.");
        }
    } else {
        final List<OAuth2TokenCache> cachesToInspect = getTokenCachesForClientId(clientId);
        for (final OAuth2TokenCache cache : cachesToInspect) {
            result.addAll(cache.getAccounts(environment, clientId));
        }
        Logger.verbose(TAG + methodName, "Found [" + result.size() + "] accounts.");
    }
    return result;
}
Also used : OAuth2TokenCache(com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache) AccountRecord(com.microsoft.identity.common.internal.dto.AccountRecord) ArrayList(java.util.ArrayList)

Example 13 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 getAccount.

@Override
@Nullable
public AccountRecord getAccount(@Nullable final String environment, @NonNull final String clientId, @NonNull final String homeAccountId, @Nullable final String realm) {
    final String methodName = ":getAccount";
    OAuth2TokenCache targetCache = null;
    AccountRecord result = null;
    if (null != environment) {
        targetCache = getTokenCacheForClient(clientId, environment, mCallingProcessUid);
        if (null == targetCache) {
            Logger.verbose(TAG + methodName, "Target cache was null. Using FOCI cache.");
            targetCache = mFociCache;
        }
        result = targetCache.getAccount(environment, clientId, homeAccountId, realm);
    } else {
        // We need to check all of the caches that match the supplied client id
        // If none match, return null...
        final List<OAuth2TokenCache> clientIdTokenCaches = getTokenCachesForClientId(clientId);
        final Iterator<OAuth2TokenCache> cacheIterator = clientIdTokenCaches.iterator();
        while (null == result && cacheIterator.hasNext()) {
            result = cacheIterator.next().getAccount(environment, clientId, homeAccountId, realm);
        }
    }
    return result;
}
Also used : OAuth2TokenCache(com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache) AccountRecord(com.microsoft.identity.common.internal.dto.AccountRecord) Nullable(androidx.annotation.Nullable)

Example 14 with OAuth2TokenCache

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

the class TokenCacheItemMigrationAdapter method tryFociTokenWithGivenClientId.

/**
 * Testing whether the given client ID can use the cached foci to refresh token.
 *
 * @param clientId           String of the given client id.
 * @param redirectUri        redirect url string of the given client id.
 * @param accountRecord      account record of request
 * @param refreshTokenRecord refresh token record of FOCI account
 * @return true if the given client id can use the cached foci token. False, otherwise.
 * @throws ClientException
 * @throws IOException
 */
public static boolean tryFociTokenWithGivenClientId(@SuppressWarnings(WarningType.rawtype_warning) @NonNull final OAuth2TokenCache brokerOAuth2TokenCache, @NonNull final String clientId, @NonNull final String redirectUri, @NonNull final RefreshTokenRecord refreshTokenRecord, @NonNull final IAccountRecord accountRecord) throws ClientException, IOException {
    final String methodName = ":tryFociTokenWithGivenClientId";
    final MicrosoftStsOAuth2Configuration config = new MicrosoftStsOAuth2Configuration();
    // Get authority url
    final Uri.Builder requestUrlBuilder = new Uri.Builder();
    requestUrlBuilder.scheme("https").authority(refreshTokenRecord.getEnvironment()).appendPath(StringUtil.isEmpty(accountRecord.getRealm()) ? ALL_ACCOUNTS_TENANT_ID : accountRecord.getRealm());
    final URL authorityUrl = new URL(requestUrlBuilder.build().toString());
    // set the token endpoint for the configuration
    config.setAuthorityUrl(authorityUrl);
    // Create the strategy
    final OAuth2StrategyParameters strategyParameters = new OAuth2StrategyParameters();
    final MicrosoftStsOAuth2Strategy strategy = new MicrosoftStsOAuth2Strategy(config, strategyParameters);
    final String refreshToken = refreshTokenRecord.getSecret();
    final String scopes;
    // https://identitydivision.visualstudio.com/Engineering/_workitems/edit/1222002
    if (TextUtils.equals(clientId, "87749df4-7ccf-48f8-aa87-704bad0e0e16")) {
        scopes = "https://devicemgmt.teams.microsoft.com/.default " + BaseController.getDelimitedDefaultScopeString();
        Logger.info(TAG + methodName, "Teams agent client ID - making a test request with teams agent resource.");
    } else {
        scopes = BaseController.getDelimitedDefaultScopeString();
    }
    // Create a correlation_id for the request
    final UUID correlationId = UUID.randomUUID();
    Logger.verbose(TAG + methodName, "Create the token request with correlationId [" + correlationId + "]");
    final MicrosoftStsTokenRequest tokenRequest = createTokenRequest(clientId, scopes, refreshToken, redirectUri, strategy, correlationId, "2");
    Logger.verbose(TAG + methodName, "Start refreshing token (to verify foci) with correlationId [" + correlationId + "]");
    final TokenResult tokenResult = strategy.requestToken(tokenRequest);
    Logger.verbose(TAG + methodName, "Is the client ID able to use the foci? [" + tokenResult.getSuccess() + "] with correlationId [" + correlationId + "]");
    if (tokenResult.getSuccess()) {
        // Save the token record in tha cache so that we have an entry in BrokerApplicationMetadata for this client id.
        final MicrosoftStsAuthorizationRequest authorizationRequest = createAuthRequest(strategy, clientId, redirectUri, scopes, accountRecord, correlationId);
        Logger.verbose(TAG + methodName, "Saving records to cache with client id" + clientId);
        brokerOAuth2TokenCacheSave(brokerOAuth2TokenCache, strategy, tokenResult, authorizationRequest);
    }
    return tokenResult.getSuccess();
}
Also used : MicrosoftStsAuthorizationRequest(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsAuthorizationRequest) MicrosoftStsTokenRequest(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsTokenRequest) TokenResult(com.microsoft.identity.common.internal.providers.oauth2.TokenResult) MicrosoftStsOAuth2Configuration(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsOAuth2Configuration) OAuth2StrategyParameters(com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters) MicrosoftStsOAuth2Strategy(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsOAuth2Strategy) UUID(java.util.UUID) Uri(android.net.Uri) URL(java.net.URL)

Example 15 with OAuth2TokenCache

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

the class BaseController method renewAccessToken.

protected void renewAccessToken(@NonNull final SilentTokenCommandParameters parameters, @NonNull final AcquireTokenResult acquireTokenSilentResult, @SuppressWarnings(WarningType.rawtype_warning) @NonNull final OAuth2TokenCache tokenCache, @SuppressWarnings(WarningType.rawtype_warning) @NonNull final OAuth2Strategy strategy, @NonNull final ICacheRecord cacheRecord) throws IOException, ClientException {
    final String methodName = ":renewAccessToken";
    Logger.info(TAG + methodName, "Renewing access token...");
    RefreshTokenRecord refreshTokenRecord = cacheRecord.getRefreshToken();
    logParameters(TAG, parameters);
    final TokenResult tokenResult = performSilentTokenRequest(strategy, refreshTokenRecord, parameters);
    acquireTokenSilentResult.setTokenResult(tokenResult);
    logResult(TAG + methodName, tokenResult);
    if (tokenResult.getSuccess()) {
        Logger.info(TAG + methodName, "Token request was successful");
        // Suppressing unchecked warnings due to casting of rawtypes to generic types of OAuth2TokenCache's instance tokenCache while calling method saveAndLoadAggregatedAccountData
        @SuppressWarnings(WarningType.unchecked_warning) final List<ICacheRecord> savedRecords = tokenCache.saveAndLoadAggregatedAccountData(strategy, getAuthorizationRequest(strategy, parameters), tokenResult.getTokenResponse());
        final ICacheRecord savedRecord = savedRecords.get(0);
        // Create a new AuthenticationResult to hold the saved record
        final LocalAuthenticationResult authenticationResult = new LocalAuthenticationResult(finalizeCacheRecordForResult(savedRecord, parameters.getAuthenticationScheme()), savedRecords, parameters.getSdkType(), false);
        // Set the client telemetry...
        if (null != tokenResult.getCliTelemInfo()) {
            final CliTelemInfo cliTelemInfo = tokenResult.getCliTelemInfo();
            authenticationResult.setSpeRing(cliTelemInfo.getSpeRing());
            authenticationResult.setRefreshTokenAge(cliTelemInfo.getRefreshTokenAge());
            Telemetry.emit(new CacheEndEvent().putSpeInfo(tokenResult.getCliTelemInfo().getSpeRing()));
        } else {
            // we can't put SpeInfo as the CliTelemInfo is null
            Telemetry.emit(new CacheEndEvent());
        }
        // Set the AuthenticationResult on the final result object
        acquireTokenSilentResult.setLocalAuthenticationResult(authenticationResult);
    } else {
        if (tokenResult.getErrorResponse() != null) {
            final String errorCode = tokenResult.getErrorResponse().getError();
            final String subErrorCode = tokenResult.getErrorResponse().getSubError();
            Logger.info(TAG, "Error: " + errorCode + " Suberror: " + subErrorCode);
            if (INVALID_GRANT.equals(errorCode) && BAD_TOKEN.equals(subErrorCode)) {
                boolean isRemoved = tokenCache.removeCredential(cacheRecord.getRefreshToken());
                Logger.info(TAG, "Refresh token is invalid, " + "attempting to delete the RT from cache, result:" + isRemoved);
            }
        } else {
            Logger.warn(TAG, "Invalid state, No token success or error response on the token result");
        }
    }
}
Also used : CliTelemInfo(com.microsoft.identity.common.internal.telemetry.CliTelemInfo) ICacheRecord(com.microsoft.identity.common.internal.cache.ICacheRecord) TokenResult(com.microsoft.identity.common.internal.providers.oauth2.TokenResult) AcquireTokenResult(com.microsoft.identity.common.internal.result.AcquireTokenResult) CacheEndEvent(com.microsoft.identity.common.internal.telemetry.events.CacheEndEvent) RefreshTokenRecord(com.microsoft.identity.common.internal.dto.RefreshTokenRecord) LocalAuthenticationResult(com.microsoft.identity.common.internal.result.LocalAuthenticationResult)

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