Search in sources :

Example 1 with MicrosoftRefreshToken

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

the class ADALOAuth2TokenCache method save.

/**
 * Method responsible for saving tokens contained in the TokenResponse to storage.
 *
 * @param strategy
 * @param request
 * @param response
 */
@Override
public ICacheRecord save(final AzureActiveDirectoryOAuth2Strategy strategy, final AzureActiveDirectoryAuthorizationRequest request, final AzureActiveDirectoryTokenResponse response) {
    final String methodName = "save";
    Logger.info(TAG + ":" + methodName, "Saving Tokens...");
    final String issuerCacheIdentifier = strategy.getIssuerCacheIdentifier(request);
    final AzureActiveDirectoryAccount account = strategy.createAccount(response);
    final String msalEnvironment = Uri.parse(issuerCacheIdentifier).getAuthority();
    account.setEnvironment(msalEnvironment);
    final AzureActiveDirectoryRefreshToken refreshToken = strategy.getRefreshTokenFromResponse(response);
    refreshToken.setEnvironment(msalEnvironment);
    Logger.info(TAG, "Constructing new ADALTokenCacheItem");
    final ADALTokenCacheItem cacheItem = new ADALTokenCacheItem(strategy, request, response);
    logTokenCacheItem(cacheItem);
    // There is more than one valid user identifier for some accounts... AAD Accounts as of this writing have 3
    Logger.info(TAG + ":" + methodName, "Setting items to cache for user...");
    for (final String cacheIdentifier : account.getCacheIdentifiers()) {
        // Azure AD Uses Resource and Not Scope... but we didn't override... heads up
        final String scope = request.getScope();
        final String clientId = request.getClientId();
        Logger.infoPII(TAG + ":" + methodName, "issuerCacheIdentifier: [" + issuerCacheIdentifier + "]");
        Logger.infoPII(TAG + ":" + methodName, "scope: [" + scope + "]");
        Logger.infoPII(TAG + ":" + methodName, "clientId: [" + clientId + "]");
        Logger.infoPII(TAG + ":" + methodName, "cacheIdentifier: [" + cacheIdentifier + "]");
        setItemToCacheForUser(issuerCacheIdentifier, scope, clientId, cacheItem, cacheIdentifier);
    }
    // For legacy reasons creating a cache entry where the userid is null
    // ADAL supported a single user mode where it was not necessary for the developer to provide the user id
    // on calls to acquireTokenSilentAsync
    setItemToCacheForUser(issuerCacheIdentifier, request.getScope(), request.getClientId(), cacheItem, null);
    // TODO At some point, the type-safety of this call needs to get beefed-up
    Logger.info(TAG + ":" + methodName, "Syncing SSO state to caches...");
    for (final IShareSingleSignOnState<MicrosoftAccount, MicrosoftRefreshToken> sharedSsoCache : mSharedSSOCaches) {
        try {
            sharedSsoCache.setSingleSignOnState(account, refreshToken);
        } catch (ClientException e) {
            Logger.errorPII(TAG, "Exception setting single sign on state for account " + account.getUsername(), e);
        }
    }
    // Returning null, since the ADAL cache's schema doesn't support this return type.
    return null;
}
Also used : AzureActiveDirectoryAccount(com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectoryAccount) MicrosoftAccount(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftAccount) AzureActiveDirectoryRefreshToken(com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectoryRefreshToken) MicrosoftRefreshToken(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftRefreshToken) ClientException(com.microsoft.identity.common.exception.ClientException)

Example 2 with MicrosoftRefreshToken

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

the class TokenCacheItemMigrationAdapter method renewToken.

@Nullable
public static Pair<MicrosoftAccount, MicrosoftRefreshToken> renewToken(@Nullable final String redirectUri, @NonNull final ITokenCacheItem targetCacheItemToRenew) {
    Pair<MicrosoftAccount, MicrosoftRefreshToken> resultPair = null;
    if (!StringExtensions.isNullOrBlank(redirectUri)) {
        try {
            final String authority = targetCacheItemToRenew.getAuthority();
            final String clientId = targetCacheItemToRenew.getClientId();
            final String refreshToken = targetCacheItemToRenew.getRefreshToken();
            final MicrosoftStsOAuth2Configuration config = new MicrosoftStsOAuth2Configuration();
            config.setAuthorityUrl(new URL(authority));
            // Create a correlation_id for the request
            final UUID correlationId = UUID.randomUUID();
            final String scopes;
            if (TextUtils.isEmpty(targetCacheItemToRenew.getResource())) {
                scopes = BaseController.getDelimitedDefaultScopeString();
            } else {
                scopes = getScopesForTokenRequest(targetCacheItemToRenew.getResource());
            }
            // Create the strategy
            final OAuth2StrategyParameters strategyParameters = new OAuth2StrategyParameters();
            final MicrosoftStsOAuth2Strategy strategy = new MicrosoftStsOAuth2Strategy(config, strategyParameters);
            final MicrosoftStsTokenRequest tokenRequest = createTokenRequest(clientId, scopes, refreshToken, redirectUri, strategy, correlationId, "2");
            final TokenResult tokenResult = strategy.requestToken(tokenRequest);
            if (tokenResult.getSuccess()) {
                final MicrosoftStsTokenResponse tokenResponse = (MicrosoftStsTokenResponse) tokenResult.getTokenResponse();
                tokenResponse.setClientId(clientId);
                // Create the Account to save...
                final MicrosoftAccount account = strategy.createAccount(tokenResponse);
                // Create the refresh token...
                final MicrosoftRefreshToken msStsRt = new MicrosoftStsRefreshToken(tokenResponse);
                msStsRt.setEnvironment(AzureActiveDirectory.getAzureActiveDirectoryCloud(new URL(authority)).getPreferredCacheHostName());
                resultPair = new Pair<>(account, msStsRt);
            } else {
                Logger.warn(TAG, correlationId.toString(), "TokenRequest was unsuccessful.");
                if (null != tokenResult.getErrorResponse()) {
                    logTokenResultError(correlationId, tokenResult);
                }
            }
        } catch (Exception e) {
            Logger.errorPII(TAG, "Failed to request new refresh token...", e);
        }
    }
    return resultPair;
}
Also used : TokenResult(com.microsoft.identity.common.internal.providers.oauth2.TokenResult) OAuth2StrategyParameters(com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters) MicrosoftStsOAuth2Strategy(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsOAuth2Strategy) MicrosoftStsRefreshToken(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsRefreshToken) URL(java.net.URL) ClientException(com.microsoft.identity.common.exception.ClientException) IOException(java.io.IOException) MicrosoftAccount(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftAccount) MicrosoftRefreshToken(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftRefreshToken) MicrosoftStsTokenRequest(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsTokenRequest) MicrosoftStsOAuth2Configuration(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsOAuth2Configuration) UUID(java.util.UUID) MicrosoftStsTokenResponse(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsTokenResponse) Nullable(androidx.annotation.Nullable)

Example 3 with MicrosoftRefreshToken

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

the class BrokerMsalController method saveMsaAccountToCache.

/**
 * Checks if the account returns is a MSA Account and sets single on state in cache
 */
private void saveMsaAccountToCache(@NonNull final Bundle resultBundle, @SuppressWarnings(WarningType.rawtype_warning) @NonNull final MsalOAuth2TokenCache msalOAuth2TokenCache) throws BaseException {
    final String methodName = ":saveMsaAccountToCache";
    final BrokerResult brokerResult = new MsalBrokerResultAdapter().brokerResultFromBundle(resultBundle);
    if (resultBundle.getBoolean(AuthenticationConstants.Broker.BROKER_REQUEST_V2_SUCCESS) && AzureActiveDirectoryAudience.MSA_MEGA_TENANT_ID.equalsIgnoreCase(brokerResult.getTenantId())) {
        Logger.info(TAG + methodName, "Result returned for MSA Account, saving to cache");
        if (StringUtil.isEmpty(brokerResult.getClientInfo())) {
            Logger.error(TAG + methodName, "ClientInfo is empty.", null);
            throw new ClientException(ErrorStrings.UNKNOWN_ERROR, "ClientInfo is empty.");
        }
        try {
            final ClientInfo clientInfo = new ClientInfo(brokerResult.getClientInfo());
            final MicrosoftStsAccount microsoftStsAccount = new MicrosoftStsAccount(new IDToken(brokerResult.getIdToken()), clientInfo);
            microsoftStsAccount.setEnvironment(brokerResult.getEnvironment());
            final MicrosoftRefreshToken microsoftRefreshToken = new MicrosoftRefreshToken(brokerResult.getRefreshToken(), clientInfo, brokerResult.getScope(), brokerResult.getClientId(), brokerResult.getEnvironment(), brokerResult.getFamilyId());
            msalOAuth2TokenCacheSetSingleSignOnState(msalOAuth2TokenCache, microsoftStsAccount, microsoftRefreshToken);
        } catch (ServiceException e) {
            Logger.errorPII(TAG + methodName, "Exception while creating Idtoken or ClientInfo," + " cannot save MSA account tokens", e);
            throw new ClientException(ErrorStrings.INVALID_JWT, e.getMessage(), e);
        }
    }
}
Also used : BrokerResult(com.microsoft.identity.common.internal.broker.BrokerResult) MsalBrokerResultAdapter(com.microsoft.identity.common.internal.result.MsalBrokerResultAdapter) MicrosoftStsAccount(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsAccount) MicrosoftRefreshToken(com.microsoft.identity.common.internal.providers.microsoft.MicrosoftRefreshToken) ServiceException(com.microsoft.identity.common.exception.ServiceException) IDToken(com.microsoft.identity.common.internal.providers.oauth2.IDToken) ClientException(com.microsoft.identity.common.exception.ClientException) ClientInfo(com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.ClientInfo)

Aggregations

ClientException (com.microsoft.identity.common.exception.ClientException)3 MicrosoftRefreshToken (com.microsoft.identity.common.internal.providers.microsoft.MicrosoftRefreshToken)3 MicrosoftAccount (com.microsoft.identity.common.internal.providers.microsoft.MicrosoftAccount)2 Nullable (androidx.annotation.Nullable)1 ServiceException (com.microsoft.identity.common.exception.ServiceException)1 BrokerResult (com.microsoft.identity.common.internal.broker.BrokerResult)1 AzureActiveDirectoryAccount (com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectoryAccount)1 AzureActiveDirectoryRefreshToken (com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.AzureActiveDirectoryRefreshToken)1 ClientInfo (com.microsoft.identity.common.internal.providers.microsoft.azureactivedirectory.ClientInfo)1 MicrosoftStsAccount (com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsAccount)1 MicrosoftStsOAuth2Configuration (com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsOAuth2Configuration)1 MicrosoftStsOAuth2Strategy (com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsOAuth2Strategy)1 MicrosoftStsRefreshToken (com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsRefreshToken)1 MicrosoftStsTokenRequest (com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsTokenRequest)1 MicrosoftStsTokenResponse (com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsTokenResponse)1 IDToken (com.microsoft.identity.common.internal.providers.oauth2.IDToken)1 OAuth2StrategyParameters (com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters)1 TokenResult (com.microsoft.identity.common.internal.providers.oauth2.TokenResult)1 MsalBrokerResultAdapter (com.microsoft.identity.common.internal.result.MsalBrokerResultAdapter)1 IOException (java.io.IOException)1