Search in sources :

Example 11 with OAuth2Strategy

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

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

the class LocalMSALController method performAuthorizationRequest.

// Suppressing rawtype warnings due to the generic types AuthorizationResult and OAuth2Strategy
@SuppressWarnings(WarningType.rawtype_warning)
private AuthorizationResult performAuthorizationRequest(@NonNull final OAuth2Strategy strategy, @NonNull final Context context, @NonNull final InteractiveTokenCommandParameters parameters) throws ExecutionException, InterruptedException, ClientException {
    throwIfNetworkNotAvailable(context, parameters.isPowerOptCheckEnabled());
    mAuthorizationStrategy = AuthorizationStrategyFactory.getInstance().getAuthorizationStrategy(parameters);
    mAuthorizationRequest = getAuthorizationRequest(strategy, parameters);
    // Suppressing unchecked warnings due to casting of AuthorizationRequest to GenericAuthorizationRequest and AuthorizationStrategy to GenericAuthorizationStrategy in the arguments of call to requestAuthorization method
    @SuppressWarnings(WarningType.unchecked_warning) final Future<AuthorizationResult> future = strategy.requestAuthorization(mAuthorizationRequest, mAuthorizationStrategy);
    final AuthorizationResult result = future.get();
    return result;
}
Also used : AuthorizationResult(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult)

Example 13 with OAuth2Strategy

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

the class LocalMSALController method deviceCodeFlowAuthRequest.

// Suppressing rawtype warnings due to the generic types AuthorizationResult and OAuth2Strategy
@SuppressWarnings(WarningType.rawtype_warning)
@Override
public AuthorizationResult deviceCodeFlowAuthRequest(final DeviceCodeFlowCommandParameters parameters) throws ServiceException, ClientException, IOException {
    // Logging start of method
    final String methodName = ":deviceCodeFlowAuthRequest";
    Logger.verbose(TAG + methodName, "Device Code Flow: Authorizing user code...");
    // Default scopes here
    final Set<String> mergedScopes = addDefaultScopes(parameters);
    final DeviceCodeFlowCommandParameters parametersWithScopes = parameters.toBuilder().scopes(mergedScopes).build();
    logParameters(TAG, parametersWithScopes);
    // Start telemetry with LOCAL_DEVICE_CODE_FLOW_ACQUIRE_URL_AND_CODE
    Telemetry.emit(new ApiStartEvent().putProperties(parametersWithScopes).putApiId(TelemetryEventStrings.Api.LOCAL_DEVICE_CODE_FLOW_ACQUIRE_URL_AND_CODE));
    final Authority.KnownAuthorityResult authorityResult = Authority.getKnownAuthorityResult(parametersWithScopes.getAuthority());
    // If not known throw resulting exception
    if (!authorityResult.getKnown()) {
        Telemetry.emit(new ApiEndEvent().putException(authorityResult.getClientException()).putApiId(TelemetryEventStrings.Api.LOCAL_DEVICE_CODE_FLOW_ACQUIRE_URL_AND_CODE));
        throw authorityResult.getClientException();
    }
    final AuthorizationResult authorizationResult;
    try {
        // Create OAuth2Strategy using commandParameters and strategyParameters
        final OAuth2StrategyParameters strategyParameters = new OAuth2StrategyParameters();
        strategyParameters.setContext(parametersWithScopes.getAndroidApplicationContext());
        final OAuth2Strategy oAuth2Strategy = parametersWithScopes.getAuthority().createOAuth2Strategy(strategyParameters);
        // DCF protocol step 1: Get user code
        // Populate global authorization request
        mAuthorizationRequest = getAuthorizationRequest(oAuth2Strategy, parametersWithScopes);
        // Call method defined in oAuth2Strategy to request authorization
        authorizationResult = oAuth2Strategy.getDeviceCode((MicrosoftStsAuthorizationRequest) mAuthorizationRequest);
        validateServiceResult(authorizationResult);
    } catch (Exception error) {
        Telemetry.emit(new ApiEndEvent().putException(error).putApiId(TelemetryEventStrings.Api.LOCAL_DEVICE_CODE_FLOW_ACQUIRE_URL_AND_CODE));
        throw error;
    }
    Logger.verbose(TAG + methodName, "Device Code Flow authorization step finished...");
    logResult(TAG, authorizationResult);
    // End telemetry with LOCAL_DEVICE_CODE_FLOW_ACQUIRE_URL_AND_CODE
    Telemetry.emit(new ApiEndEvent().putApiId(TelemetryEventStrings.Api.LOCAL_DEVICE_CODE_FLOW_ACQUIRE_URL_AND_CODE));
    return authorizationResult;
}
Also used : MicrosoftStsAuthorizationRequest(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsAuthorizationRequest) ApiEndEvent(com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent) Authority(com.microsoft.identity.common.internal.authorities.Authority) DeviceCodeFlowCommandParameters(com.microsoft.identity.common.internal.commands.parameters.DeviceCodeFlowCommandParameters) ApiStartEvent(com.microsoft.identity.common.internal.telemetry.events.ApiStartEvent) OAuth2StrategyParameters(com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters) OAuth2Strategy(com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy) AuthorizationResult(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult) ServiceException(com.microsoft.identity.common.exception.ServiceException) ClientException(com.microsoft.identity.common.exception.ClientException) IOException(java.io.IOException) ArgumentException(com.microsoft.identity.common.exception.ArgumentException) ExecutionException(java.util.concurrent.ExecutionException)

Example 14 with OAuth2Strategy

use of com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy 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)

Example 15 with OAuth2Strategy

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

the class ConfidentialClientHelper method requestAccessTokenForAutomation.

/**
 * Yep.  Hardcoding this method to retrieve access token for MSIDLABS
 */
private String requestAccessTokenForAutomation() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, IOException {
    String accessToken = null;
    final TokenRequest tokenRequest = this.createTokenRequest();
    tokenRequest.setGrantType(CLIENT_CREDENTIALS);
    final AccountsInOneOrganization aadAudience = new AccountsInOneOrganization(TENANT_ID);
    final AzureActiveDirectoryAuthority authority = new AzureActiveDirectoryAuthority(aadAudience);
    try {
        final OAuth2StrategyParameters strategyParameters = new OAuth2StrategyParameters();
        OAuth2Strategy<AccessToken, BaseAccount, AuthorizationRequest, AuthorizationRequest.Builder, AuthorizationStrategy, OAuth2Configuration, OAuth2StrategyParameters, AuthorizationResponse, RefreshToken, TokenRequest, TokenResponse, TokenResult, AuthorizationResult> strategy = authority.createOAuth2Strategy(strategyParameters);
        TokenResult tokenResult = strategy.requestToken(tokenRequest);
        if (tokenResult.getSuccess()) {
            accessToken = tokenResult.getTokenResponse().getAccessToken();
        } else {
            throw new RuntimeException(tokenResult.getErrorResponse().getErrorDescription());
        }
    } catch (final ClientException e) {
        e.printStackTrace();
    }
    return accessToken;
}
Also used : AuthorizationStrategy(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationStrategy) AuthorizationRequest(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationRequest) TokenResult(com.microsoft.identity.common.internal.providers.oauth2.TokenResult) OAuth2StrategyParameters(com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters) AuthorizationResult(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult) AuthorizationResponse(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResponse) RefreshToken(com.microsoft.identity.common.internal.providers.oauth2.RefreshToken) TokenResponse(com.microsoft.identity.common.internal.providers.oauth2.TokenResponse) AccessToken(com.microsoft.identity.common.internal.providers.oauth2.AccessToken) BaseAccount(com.microsoft.identity.common.BaseAccount) AccountsInOneOrganization(com.microsoft.identity.common.internal.authorities.AccountsInOneOrganization) TokenRequest(com.microsoft.identity.common.internal.providers.oauth2.TokenRequest) AzureActiveDirectoryAuthority(com.microsoft.identity.common.internal.authorities.AzureActiveDirectoryAuthority) OAuth2Configuration(com.microsoft.identity.common.internal.providers.oauth2.OAuth2Configuration) ClientException(com.microsoft.identity.common.exception.ClientException)

Aggregations

OAuth2StrategyParameters (com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters)7 TokenResult (com.microsoft.identity.common.internal.providers.oauth2.TokenResult)7 ClientException (com.microsoft.identity.common.exception.ClientException)6 OAuth2Strategy (com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy)6 AuthorizationResult (com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult)5 AcquireTokenResult (com.microsoft.identity.common.internal.result.AcquireTokenResult)5 ICacheRecord (com.microsoft.identity.common.internal.cache.ICacheRecord)4 TokenRequest (com.microsoft.identity.common.internal.providers.oauth2.TokenRequest)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 Authority (com.microsoft.identity.common.internal.authorities.Authority)3 OAuth2TokenCache (com.microsoft.identity.common.internal.providers.oauth2.OAuth2TokenCache)3 ArgumentException (com.microsoft.identity.common.exception.ArgumentException)2 ServiceException (com.microsoft.identity.common.exception.ServiceException)2 AzureActiveDirectoryAuthority (com.microsoft.identity.common.internal.authorities.AzureActiveDirectoryAuthority)2 CertificateCredential (com.microsoft.identity.common.internal.providers.keys.CertificateCredential)2 ClientCertificateMetadata (com.microsoft.identity.common.internal.providers.keys.ClientCertificateMetadata)2 KeyStoreConfiguration (com.microsoft.identity.common.internal.providers.keys.KeyStoreConfiguration)2 MicrosoftClientAssertion (com.microsoft.identity.common.internal.providers.microsoft.MicrosoftClientAssertion)2