Search in sources :

Example 1 with BrokerInteractiveTokenCommandParameters

use of com.microsoft.identity.common.internal.commands.parameters.BrokerInteractiveTokenCommandParameters in project microsoft-authentication-library-common-for-android by AzureAD.

the class CommandDispatcher method beginInteractive.

public static void beginInteractive(final InteractiveTokenCommand command) {
    final String methodName = ":beginInteractive";
    synchronized (sLock) {
        final LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(command.getParameters().getAndroidApplicationContext());
        // Cancel interactive request if authorizationInCurrentTask() returns true OR this is a broker request.
        if (LibraryConfiguration.getInstance().isAuthorizationInCurrentTask() || command.getParameters() instanceof BrokerInteractiveTokenCommandParameters) {
            // Send a broadcast to cancel if any active auth request is present.
            localBroadcastManager.sendBroadcast(new Intent(CANCEL_INTERACTIVE_REQUEST));
        }
        sInteractiveExecutor.execute(new Runnable() {

            @Override
            public void run() {
                final CommandParameters commandParameters = command.getParameters();
                final String correlationId = initializeDiagnosticContext(commandParameters.getCorrelationId(), commandParameters.getSdkType() == null ? SdkType.UNKNOWN.getProductName() : commandParameters.getSdkType().getProductName(), commandParameters.getSdkVersion());
                try {
                    // set correlation id on parameters as it may not already be set
                    commandParameters.setCorrelationId(correlationId);
                    logParameters(TAG + methodName, correlationId, commandParameters, command.getPublicApiId());
                    EstsTelemetry.getInstance().initTelemetryForCommand(command);
                    EstsTelemetry.getInstance().emitApiId(command.getPublicApiId());
                    final BroadcastReceiver resultReceiver = new BroadcastReceiver() {

                        @Override
                        public void onReceive(Context context, Intent intent) {
                            completeInteractive(intent);
                        }
                    };
                    CommandResult commandResult;
                    Handler handler = new Handler(Looper.getMainLooper());
                    localBroadcastManager.registerReceiver(resultReceiver, new IntentFilter(RETURN_INTERACTIVE_REQUEST_RESULT));
                    sCommand = command;
                    // Try executing request
                    commandResult = executeCommand(command);
                    sCommand = null;
                    localBroadcastManager.unregisterReceiver(resultReceiver);
                    // set correlation id on Local Authentication Result
                    setCorrelationIdOnResult(commandResult, correlationId);
                    Logger.info(TAG + methodName, "Completed interactive request for correlation id : **" + correlationId + ", with the status : " + commandResult.getStatus().getLogStatus());
                    EstsTelemetry.getInstance().flush(command, commandResult);
                    Telemetry.getInstance().flush(correlationId);
                    returnCommandResult(command, commandResult, handler);
                } finally {
                    DiagnosticContext.clear();
                }
            }
        });
    }
}
Also used : DiagnosticContext(com.microsoft.identity.common.logging.DiagnosticContext) Context(android.content.Context) IntentFilter(android.content.IntentFilter) Handler(android.os.Handler) Intent(android.content.Intent) CommandParameters(com.microsoft.identity.common.internal.commands.parameters.CommandParameters) BrokerInteractiveTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerInteractiveTokenCommandParameters) SilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.SilentTokenCommandParameters) BroadcastReceiver(android.content.BroadcastReceiver) LocalBroadcastManager(androidx.localbroadcastmanager.content.LocalBroadcastManager) BrokerInteractiveTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerInteractiveTokenCommandParameters)

Example 2 with BrokerInteractiveTokenCommandParameters

use of com.microsoft.identity.common.internal.commands.parameters.BrokerInteractiveTokenCommandParameters in project microsoft-authentication-library-common-for-android by AzureAD.

the class ExceptionAdapter method getExceptionFromTokenErrorResponse.

public static ServiceException getExceptionFromTokenErrorResponse(@Nullable final CommandParameters commandParameters, @NonNull final TokenErrorResponse errorResponse) {
    if (isIntunePolicyRequiredError(errorResponse)) {
        if (commandParameters == null || !(isBrokerTokenCommandParameters(commandParameters))) {
            Logger.warn(TAG, "In order to properly construct the IntuneAppProtectionPolicyRequiredException we need the command parameters to be supplied.  Returning as service exception instead.");
            return getExceptionFromTokenErrorResponse(errorResponse);
        }
        IntuneAppProtectionPolicyRequiredException policyRequiredException;
        if (commandParameters instanceof BrokerInteractiveTokenCommandParameters) {
            policyRequiredException = new IntuneAppProtectionPolicyRequiredException(errorResponse.getError(), errorResponse.getErrorDescription(), (BrokerInteractiveTokenCommandParameters) commandParameters);
        } else {
            policyRequiredException = new IntuneAppProtectionPolicyRequiredException(errorResponse.getError(), errorResponse.getErrorDescription(), (BrokerSilentTokenCommandParameters) commandParameters);
        }
        policyRequiredException.setOauthSubErrorCode(errorResponse.getSubError());
        setHttpResponseUsingTokenErrorResponse(policyRequiredException, errorResponse);
        return policyRequiredException;
    } else {
        return getExceptionFromTokenErrorResponse(errorResponse);
    }
}
Also used : BrokerSilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerSilentTokenCommandParameters) IntuneAppProtectionPolicyRequiredException(com.microsoft.identity.common.exception.IntuneAppProtectionPolicyRequiredException) BrokerInteractiveTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerInteractiveTokenCommandParameters)

Example 3 with BrokerInteractiveTokenCommandParameters

use of com.microsoft.identity.common.internal.commands.parameters.BrokerInteractiveTokenCommandParameters in project microsoft-authentication-library-common-for-android by AzureAD.

the class AdalBrokerRequestAdapter method brokerInteractiveParametersFromActivity.

@Override
public BrokerInteractiveTokenCommandParameters brokerInteractiveParametersFromActivity(@NonNull final Activity callingActivity) {
    final String methodName = "brokerInteractiveParametersFromActivity";
    Logger.verbose(TAG + methodName, "Constructing BrokerAcquireTokenOperationParameters from activity ");
    final Intent intent = callingActivity.getIntent();
    final int callingAppUid = intent.getIntExtra(AuthenticationConstants.Broker.CALLER_INFO_UID, 0);
    // There are two constants that need to be checked for the presence of the caller pkg name:
    // 1. CALLER_INFO_PACKAGE
    // 2. APP_PACKAGE_NAME
    // 
    // But wait! There are also versions of the ADAL library (Android) that did not send this value
    // in those cases, we simply 'lie' and say that the request came from **current** execution
    // context. This will not always be correct. We'll set a flag here to signal when the param
    // is used.
    final boolean callerPackageNameProvided = packageNameWasProvidedInBundle(intent.getExtras());
    String redirectUri;
    // If the caller package name was provided, compute their redirect
    if (callerPackageNameProvided) {
        // V1 Broker would compute the redirect_uri for the calling package, rather than
        // 'trust' the provided value -- this had the unfortunate consequence of allowing
        // callers to pass non-URL-encoded signature hashes into the library despite the documentation
        // prescribing otherwise. The ADAL.NET implementation unfortunately RELIES on this behavior,
        // forcing customers to use non-encoded values in order to pass validation check inside of
        // ADAL.NET. In order to not regress this experience, the redirect URI must now be computed
        // meaning that the ACCOUNT_REDIRECT parameter is basically ignored.
        redirectUri = BrokerValidator.getBrokerRedirectUri(callingActivity, getPackageNameFromBundle(intent.getExtras(), callingActivity.getApplicationContext()));
    } else {
        // The caller's package name was not provided, so we cannot compute the redirect for them.
        // In this case, use the provided value...
        redirectUri = intent.getStringExtra(AuthenticationConstants.Broker.ACCOUNT_REDIRECT);
    }
    final List<Pair<String, String>> extraQP = getExtraQueryParamAsList(intent.getStringExtra(AuthenticationConstants.Broker.ACCOUNT_EXTRA_QUERY_PARAM));
    final AzureActiveDirectoryAuthority authority = getRequestAuthorityWithExtraQP(intent.getStringExtra(AuthenticationConstants.Broker.ACCOUNT_AUTHORITY), extraQP);
    // We need to explicitly add tenant id as organizations if we want similar behavior from V2 endpoint
    if (AzureActiveDirectoryAudience.ALL.equalsIgnoreCase(authority.getAudience().getTenantId())) {
        authority.getAudience().setTenantId(AzureActiveDirectoryAudience.ORGANIZATIONS);
    }
    final String resource = intent.getStringExtra(AuthenticationConstants.Broker.ACCOUNT_RESOURCE);
    final Set<String> scopes = new HashSet<>();
    scopes.add(TokenCacheItemMigrationAdapter.getScopeFromResource(resource));
    String correlationIdString = intent.getStringExtra(AuthenticationConstants.Broker.ACCOUNT_CORRELATIONID);
    if (TextUtils.isEmpty(correlationIdString)) {
        Logger.info(TAG, "Correlation id not set by Adal, creating a new one");
        UUID correlationId = UUID.randomUUID();
        correlationIdString = correlationId.toString();
    }
    final BrokerInteractiveTokenCommandParameters commandParameters = BrokerInteractiveTokenCommandParameters.builder().authenticationScheme(new BearerAuthenticationSchemeInternal()).activity(callingActivity).androidApplicationContext(callingActivity.getApplicationContext()).sdkType(SdkType.ADAL).sdkVersion(intent.getStringExtra(AuthenticationConstants.Broker.ADAL_VERSION_KEY)).callerUid(callingAppUid).callerPackageName(getPackageNameFromBundle(intent.getExtras(), callingActivity.getApplicationContext())).callerAppVersion(intent.getStringExtra(AuthenticationConstants.AAD.APP_VERSION)).extraQueryStringParameters(extraQP).authority(authority).scopes(scopes).clientId(intent.getStringExtra(AuthenticationConstants.Broker.ACCOUNT_CLIENTID_KEY)).redirectUri(redirectUri).loginHint(intent.getStringExtra(AuthenticationConstants.Broker.ACCOUNT_NAME)).correlationId(correlationIdString).claimsRequestJson(intent.getStringExtra(AuthenticationConstants.Broker.ACCOUNT_CLAIMS)).prompt(OpenIdConnectPromptParameter._fromPromptBehavior(intent.getStringExtra(AuthenticationConstants.Broker.ACCOUNT_PROMPT))).authorizationAgent(AuthorizationAgent.WEBVIEW).build();
    return commandParameters;
}
Also used : BearerAuthenticationSchemeInternal(com.microsoft.identity.common.internal.authscheme.BearerAuthenticationSchemeInternal) AzureActiveDirectoryAuthority(com.microsoft.identity.common.internal.authorities.AzureActiveDirectoryAuthority) Intent(android.content.Intent) UUID(java.util.UUID) BrokerInteractiveTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerInteractiveTokenCommandParameters) Pair(android.util.Pair) HashSet(java.util.HashSet)

Example 4 with BrokerInteractiveTokenCommandParameters

use of com.microsoft.identity.common.internal.commands.parameters.BrokerInteractiveTokenCommandParameters in project microsoft-authentication-library-common-for-android by AzureAD.

the class MsalBrokerRequestAdapter method brokerInteractiveParametersFromActivity.

@Override
public BrokerInteractiveTokenCommandParameters brokerInteractiveParametersFromActivity(@NonNull final Activity callingActivity) {
    Logger.info(TAG, "Constructing BrokerAcquireTokenOperationParameters from calling activity");
    final Intent intent = callingActivity.getIntent();
    final BrokerRequest brokerRequest = brokerRequestFromBundle(intent.getExtras());
    if (brokerRequest == null) {
        Logger.error(TAG, "Broker Result is null, returning empty parameters, " + "validation is expected to fail", null);
        return BrokerInteractiveTokenCommandParameters.builder().build();
    }
    int callingAppUid = intent.getIntExtra(CALLER_INFO_UID, 0);
    List<Pair<String, String>> extraQP = QueryParamsAdapter._fromJson(brokerRequest.getExtraQueryStringParameter());
    List<Pair<String, String>> extraOptions = QueryParamsAdapter._fromJson(brokerRequest.getExtraOptions());
    ;
    final AzureActiveDirectoryAuthority authority = AdalBrokerRequestAdapter.getRequestAuthorityWithExtraQP(brokerRequest.getAuthority(), extraQP);
    if (authority != null) {
        authority.setMultipleCloudsSupported(brokerRequest.isMultipleCloudsSupported());
    }
    String correlationIdString = brokerRequest.getCorrelationId();
    if (TextUtils.isEmpty(correlationIdString)) {
        UUID correlationId = UUID.randomUUID();
        correlationIdString = correlationId.toString();
    }
    final String negotiatedBrokerProtocolVersion = intent.getStringExtra(NEGOTIATED_BP_VERSION_KEY);
    Logger.info(TAG, "Authorization agent passed in by MSAL: " + brokerRequest.getAuthorizationAgent());
    @SuppressWarnings("rawtypes") final BrokerInteractiveTokenCommandParameters.BrokerInteractiveTokenCommandParametersBuilder commandParametersBuilder = BrokerInteractiveTokenCommandParameters.builder().authenticationScheme(getAuthenticationScheme(callingActivity, brokerRequest)).activity(callingActivity).androidApplicationContext(callingActivity.getApplicationContext()).sdkType(brokerRequest.getSdkType() == null ? SdkType.MSAL : brokerRequest.getSdkType()).sdkVersion(brokerRequest.getMsalVersion()).callerUid(callingAppUid).applicationName(brokerRequest.getApplicationName()).applicationVersion(brokerRequest.getApplicationVersion()).callerPackageName(brokerRequest.getApplicationName()).callerAppVersion(brokerRequest.getApplicationVersion()).extraQueryStringParameters(extraQP).authority(authority).extraOptions(extraOptions).scopes(getScopesAsSet(brokerRequest.getScope())).clientId(brokerRequest.getClientId()).redirectUri(brokerRequest.getRedirect()).loginHint(brokerRequest.getUserName()).correlationId(correlationIdString).claimsRequestJson(brokerRequest.getClaims()).prompt(brokerRequest.getPrompt() != null ? OpenIdConnectPromptParameter.valueOf(brokerRequest.getPrompt()) : OpenIdConnectPromptParameter.UNSET).negotiatedBrokerProtocolVersion(negotiatedBrokerProtocolVersion).powerOptCheckEnabled(brokerRequest.isPowerOptCheckEnabled());
    if (AuthorizationAgent.BROWSER.name().equalsIgnoreCase(brokerRequest.getAuthorizationAgent()) && isCallingPackageIntune(brokerRequest.getApplicationName())) {
        // TODO : Remove this whenever we enable System Browser support in Broker for apps.
        Logger.info(TAG, "Setting Authorization Agent to Browser for Intune app");
        buildCommandParameterBuilder(commandParametersBuilder);
    } else {
        commandParametersBuilder.authorizationAgent(AuthorizationAgent.WEBVIEW);
    }
    // Set Global environment variable for instance discovery if present
    if (!TextUtils.isEmpty(brokerRequest.getEnvironment())) {
        AzureActiveDirectory.setEnvironment(Environment.valueOf(brokerRequest.getEnvironment()));
    }
    return commandParametersBuilder.build();
}
Also used : AzureActiveDirectoryAuthority(com.microsoft.identity.common.internal.authorities.AzureActiveDirectoryAuthority) Intent(android.content.Intent) BrokerRequest(com.microsoft.identity.common.internal.broker.BrokerRequest) GzipUtil.compressString(com.microsoft.identity.common.internal.util.GzipUtil.compressString) GzipUtil.decompressBytesToString(com.microsoft.identity.common.internal.util.GzipUtil.decompressBytesToString) UUID(java.util.UUID) BrokerInteractiveTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerInteractiveTokenCommandParameters) Pair(android.util.Pair)

Example 5 with BrokerInteractiveTokenCommandParameters

use of com.microsoft.identity.common.internal.commands.parameters.BrokerInteractiveTokenCommandParameters in project microsoft-authentication-library-common-for-android by AzureAD.

the class ApiStartEvent method putProperties.

public ApiStartEvent putProperties(@Nullable final CommandParameters parameters) {
    if (parameters == null) {
        return this;
    }
    if (parameters.getSdkType() != null) {
        put(Key.SDK_NAME, parameters.getSdkType().name());
    }
    put(Key.SDK_VERSION, parameters.getSdkVersion());
    // Pii
    put(Key.REDIRECT_URI, parameters.getRedirectUri());
    // Pii
    put(Key.CLIENT_ID, parameters.getClientId());
    put(Key.BROKER_PROTOCOL_VERSION, String.valueOf(parameters.getRequiredBrokerProtocolVersion()));
    if (parameters instanceof TokenCommandParameters) {
        final TokenCommandParameters tokenCommandParameters = (TokenCommandParameters) parameters;
        final Authority authority = tokenCommandParameters.getAuthority();
        if (authority != null) {
            if (authority.getAuthorityURL() != null) {
                // Pii
                put(Key.AUTHORITY, authority.getAuthorityURL().getAuthority());
            }
            put(Key.AUTHORITY_TYPE, authority.getAuthorityTypeString());
        }
        put(Key.CLAIM_REQUEST, StringUtil.isEmpty(tokenCommandParameters.getClaimsRequestJson()) ? Value.FALSE : Value.TRUE);
        if (tokenCommandParameters.getScopes() != null) {
            put(Key.SCOPE_SIZE, String.valueOf(tokenCommandParameters.getScopes().size()));
            // Pii
            put(Key.SCOPE, tokenCommandParameters.getScopes().toString());
        }
        final AbstractAuthenticationScheme authScheme = tokenCommandParameters.getAuthenticationScheme();
        if (null != authScheme) {
            put(Key.AUTHENTICATION_SCHEME, authScheme.getName());
        }
    }
    if (parameters instanceof InteractiveTokenCommandParameters) {
        final InteractiveTokenCommandParameters atOperationParameters = (InteractiveTokenCommandParameters) parameters;
        if (atOperationParameters.getAuthorizationAgent() != null) {
            put(Key.USER_AGENT, atOperationParameters.getAuthorizationAgent().name());
        }
        put(// Pii
        Key.LOGIN_HINT, atOperationParameters.getLoginHint());
        if (atOperationParameters.getExtraQueryStringParameters() != null) {
            put(// Pii
            Key.REQUEST_QUERY_PARAMS, String.valueOf(atOperationParameters.getExtraQueryStringParameters().size()));
        }
        if (atOperationParameters.getPrompt() != null) {
            put(Key.PROMPT_BEHAVIOR, atOperationParameters.getPrompt().toString());
        }
    }
    if (parameters instanceof SilentTokenCommandParameters) {
        final SilentTokenCommandParameters silentParameters = (SilentTokenCommandParameters) parameters;
        if (silentParameters.getAccount() != null) {
            // Pii
            put(Key.USER_ID, silentParameters.getAccount().getHomeAccountId());
        }
        put(Key.IS_FORCE_REFRESH, String.valueOf(silentParameters.isForceRefresh()));
    }
    if (parameters instanceof BrokerInteractiveTokenCommandParameters) {
    // TODO when integrate the telemetry with broker.
    }
    if (parameters instanceof BrokerSilentTokenCommandParameters) {
    // TODO when integrate the telemetry with broker.
    }
    return this;
}
Also used : AbstractAuthenticationScheme(com.microsoft.identity.common.internal.authscheme.AbstractAuthenticationScheme) SilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.SilentTokenCommandParameters) BrokerSilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerSilentTokenCommandParameters) BrokerSilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerSilentTokenCommandParameters) InteractiveTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.InteractiveTokenCommandParameters) BrokerInteractiveTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerInteractiveTokenCommandParameters) SilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.SilentTokenCommandParameters) TokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.TokenCommandParameters) BrokerSilentTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerSilentTokenCommandParameters) Authority(com.microsoft.identity.common.internal.authorities.Authority) InteractiveTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.InteractiveTokenCommandParameters) BrokerInteractiveTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerInteractiveTokenCommandParameters) BrokerInteractiveTokenCommandParameters(com.microsoft.identity.common.internal.commands.parameters.BrokerInteractiveTokenCommandParameters)

Aggregations

BrokerInteractiveTokenCommandParameters (com.microsoft.identity.common.internal.commands.parameters.BrokerInteractiveTokenCommandParameters)6 Intent (android.content.Intent)3 Context (android.content.Context)2 Pair (android.util.Pair)2 AzureActiveDirectoryAuthority (com.microsoft.identity.common.internal.authorities.AzureActiveDirectoryAuthority)2 BrokerSilentTokenCommandParameters (com.microsoft.identity.common.internal.commands.parameters.BrokerSilentTokenCommandParameters)2 SilentTokenCommandParameters (com.microsoft.identity.common.internal.commands.parameters.SilentTokenCommandParameters)2 UUID (java.util.UUID)2 BroadcastReceiver (android.content.BroadcastReceiver)1 IntentFilter (android.content.IntentFilter)1 Handler (android.os.Handler)1 LocalBroadcastManager (androidx.localbroadcastmanager.content.LocalBroadcastManager)1 ClientException (com.microsoft.identity.common.exception.ClientException)1 IntuneAppProtectionPolicyRequiredException (com.microsoft.identity.common.exception.IntuneAppProtectionPolicyRequiredException)1 Authority (com.microsoft.identity.common.internal.authorities.Authority)1 AbstractAuthenticationScheme (com.microsoft.identity.common.internal.authscheme.AbstractAuthenticationScheme)1 BearerAuthenticationSchemeInternal (com.microsoft.identity.common.internal.authscheme.BearerAuthenticationSchemeInternal)1 BrokerRequest (com.microsoft.identity.common.internal.broker.BrokerRequest)1 CommandParameters (com.microsoft.identity.common.internal.commands.parameters.CommandParameters)1 InteractiveTokenCommandParameters (com.microsoft.identity.common.internal.commands.parameters.InteractiveTokenCommandParameters)1