public async Task <string> GetBrokerAuthTokenSilentlyAsync(IDictionary <string, string> brokerPayload, Activity callerActivity)
        {
            CheckForBrokerAccountInfoInAccountManager(brokerPayload, callerActivity);
            Bundle silentOperationBundle = GetSilentBrokerBundle(brokerPayload);

            silentOperationBundle.PutString(BrokerConstants.BrokerAccountManagerOperationKey, BrokerConstants.AcquireTokenSilent);

            IAccountManagerFuture result = _androidAccountManager.AddAccount(BrokerConstants.BrokerAccountType,
                                                                             BrokerConstants.AuthtokenType,
                                                                             null,
                                                                             silentOperationBundle,
                                                                             null,
                                                                             null,
                                                                             GetPreferredLooper(callerActivity));

            if (result != null)
            {
                Bundle bundleResult = (Bundle)await result.GetResultAsync(
                    AccountManagerTimeoutSeconds,
                    TimeUnit.Seconds)
                                      .ConfigureAwait(false);

                if (bundleResult.GetBoolean(BrokerConstants.BrokerRequestV2Success))
                {
                    _logger.Info("Android Broker succsesfully refreshed the access token.");
                    return(bundleResult.GetString(BrokerConstants.BrokerResultV2));
                }
            }

            _logger.Info("Android Broker didn't return any results.");
            return(null);
        }
        public async Task <Intent> GetIntentForInteractiveBrokerRequestAsync(BrokerRequest brokerRequest, Activity callerActivity)
        {
            Intent intent = null;

            try
            {
                IAccountManagerFuture result = null;
                // Callback is not passed since it is making a blocking call to get
                // intent. Activity needs to be launched from calling app
                // to get the calling app's metadata if needed at BrokerActivity.

                Bundle addAccountOptions = new Bundle();
                addAccountOptions.PutString(BrokerConstants.BrokerAccountManagerOperationKey, BrokerConstants.GetIntentForInteractiveRequest);

                result = _androidAccountManager.AddAccount(BrokerConstants.BrokerAccountType,
                                                           BrokerConstants.AuthtokenType,
                                                           null,
                                                           addAccountOptions,
                                                           null,
                                                           null,
                                                           GetPreferredLooper(callerActivity));

                if (result == null)
                {
                    _logger.Info("Android account manager didn't return any results for interactive broker request.");
                }

                Bundle bundleResult = (Bundle)await result.GetResultAsync(
                    AccountManagerTimeoutSeconds,
                    TimeUnit.Seconds)
                                      .ConfigureAwait(false);

                intent = (Intent)bundleResult?.GetParcelable(AccountManager.KeyIntent);

                //Validate that the intent was created successfully.
                if (intent != null)
                {
                    _logger.Info("Intent created from BundleResult is not null. Starting interactive broker request");
                    // Need caller info UID for broker communication
                    intent.PutExtra(BrokerConstants.CallerInfoUID, Binder.CallingUid);
                }
                else
                {
                    _logger.Info("Intent created from BundleResult is null. ");
                    throw new MsalClientException(MsalError.NullIntentReturnedFromAndroidBroker, MsalErrorMessage.NullIntentReturnedFromBroker);
                }

                intent = GetInteractiveBrokerIntent(brokerRequest, intent);
            }
            catch
            {
                _logger.Error("Error when trying to acquire intent for broker authentication.");
                throw;
            }

            return(intent);
        }
        public async Task <string> GetBrokerAuthTokenSilentlyAsync(BrokerRequest brokerRequest, Activity callerActivity)
        {
            CheckForBrokerAccountInfoInAccountManager(brokerRequest, callerActivity);
            Bundle silentOperationBundle = CreateSilentBrokerBundle(brokerRequest);

            silentOperationBundle.PutString(BrokerConstants.BrokerAccountManagerOperationKey, BrokerConstants.AcquireTokenSilent);

            IAccountManagerFuture result = _androidAccountManager.AddAccount(BrokerConstants.BrokerAccountType,
                                                                             BrokerConstants.AuthtokenType,
                                                                             null,
                                                                             silentOperationBundle,
                                                                             null,
                                                                             null,
                                                                             GetPreferredLooper(callerActivity));

            if (result != null)
            {
                Bundle bundleResult = null;

                try
                {
                    bundleResult = (Bundle)await result.GetResultAsync(
                        AccountManagerTimeoutSeconds,
                        TimeUnit.Seconds)
                                   .ConfigureAwait(false);
                }
                catch (OperationCanceledException ex)
                {
                    _logger.Error("An error occurred when trying to communicate with the account manager: " + ex.Message);
                }
                catch (Exception ex)
                {
                    throw new MsalClientException(MsalError.BrokerApplicationRequired, MsalErrorMessage.AndroidBrokerCannotBeInvoked, ex);
                }

                string responseJson = bundleResult.GetString(BrokerConstants.BrokerResultV2);

                bool success = bundleResult.GetBoolean(BrokerConstants.BrokerRequestV2Success);
                _logger.Info($"Android Broker Silent call result - success? {success}. ");

                if (!success)
                {
                    _logger.Warning($"Android Broker Silent call failed. " +
                                    $"This usually means that the RT cannot be refreshed and interaction is required. " +
                                    $"BundleResult: {bundleResult} Result string: {responseJson}");
                }

                // upstream logic knows how to extract potential errors from this result
                return(responseJson);
            }

            _logger.Info("Android Broker didn't return any results. ");
            return(null);
        }
        //Inorder for broker to use the V2 endpoint during authentication, MSAL must initiate a handshake with broker to specify what endpoint should be used for the request.
        public async Task InitiateBrokerHandshakeAsync(Activity callerActivity)
        {
            using (_logger.LogMethodDuration())
            {
                try
                {
                    Bundle helloRequestBundle = new Bundle();
                    helloRequestBundle.PutString(BrokerConstants.ClientAdvertisedMaximumBPVersionKey, BrokerConstants.BrokerProtocalVersionCode);
                    helloRequestBundle.PutString(BrokerConstants.ClientConfiguredMinimumBPVersionKey, "2.0");
                    helloRequestBundle.PutString(BrokerConstants.BrokerAccountManagerOperationKey, "HELLO");

                    IAccountManagerFuture result = _androidAccountManager.AddAccount(BrokerConstants.BrokerAccountType,
                                                                                     BrokerConstants.AuthtokenType,
                                                                                     null,
                                                                                     helloRequestBundle,
                                                                                     null,
                                                                                     null,
                                                                                     GetPreferredLooper(callerActivity));

                    if (result != null)
                    {
                        Bundle bundleResult = (Bundle)await result.GetResultAsync(
                            AccountManagerTimeoutSeconds,
                            TimeUnit.Seconds)
                                              .ConfigureAwait(false);

                        var bpKey = bundleResult?.GetString(BrokerConstants.NegotiatedBPVersionKey);

                        if (!string.IsNullOrEmpty(bpKey))
                        {
                            _logger.Info("Using broker protocol version: " + bpKey);
                            return;
                        }

                        throw new MsalClientException("Could not negotiate protocol version with broker.");
                    }

                    throw new MsalClientException("Could not communicate with broker via account manager");
                }
                catch
                {
                    _logger.Error("Error when trying to initiate communication with the broker.");
                    throw;
                }
            }
        }
        private async Task <Bundle> ExtractAccountManagerResultAsync(IAccountManagerFuture accountManagerResultFuture)
        {
            if (accountManagerResultFuture != null)
            {
                try
                {
                    return((Bundle)await accountManagerResultFuture.GetResultAsync(
                               AccountManagerTimeoutSeconds,
                               TimeUnit.Seconds)
                           .ConfigureAwait(false));
                }
                catch (System.OperationCanceledException ex)
                {
                    _logger.Error("[Android broker] An error occurred when trying to communicate with the account manager: " + ex.Message);
                }
            }

            throw new MsalClientException("[Android broker] Could not communicate with broker via account manager. Please ensure power optimization settings are turned off. ");
        }
Ejemplo n.º 6
0
        //Inorder for broker to use the V2 endpoint during authentication, MSAL must initiate a handshake with broker to specify what endpoint should be used for the request.
        public async Task InitiateBrokerHandshakeAsync(Activity callerActivity)
        {
            using (_logger.LogMethodDuration())
            {
                try
                {
                    Bundle helloRequestBundle = new Bundle();
                    helloRequestBundle.PutString(BrokerConstants.ClientAdvertisedMaximumBPVersionKey, BrokerConstants.BrokerProtocalVersionCode);
                    helloRequestBundle.PutString(BrokerConstants.ClientConfiguredMinimumBPVersionKey, "2.0");
                    helloRequestBundle.PutString(BrokerConstants.BrokerAccountManagerOperationKey, "HELLO");

                    IAccountManagerFuture result = _androidAccountManager.AddAccount(BrokerConstants.BrokerAccountType,
                                                                                     BrokerConstants.AuthtokenType,
                                                                                     null,
                                                                                     helloRequestBundle,
                                                                                     null,
                                                                                     null,
                                                                                     GetPreferredLooper(callerActivity));

                    if (result != null)
                    {
                        Bundle bundleResult = (Bundle)await result.GetResultAsync(
                            AccountManagerTimeoutSeconds,
                            TimeUnit.Seconds)
                                              .ConfigureAwait(false);

                        var bpKey = bundleResult?.GetString(BrokerConstants.NegotiatedBPVersionKey);

                        if (!string.IsNullOrEmpty(bpKey))
                        {
                            _logger.Info("Using broker protocol version: " + bpKey);
                            return;
                        }

                        dynamic errorResult      = JObject.Parse(bundleResult?.GetString(BrokerConstants.BrokerResultV2));
                        string  errorCode        = null;
                        string  errorDescription = null;

                        if (!string.IsNullOrEmpty(errorResult))
                        {
                            errorCode = errorResult[BrokerResponseConst.BrokerErrorCode]?.ToString();
                            string errorMessage = errorResult[BrokerResponseConst.BrokerErrorMessage]?.ToString();
                            errorDescription = $"An error occurred during hand shake with the broker. Error: {errorCode} Error Message: {errorMessage}";
                        }
                        else
                        {
                            errorCode        = BrokerConstants.BrokerUnknownErrorCode;
                            errorDescription = "An error occurred during hand shake with the broker, no detailed error information was returned";
                        }

                        _logger.Error(errorDescription);
                        throw new MsalClientException(errorCode, errorDescription);
                    }

                    throw new MsalClientException("Could not communicate with broker via account manager");
                }
                catch
                {
                    _logger.Error("Error when trying to initiate communication with the broker.");
                    throw;
                }
            }
        }