Search in sources :

Example 1 with ApiEndEvent

use of com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent in project microsoft-authentication-library-common-for-android by AzureAD.

the class BrokerOperationExecutor method emitOperationSuccessEvent.

private <U> void emitOperationSuccessEvent(@NonNull final BrokerOperation<U> operation, final U result) {
    if (operation.getTelemetryApiId() != null) {
        final ApiEndEvent successEvent = new ApiEndEvent().putApiId(operation.getTelemetryApiId()).isApiCallSuccessful(Boolean.TRUE);
        operation.putValueInSuccessEvent(successEvent, result);
        Telemetry.emit(successEvent);
    }
}
Also used : ApiEndEvent(com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent)

Example 2 with ApiEndEvent

use of com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent 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 ApiEndEvent

use of com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent in project microsoft-authentication-library-common-for-android by AzureAD.

the class BrokerMsalController method acquireToken.

/**
 * Performs interactive acquire token with Broker.
 *
 * @param parameters a {@link InteractiveTokenCommandParameters}
 * @return an {@link AcquireTokenResult}.
 */
@Override
public AcquireTokenResult acquireToken(@NonNull final InteractiveTokenCommandParameters parameters) throws BaseException, InterruptedException {
    Telemetry.emit(new ApiStartEvent().putProperties(parameters).putApiId(TelemetryEventStrings.Api.BROKER_ACQUIRE_TOKEN_INTERACTIVE));
    // Create BrokerResultFuture to block on response from the broker... response will be return as an activity result
    // BrokerActivity will receive the result and ask the API dispatcher to complete the request
    // In completeAcquireToken below we will set the result on the future and unblock the flow.
    mBrokerResultFuture = new BrokerResultFuture();
    // Get the broker interactive parameters intent
    final Intent interactiveRequestIntent = getBrokerAuthorizationIntent(parameters);
    // Pass this intent to the BrokerActivity which will be used to start this activity
    final Intent brokerActivityIntent = new Intent(parameters.getAndroidApplicationContext(), BrokerActivity.class);
    brokerActivityIntent.putExtra(BrokerActivity.BROKER_INTENT, interactiveRequestIntent);
    if (null == parameters.getActivity()) {
        // To support calling from OneAuth-MSAL, which may be initialized without an Activity
        // add Flags to start as a NEW_TASK if we are launching from an application Context
        brokerActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mApplicationContext.startActivity(brokerActivityIntent);
    } else {
        // Start the BrokerActivity using our existing Activity
        parameters.getActivity().startActivity(brokerActivityIntent);
    }
    // Wait to be notified of the result being returned... we could add a timeout here if we want to
    final Bundle resultBundle = mBrokerResultFuture.get();
    // If the request is from MSALCPP , OAuth2TokenCache will be null.
    if (parameters.getOAuth2TokenCache() != null) {
        saveMsaAccountToCache(resultBundle, (MsalOAuth2TokenCache) parameters.getOAuth2TokenCache());
    }
    final AcquireTokenResult result;
    try {
        result = new MsalBrokerResultAdapter().getAcquireTokenResultFromResultBundle(resultBundle);
    } catch (BaseException e) {
        Telemetry.emit(new ApiEndEvent().putException(e).putApiId(TelemetryEventStrings.Api.BROKER_ACQUIRE_TOKEN_INTERACTIVE));
        throw e;
    }
    Telemetry.emit(new ApiEndEvent().putResult(result).putApiId(TelemetryEventStrings.Api.BROKER_ACQUIRE_TOKEN_INTERACTIVE));
    return result;
}
Also used : AcquireTokenResult(com.microsoft.identity.common.internal.result.AcquireTokenResult) MsalBrokerResultAdapter(com.microsoft.identity.common.internal.result.MsalBrokerResultAdapter) BaseException(com.microsoft.identity.common.exception.BaseException) ApiEndEvent(com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent) Bundle(android.os.Bundle) BrokerOperationBundle(com.microsoft.identity.common.internal.broker.ipc.BrokerOperationBundle) ApiStartEvent(com.microsoft.identity.common.internal.telemetry.events.ApiStartEvent) BrokerResultFuture(com.microsoft.identity.common.internal.broker.BrokerResultFuture) Intent(android.content.Intent)

Example 4 with ApiEndEvent

use of com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent in project microsoft-authentication-library-common-for-android by AzureAD.

the class LocalMSALController method removeAccount.

@Override
@WorkerThread
public boolean removeAccount(@NonNull final RemoveAccountCommandParameters parameters) {
    Telemetry.emit(new ApiStartEvent().putProperties(parameters).putApiId(TelemetryEventStrings.Api.LOCAL_REMOVE_ACCOUNT));
    String realm = null;
    if (parameters.getAccount() != null) {
        realm = parameters.getAccount().getRealm();
    }
    final boolean localRemoveAccountSuccess = !parameters.getOAuth2TokenCache().removeAccount(// remove account from all environment
    null, parameters.getClientId(), parameters.getAccount() == null ? null : parameters.getAccount().getHomeAccountId(), realm).isEmpty();
    Telemetry.emit(new ApiEndEvent().put(TelemetryEventStrings.Key.IS_SUCCESSFUL, String.valueOf(localRemoveAccountSuccess)).putApiId(TelemetryEventStrings.Api.LOCAL_REMOVE_ACCOUNT));
    return localRemoveAccountSuccess;
}
Also used : ApiEndEvent(com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent) ApiStartEvent(com.microsoft.identity.common.internal.telemetry.events.ApiStartEvent) WorkerThread(androidx.annotation.WorkerThread)

Example 5 with ApiEndEvent

use of com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent 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)

Aggregations

ApiEndEvent (com.microsoft.identity.common.internal.telemetry.events.ApiEndEvent)8 ApiStartEvent (com.microsoft.identity.common.internal.telemetry.events.ApiStartEvent)7 ICacheRecord (com.microsoft.identity.common.internal.cache.ICacheRecord)4 OAuth2Strategy (com.microsoft.identity.common.internal.providers.oauth2.OAuth2Strategy)4 OAuth2StrategyParameters (com.microsoft.identity.common.internal.providers.oauth2.OAuth2StrategyParameters)4 AcquireTokenResult (com.microsoft.identity.common.internal.result.AcquireTokenResult)4 ClientException (com.microsoft.identity.common.exception.ClientException)3 LocalAuthenticationResult (com.microsoft.identity.common.internal.result.LocalAuthenticationResult)3 WorkerThread (androidx.annotation.WorkerThread)2 ArgumentException (com.microsoft.identity.common.exception.ArgumentException)2 ServiceException (com.microsoft.identity.common.exception.ServiceException)2 Authority (com.microsoft.identity.common.internal.authorities.Authority)2 AuthorizationResult (com.microsoft.identity.common.internal.providers.oauth2.AuthorizationResult)2 TokenResult (com.microsoft.identity.common.internal.providers.oauth2.TokenResult)2 IOException (java.io.IOException)2 ExecutionException (java.util.concurrent.ExecutionException)2 Intent (android.content.Intent)1 Bundle (android.os.Bundle)1 BaseException (com.microsoft.identity.common.exception.BaseException)1 AbstractAuthenticationScheme (com.microsoft.identity.common.internal.authscheme.AbstractAuthenticationScheme)1