public async Task <IWebTokenRequestResultWrapper> GetTokenSilentlyAsync(WebAccount webAccount, WebTokenRequest webTokenRequest)
        {
            using (_logger.LogBlockDuration("WAM:GetTokenSilentlyAsync:webAccount"))
            {
                var wamResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest, webAccount);

                return(new WebTokenRequestResultWrapper(wamResult));
            }
        }
        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);
            }
        }
示例#4
0
        public async Task <HttpResponse> SendPostAsync(Uri endpoint, IDictionary <string, string> headers, IDictionary <string, string> bodyParameters, ICoreLogger logger, CancellationToken cancellationToken = default)
        {
            using (logger.LogBlockDuration("Test HttpManager - SendPostAsync"))
            {
                await Task.Delay(Settings.NetworkAccessPenaltyMs).ConfigureAwait(false);

                // example endpoint https://login.microsoftonline.com/tid2/oauth2/v2.0/token

                var regexp = @"https://login.microsoftonline.com/(?<tid>.*)/oauth2/v2.0/token"; // captures the tenantID
                var m      = Regex.Match(endpoint.AbsoluteUri, regexp);
                var tid    = m.Groups["tid"];

                if (tid != null)
                {
                    return(new HttpResponse()
                    {
                        Body = GetDefaultTokenResponse(tid.Value),
                        StatusCode = System.Net.HttpStatusCode.OK
                    });
                }
                else
                {
                    throw new InvalidOperationException("Not expecting this /token request " + endpoint.AbsoluteUri);
                }
            }
        }
示例#5
0
        private async Task InvokeIosBrokerAsync(Dictionary <string, string> brokerPayload)
        {
            s_brokerResponseReady = new SemaphoreSlim(0);

            _logger.Info(iOSBrokerConstants.InvokeTheIosBroker);
            NSUrl url = new NSUrl(iOSBrokerConstants.InvokeV2Broker + brokerPayload.ToQueryParameter());

            _logger.VerbosePii(
                iOSBrokerConstants.BrokerPayloadPii + brokerPayload.ToQueryParameter(),
                iOSBrokerConstants.BrokerPayloadNoPii + brokerPayload.Count);

            DispatchQueue.MainQueue.DispatchAsync(() => UIApplication.SharedApplication.OpenUrl(url));

            using (_logger.LogBlockDuration("waiting for broker response"))
            {
                await s_brokerResponseReady.WaitAsync().ConfigureAwait(false);
            }
        }
示例#6
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);
            }
        }
        public async Task <IWebTokenRequestResultWrapper> GetTokenSilentlyAsync(WebAccount webAccount, WebTokenRequest webTokenRequest)
        {
            using (_logger.LogBlockDuration("WAM:GetTokenSilentlyAsync:webAccount"))
            {
                if (_logger.IsLoggingEnabled(LogLevel.Verbose))
                {
                    _logger.VerbosePii(webTokenRequest.ToLogString(true), webTokenRequest.ToLogString(false));
                    _logger.VerbosePii(webAccount.ToLogString(true), webAccount.ToLogString(false));
                }

                var wamResult = await WebAuthenticationCoreManager.GetTokenSilentlyAsync(webTokenRequest, webAccount);

                return(new WebTokenRequestResultWrapper(wamResult));
            }
        }
示例#8
0
        private async Task <HttpResponse> ExecuteWithRetryAsync(
            Uri endpoint,
            IDictionary <string, string> headers,
            HttpContent body,
            HttpMethod method,
            ICoreLogger logger,
            bool doNotThrow = false,
            bool retry      = true,
            CancellationToken cancellationToken = default)
        {
            Exception    timeoutException = null;
            bool         isRetryable      = false;
            bool         is5xxError       = false;
            HttpResponse response         = null;

            try
            {
                HttpContent clonedBody = body;
                if (body != null)
                {
                    // Since HttpContent would be disposed by underlying client.SendAsync(),
                    // we duplicate it so that we will have a copy in case we would need to retry
                    clonedBody = await CloneHttpContentAsync(body).ConfigureAwait(false);
                }

                using (logger.LogBlockDuration("[HttpManager] ExecuteAsync"))
                {
                    response = await ExecuteAsync(endpoint, headers, clonedBody, method, logger, cancellationToken).ConfigureAwait(false);
                }

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    return(response);
                }

                logger.Info(string.Format(CultureInfo.InvariantCulture,
                                          MsalErrorMessage.HttpRequestUnsuccessful,
                                          (int)response.StatusCode, response.StatusCode));

                is5xxError  = (int)response.StatusCode >= 500 && (int)response.StatusCode < 600;
                isRetryable = is5xxError && !HasRetryAfterHeader(response);
            }
            catch (TaskCanceledException exception)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    logger.Info("The HTTP request was cancelled. ");
                    throw;
                }

                logger.Error("The HTTP request failed. " + exception.Message);
                isRetryable = true;

                timeoutException = exception;
            }

            if (isRetryable && retry)
            {
                logger.Info("Retrying one more time..");
                await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false);

                return(await ExecuteWithRetryAsync(
                           endpoint,
                           headers,
                           body,
                           method,
                           logger,
                           doNotThrow,
                           retry : false).ConfigureAwait(false));
            }

            logger.Warning("Request retry failed.");
            if (timeoutException != null)
            {
                throw new MsalServiceException(
                          MsalError.RequestTimeout,
                          "Request to the endpoint timed out.",
                          timeoutException);
            }

            if (doNotThrow)
            {
                return(response);
            }

            if (is5xxError)
            {
                throw MsalServiceExceptionFactory.FromHttpResponse(
                          MsalError.ServiceNotAvailable,
                          "Service is unavailable to process the request",
                          response);
            }

            return(response);
        }