Search in sources :

Example 1 with LocalAuthenticationResult

use of com.microsoft.identity.common.internal.result.LocalAuthenticationResult 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)

Example 2 with LocalAuthenticationResult

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

the class LocalMSALController method acquireDeviceCodeFlowToken.

@Override
public AcquireTokenResult acquireDeviceCodeFlowToken(@SuppressWarnings(WarningType.rawtype_warning) final AuthorizationResult authorizationResult, final DeviceCodeFlowCommandParameters parameters) throws ServiceException, ClientException, IOException {
    // Logging start of method
    final String methodName = ":acquireDeviceCodeFlowToken";
    Logger.verbose(TAG + methodName, "Device Code Flow: Polling for token...");
    // Start telemetry with LOCAL_DEVICE_CODE_FLOW_POLLING
    Telemetry.emit(new ApiStartEvent().putApiId(TelemetryEventStrings.Api.LOCAL_DEVICE_CODE_FLOW_POLLING));
    // Create empty AcquireTokenResult object
    final AcquireTokenResult acquireTokenResult = new AcquireTokenResult();
    // Assign authorization result
    acquireTokenResult.setAuthorizationResult(authorizationResult);
    // Fetch the Authorization Response
    final MicrosoftStsAuthorizationResponse authorizationResponse = (MicrosoftStsAuthorizationResponse) authorizationResult.getAuthorizationResponse();
    // DCF protocol step 2: Poll for token
    TokenResult tokenResult = null;
    try {
        // Create OAuth2Strategy using commandParameters and strategyParameters
        final OAuth2StrategyParameters strategyParameters = new OAuth2StrategyParameters();
        strategyParameters.setContext(parameters.getAndroidApplicationContext());
        @SuppressWarnings(WarningType.rawtype_warning) final OAuth2Strategy oAuth2Strategy = parameters.getAuthority().createOAuth2Strategy(strategyParameters);
        // Create token request outside of loop so it isn't re-created after every loop
        // Suppressing unchecked warnings due to casting of AuthorizationRequest to GenericAuthorizationRequest and MicrosoftStsAuthorizationResponse to GenericAuthorizationResponse in the arguments of call to createTokenRequest method
        @SuppressWarnings(WarningType.unchecked_warning) final MicrosoftStsTokenRequest tokenRequest = (MicrosoftStsTokenRequest) oAuth2Strategy.createTokenRequest(mAuthorizationRequest, authorizationResponse, parameters.getAuthenticationScheme());
        // Fetch wait interval
        final int intervalInMilliseconds = Integer.parseInt(authorizationResponse.getInterval()) * 1000;
        String errorCode = ErrorStrings.DEVICE_CODE_FLOW_AUTHORIZATION_PENDING_ERROR_CODE;
        // Loop to send multiple requests checking for token
        while (authorizationPending(errorCode)) {
            // Wait between polls
            ThreadUtils.sleepSafely(intervalInMilliseconds, TAG, "Attempting to sleep thread during Device Code Flow token polling...");
            // Reset error code
            errorCode = "";
            // Execute Token Request
            // Suppressing unchecked warnings due to casting of MicrosoftStsTokenRequest to GenericTokenRequest in the arguments of call to requestToken method
            @SuppressWarnings(WarningType.unchecked_warning) TokenResult tokenResultFromRequestToken = oAuth2Strategy.requestToken(tokenRequest);
            tokenResult = tokenResultFromRequestToken;
            // Fetch error if the request failed
            if (tokenResult.getErrorResponse() != null) {
                errorCode = tokenResult.getErrorResponse().getError();
            }
        }
        // Validate request success, may throw MsalServiceException
        validateServiceResult(tokenResult);
        // Assign token result
        acquireTokenResult.setTokenResult(tokenResult);
        // If the token is valid, save it into token cache
        final List<ICacheRecord> records = saveTokens(oAuth2Strategy, mAuthorizationRequest, acquireTokenResult.getTokenResult().getTokenResponse(), parameters.getOAuth2TokenCache());
        // Once the token is stored, fetch and assign the authentication result
        final ICacheRecord newestRecord = records.get(0);
        acquireTokenResult.setLocalAuthenticationResult(new LocalAuthenticationResult(finalizeCacheRecordForResult(newestRecord, parameters.getAuthenticationScheme()), records, SdkType.MSAL, false));
    } catch (Exception error) {
        Telemetry.emit(new ApiEndEvent().putException(error).putApiId(TelemetryEventStrings.Api.LOCAL_DEVICE_CODE_FLOW_POLLING));
        throw error;
    }
    logResult(TAG, tokenResult);
    // End telemetry with LOCAL_DEVICE_CODE_FLOW_POLLING
    Telemetry.emit(new ApiEndEvent().putResult(acquireTokenResult).putApiId(TelemetryEventStrings.Api.LOCAL_DEVICE_CODE_FLOW_POLLING));
    return acquireTokenResult;
}
Also used : AcquireTokenResult(com.microsoft.identity.common.internal.result.AcquireTokenResult) 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) OAuth2StrategyParameters(com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters) OAuth2Strategy(com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy) 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) MicrosoftStsAuthorizationResponse(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsAuthorizationResponse) ApiEndEvent(com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent) MicrosoftStsTokenRequest(com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsTokenRequest) ApiStartEvent(com.microsoft.identity.common.internal.telemetry.events.ApiStartEvent) LocalAuthenticationResult(com.microsoft.identity.common.internal.result.LocalAuthenticationResult)

Example 3 with LocalAuthenticationResult

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

the class CommandDispatcher method setCorrelationIdOnResult.

private static void setCorrelationIdOnResult(@NonNull final CommandResult commandResult, @NonNull final String correlationId) {
    // set correlation id on Local Authentication Result
    if (commandResult.getResult() != null && commandResult.getResult() instanceof LocalAuthenticationResult) {
        final LocalAuthenticationResult localAuthenticationResult = (LocalAuthenticationResult) commandResult.getResult();
        localAuthenticationResult.setCorrelationId(correlationId);
    }
}
Also used : LocalAuthenticationResult(com.microsoft.identity.common.internal.result.LocalAuthenticationResult)

Example 4 with LocalAuthenticationResult

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

the class LocalMSALController method acquireToken.

@Override
public AcquireTokenResult acquireToken(@NonNull final InteractiveTokenCommandParameters parameters) throws ExecutionException, InterruptedException, ClientException, IOException, ArgumentException {
    final String methodName = ":acquireToken";
    Logger.verbose(TAG + methodName, "Acquiring token...");
    Telemetry.emit(new ApiStartEvent().putProperties(parameters).putApiId(TelemetryEventStrings.Api.LOCAL_ACQUIRE_TOKEN_INTERACTIVE));
    final AcquireTokenResult acquireTokenResult = new AcquireTokenResult();
    // 00) Validate MSAL Parameters
    parameters.validate();
    // Add default scopes
    final Set<String> mergedScopes = addDefaultScopes(parameters);
    final InteractiveTokenCommandParameters parametersWithScopes = parameters.toBuilder().scopes(mergedScopes).build();
    logParameters(TAG, parametersWithScopes);
    // 0) Get known authority result
    throwIfNetworkNotAvailable(parametersWithScopes.getAndroidApplicationContext(), parametersWithScopes.isPowerOptCheckEnabled());
    Authority.KnownAuthorityResult authorityResult = Authority.getKnownAuthorityResult(parametersWithScopes.getAuthority());
    // 0.1 If not known throw resulting exception
    if (!authorityResult.getKnown()) {
        Telemetry.emit(new ApiEndEvent().putException(authorityResult.getClientException()).putApiId(TelemetryEventStrings.Api.LOCAL_ACQUIRE_TOKEN_INTERACTIVE));
        throw authorityResult.getClientException();
    }
    // Build up params for Strategy construction
    final OAuth2StrategyParameters strategyParameters = new OAuth2StrategyParameters();
    strategyParameters.setContext(parametersWithScopes.getAndroidApplicationContext());
    // 1) Get oAuth2Strategy for Authority Type
    @SuppressWarnings(WarningType.rawtype_warning) final OAuth2Strategy oAuth2Strategy = parametersWithScopes.getAuthority().createOAuth2Strategy(strategyParameters);
    // 2) Request authorization interactively
    @SuppressWarnings(WarningType.rawtype_warning) final AuthorizationResult result = performAuthorizationRequest(oAuth2Strategy, parametersWithScopes.getAndroidApplicationContext(), parametersWithScopes);
    acquireTokenResult.setAuthorizationResult(result);
    logResult(TAG, result);
    if (result.getAuthorizationStatus().equals(AuthorizationStatus.SUCCESS)) {
        // 3) Exchange authorization code for token
        final TokenResult tokenResult = performTokenRequest(oAuth2Strategy, mAuthorizationRequest, result.getAuthorizationResponse(), parametersWithScopes);
        acquireTokenResult.setTokenResult(tokenResult);
        if (tokenResult != null && tokenResult.getSuccess()) {
            // 4) Save tokens in token cache
            final List<ICacheRecord> records = saveTokens(oAuth2Strategy, mAuthorizationRequest, tokenResult.getTokenResponse(), parametersWithScopes.getOAuth2TokenCache());
            // The first element in the returned list is the item we *just* saved, the rest of
            // the elements are necessary to construct the full IAccount + TenantProfile
            final ICacheRecord newestRecord = records.get(0);
            acquireTokenResult.setLocalAuthenticationResult(new LocalAuthenticationResult(finalizeCacheRecordForResult(newestRecord, parametersWithScopes.getAuthenticationScheme()), records, SdkType.MSAL, false));
        }
    }
    Telemetry.emit(new ApiEndEvent().putResult(acquireTokenResult).putApiId(TelemetryEventStrings.Api.LOCAL_ACQUIRE_TOKEN_INTERACTIVE));
    return acquireTokenResult;
}
Also used : AcquireTokenResult(com.microsoft.identity.common.internal.result.AcquireTokenResult) ICacheRecord(com.microsoft.identity.common.internal.cache.ICacheRecord) Authority(com.microsoft.identity.common.internal.authorities.Authority) TokenResult(com.microsoft.identity.common.internal.providers.oauth2.TokenResult) AcquireTokenResult(com.microsoft.identity.common.internal.result.AcquireTokenResult) OAuth2StrategyParameters(com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters) InteractiveTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.InteractiveTokenCommandParameters) OAuth2Strategy(com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy) AuthorizationResult(com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult) ApiEndEvent(com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent) ApiStartEvent(com.microsoft.identity.common.internal.telemetry.events.ApiStartEvent) LocalAuthenticationResult(com.microsoft.identity.common.internal.result.LocalAuthenticationResult)

Example 5 with LocalAuthenticationResult

use of com.microsoft.identity.common.internal.result.LocalAuthenticationResult 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)

Aggregations

LocalAuthenticationResult (com.microsoft.identity.common.internal.result.LocalAuthenticationResult)5 ICacheRecord (com.microsoft.identity.common.internal.cache.ICacheRecord)4 AcquireTokenResult (com.microsoft.identity.common.internal.result.AcquireTokenResult)4 OAuth2Strategy (com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy)3 OAuth2StrategyParameters (com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters)3 TokenResult (com.microsoft.identity.common.internal.providers.oauth2.TokenResult)3 ApiEndEvent (com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent)3 ApiStartEvent (com.microsoft.identity.common.internal.telemetry.events.ApiStartEvent)3 ClientException (com.microsoft.identity.common.exception.ClientException)2 ArgumentException (com.microsoft.identity.common.exception.ArgumentException)1 ServiceException (com.microsoft.identity.common.exception.ServiceException)1 Authority (com.microsoft.identity.common.internal.authorities.Authority)1 AbstractAuthenticationScheme (com.microsoft.identity.common.internal.authscheme.AbstractAuthenticationScheme)1 InteractiveTokenCommandParameters (com.microsoft.identity.common.internal.commands.parameters.InteractiveTokenCommandParameters)1 SilentTokenCommandParameters (com.microsoft.identity.common.internal.commands.parameters.SilentTokenCommandParameters)1 AccountRecord (com.microsoft.identity.common.internal.dto.AccountRecord)1 RefreshTokenRecord (com.microsoft.identity.common.internal.dto.RefreshTokenRecord)1 MicrosoftStsAuthorizationResponse (com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsAuthorizationResponse)1 MicrosoftStsTokenRequest (com.microsoft.identity.common.internal.providers.microsoft.microsoftsts.MicrosoftStsTokenRequest)1 AuthorizationResult (com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult)1