public async Task <MsalTokenResponse> AcquireTokenInteractiveAsync(
            AuthenticationRequestParameters authenticationRequestParameters,
            AcquireTokenInteractiveParameters acquireTokenInteractiveParameters)
        {
            CheckPowerOptimizationStatus();

            AndroidBrokerInteractiveResponseHelper.InteractiveBrokerTokenResponse = null;

            BrokerRequest brokerRequest = BrokerRequest.FromInteractiveParameters(
                authenticationRequestParameters, acquireTokenInteractiveParameters);

            // There can only be 1 broker request at a time so keep track of the correlation id
            AndroidBrokerInteractiveResponseHelper.InteractiveRequestCorrelationId = brokerRequest.CorrelationId;

            try
            {
                await InitiateBrokerHandshakeAsync().ConfigureAwait(false);
                await AcquireTokenInteractiveViaBrokerAsync(brokerRequest).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _logger.ErrorPiiWithPrefix(ex, "[Android broker] Android broker interactive invocation failed. ");
                _brokerHelper.HandleBrokerOperationError(ex);
            }

            using (_logger.LogBlockDuration("[Android broker] Waiting for Android broker response. "))
            {
                await AndroidBrokerInteractiveResponseHelper.ReadyForResponse.WaitAsync().ConfigureAwait(false);

                return(AndroidBrokerInteractiveResponseHelper.InteractiveBrokerTokenResponse);
            }
        }
        public async Task <MsalTokenResponse> AcquireTokenInteractiveAsync(
            AuthenticationRequestParameters authenticationRequestParameters,
            AcquireTokenInteractiveParameters acquireTokenInteractiveParameters)
        {
            s_androidBrokerTokenResponse = null;

            BrokerRequest brokerRequest = BrokerRequest.FromInteractiveParameters(
                authenticationRequestParameters, acquireTokenInteractiveParameters);

            // There can only be 1 broker request at a time so keep track of the correlation id
            s_correlationId = brokerRequest.CorrelationId;

            try
            {
                await _brokerHelper.InitiateBrokerHandshakeAsync(_parentActivity).ConfigureAwait(false);

                // todo: needed?
                // brokerPayload[BrokerParameter.BrokerAccountName] = AndroidBrokerHelper.GetValueFromBrokerPayload(brokerPayload, BrokerParameter.Username);

                await AcquireTokenInteractiveViaBrokerAsync(brokerRequest).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _logger.ErrorPiiWithPrefix(ex, "Android broker interactive invocation failed. ");
                HandleBrokerOperationError(ex);
            }

            using (_logger.LogBlockDuration("Waiting for Android broker response. "))
            {
                await s_readyForResponse.WaitAsync().ConfigureAwait(false);

                return(s_androidBrokerTokenResponse);
            }
        }
 /// <summary>
 /// Fire and forget the fetch action on a background thread.
 /// Do not change to Task and do not await it.
 /// </summary>
 internal static void ProcessFetchInBackground(
     MsalAccessTokenCacheItem oldAccessToken,
     Func <Task <AuthenticationResult> > fetchAction,
     ICoreLogger logger)
 {
     _ = Task.Run(async() =>
     {
         try
         {
             await fetchAction().ConfigureAwait(false);
         }
         catch (MsalServiceException ex)
         {
             string logMsg = $"Background fetch failed with MsalServiceException. Is AAD down? { ex.IsAadUnavailable()}";
             if (ex.StatusCode == 400)
             {
                 logger.ErrorPiiWithPrefix(ex, logMsg);
             }
             else
             {
                 logger.WarningPiiWithPrefix(ex, logMsg);
             }
         }
         catch (Exception ex)
         {
             string logMsg = $"Background fetch failed with exception.";
             logger.WarningPiiWithPrefix(ex, logMsg);
         }
     });
 }
示例#4
0
        private async Task <MsalTokenResponse> AcquireTokenInteractiveInternalAsync(BrokerRequest brokerRequest)
        {
            try
            {
                await AcquireTokenInteractiveViaContentProviderAsync(brokerRequest).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                _logger.ErrorPiiWithPrefix(ex, "[Android broker] Interactive invocation failed. ");
                _brokerHelper.HandleBrokerOperationError(ex);
            }

            using (_logger.LogBlockDuration("[Android broker] Waiting for broker response. "))
            {
                await AndroidBrokerInteractiveResponseHelper.ReadyForResponse.WaitAsync().ConfigureAwait(false);

                return(AndroidBrokerInteractiveResponseHelper.InteractiveBrokerTokenResponse);
            }
        }
示例#5
0
        byte[] ILegacyCachePersistence.LoadCache()
        {
            try
            {
                ISharedPreferences preferences = Application.Context.GetSharedPreferences(SharedPreferencesName, FileCreationMode.Private);
                string             stateString = preferences.GetString(SharedPreferencesKey, null);
                if (stateString != null)
                {
                    return(Convert.FromBase64String(stateString));
                }
            }
            catch (Exception ex)
            {
                _logger.ErrorPiiWithPrefix(ex, "An error occurred while reading the adal cache: ");
                // Ignore as the cache seems to be corrupt
            }

            return(null);
        }
        private async Task AcquireTokenInternalAsync(IDictionary <string, string> brokerPayload)
        {
            _brokerHelper.InitiateBrokerHandshake(_activity);

            Context mContext = Application.Context;

            brokerPayload[BrokerParameter.BrokerAccountName] = AndroidBrokerHelper.GetValueFromBrokerPayload(brokerPayload, BrokerParameter.LoginHint);

            // Don't send silent background request if account information is not provided
            if (!string.IsNullOrEmpty(AndroidBrokerHelper.GetValueFromBrokerPayload(brokerPayload, BrokerParameter.BrokerAccountName)) ||
                !string.IsNullOrEmpty(AndroidBrokerHelper.GetValueFromBrokerPayload(brokerPayload, BrokerParameter.Username)))
            {
                _logger.Verbose("User is specified for silent token request. Starting silent broker request");
                string silentResult = _brokerHelper.GetBrokerAuthTokenSilently(brokerPayload, _activity);
                _androidBrokerTokenResponse = CreateMsalTokenResponseFromResult(silentResult);
                _readyForResponse?.Release();
                return;
            }
            else
            {
                _logger.Verbose("User is not specified for silent token request");
            }

            _logger.Verbose("Starting Android Broker interactive authentication");

            // onActivityResult will receive the response for this activity.
            // Lauching this activity will switch to the broker app.
            Intent brokerIntent = _brokerHelper.GetIntentForInteractiveBrokerRequest(brokerPayload, _activity);

            if (brokerIntent != null)
            {
                try
                {
                    _logger.Info(
                        "Calling activity pid:" + AndroidNative.OS.Process.MyPid()
                        + " tid:" + AndroidNative.OS.Process.MyTid() + "uid:"
                        + AndroidNative.OS.Process.MyUid());

                    _activity.StartActivityForResult(brokerIntent, 1001);
                }
                catch (ActivityNotFoundException e)
                {
                    _logger.ErrorPiiWithPrefix(e, "Unable to get android activity during interactive broker request");
                }
            }

            await _readyForResponse.WaitAsync().ConfigureAwait(false);
        }
示例#7
0
        public void LaunchInteractiveActivity(Activity activity, Intent interactiveIntent)
        {
            // onActivityResult will receive the response for this activity.
            // Launching this activity will switch to the broker app.
            try
            {
                _logger.Info(
                    "[Android broker] Calling activity pid:" + Process.MyPid()
                    + " tid:" + Process.MyTid() + "uid:"
                    + Process.MyUid());

                activity.StartActivityForResult(interactiveIntent, 1001);
            }
            catch (ActivityNotFoundException e)
            {
                _logger.ErrorPiiWithPrefix(e, "[Android broker] Unable to get Android activity during interactive broker request. ");
                throw;
            }
        }
        private async Task AcquireTokenInternalAsync(IDictionary <string, string> brokerPayload)
        {
            try
            {
                if (brokerPayload.ContainsKey(BrokerParameter.BrokerInstallUrl))
                {
                    _logger.Info("Android Broker - broker payload contains install url");

                    var appLink = AndroidBrokerHelper.GetValueFromBrokerPayload(brokerPayload, BrokerParameter.BrokerInstallUrl);
                    _logger.Info("Android Broker - Starting ActionView activity to " + appLink);
                    _activity.StartActivity(new Intent(Intent.ActionView, AndroidNative.Net.Uri.Parse(appLink)));

                    throw new MsalClientException(
                              MsalError.BrokerApplicationRequired,
                              MsalErrorMessage.BrokerApplicationRequired);
                }
                await _brokerHelper.InitiateBrokerHandshakeAsync(_activity).ConfigureAwait(false);

                brokerPayload[BrokerParameter.BrokerAccountName] = AndroidBrokerHelper.GetValueFromBrokerPayload(brokerPayload, BrokerParameter.Username);

                // Don't send silent background request if account information is not provided
                if (brokerPayload.ContainsKey(BrokerParameter.IsSilentBrokerRequest))
                {
                    _logger.Verbose("User is specified for silent token request. Starting silent broker request.");
                    string silentResult = await _brokerHelper.GetBrokerAuthTokenSilentlyAsync(brokerPayload, _activity).ConfigureAwait(false);

                    if (!string.IsNullOrEmpty(silentResult))
                    {
                        s_androidBrokerTokenResponse = CreateMsalTokenResponseFromResult(silentResult);
                    }
                    else
                    {
                        s_androidBrokerTokenResponse = new MsalTokenResponse
                        {
                            Error            = MsalError.BrokerResponseReturnedError,
                            ErrorDescription = "Failed to acquire token silently from the broker." + MsalErrorMessage.AndroidBrokerCannotBeInvoked,
                        };
                    }
                    return;
                }
                else
                {
                    _logger.Verbose("User is not specified for silent token request");
                }

                _logger.Verbose("Starting Android Broker interactive authentication");

                // onActivityResult will receive the response for this activity.
                // Lauching this activity will switch to the broker app.

                Intent brokerIntent = await _brokerHelper
                                      .GetIntentForInteractiveBrokerRequestAsync(brokerPayload, _activity)
                                      .ConfigureAwait(false);

                if (brokerIntent != null)
                {
                    try
                    {
                        _logger.Info(
                            "Calling activity pid:" + AndroidNative.OS.Process.MyPid()
                            + " tid:" + AndroidNative.OS.Process.MyTid() + "uid:"
                            + AndroidNative.OS.Process.MyUid());

                        _activity.StartActivityForResult(brokerIntent, 1001);
                    }
                    catch (ActivityNotFoundException e)
                    {
                        _logger.ErrorPiiWithPrefix(e, "Unable to get android activity during interactive broker request");
                        throw;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.ErrorPiiWithPrefix(ex, "Broker invocation failed.");
                throw;
            }

            await s_readyForResponse.WaitAsync().ConfigureAwait(false);
        }