private static AuthorizationResult CreateResultForOkResponse(string url)
        {
            AuthorizationResult result = new AuthorizationResult(AuthorizationStatus.Success);

            if (!string.IsNullOrEmpty(url))
            {
                result.ParseAuthorizeResponse(url);       
            }

            return result;
        }
        /// <summary>
        /// 
        /// </summary>
        public static void SetAuthenticationAgentContinuationEventArgs(int requestCode, Result resultCode, Intent data)
        {
            AuthorizationResult authorizationResult = null;
            switch ((int)resultCode)
            {
                case (int)Result.Ok:
                    authorizationResult = CreateResultForOkResponse(data.GetStringExtra("ReturnedUrl"));
                    break;

                case (int)Result.Canceled:
                    authorizationResult = new AuthorizationResult(AuthorizationStatus.UserCancel, null);
                    break;

                default:
                    authorizationResult = new AuthorizationResult(AuthorizationStatus.UnknownError, null);
                    break;
            }

            WebUI.SetAuthorizationResult(authorizationResult);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            View.BackgroundColor = UIColor.White;

            _webView = new UIWebView((CGRect) View.Bounds);
            _webView.ShouldStartLoad = (wView, request, navType) =>
            {
                if (request == null)
                {
                    return true;
                }

                string requestUrlString = request.Url.ToString();
                
                if (requestUrlString.StartsWith(BrokerConstants.BrowserExtPrefix, StringComparison.OrdinalIgnoreCase))
                {
                    DispatchQueue.MainQueue.DispatchAsync(() => CancelAuthentication(null, null));
                    requestUrlString = requestUrlString.Replace(BrokerConstants.BrowserExtPrefix, "https://");
                    DispatchQueue.MainQueue.DispatchAsync(
                        () => UIApplication.SharedApplication.OpenUrl(new NSUrl(requestUrlString)));
                    this.DismissViewController(true, null);
                    return false;
                }

                if (requestUrlString.ToLower(CultureInfo.InvariantCulture).StartsWith(_callback.ToLower(CultureInfo.InvariantCulture), StringComparison.OrdinalIgnoreCase) || requestUrlString.StartsWith(BrokerConstants.BrowserExtInstallPrefix, StringComparison.OrdinalIgnoreCase))
                {
                    callbackMethod(new AuthorizationResult(AuthorizationStatus.Success, request.Url.ToString()));
                    this.DismissViewController(true, null);
                    return false;
                }

                if (requestUrlString.StartsWith(BrokerConstants.DeviceAuthChallengeRedirect, StringComparison.CurrentCultureIgnoreCase))
                {
                    Uri uri = new Uri(requestUrlString);
                    string query = uri.Query;
                    if (query.StartsWith("?", StringComparison.OrdinalIgnoreCase))
                    {
                        query = query.Substring(1);
                    }

                    Dictionary<string, string> keyPair = EncodingHelper.ParseKeyValueList(query, '&', true, false, null);
                    string responseHeader = PlatformPlugin.DeviceAuthHelper.CreateDeviceAuthChallengeResponse(keyPair).Result;
                    
                    NSMutableUrlRequest newRequest = (NSMutableUrlRequest)request.MutableCopy();
                    newRequest.Url = new NSUrl(keyPair["SubmitUrl"]);
                    newRequest[BrokerConstants.ChallengeResponseHeader] = responseHeader;
                    wView.LoadRequest(newRequest);
                    return false;
                }
                
                if (!request.Url.AbsoluteString.Equals("about:blank", StringComparison.CurrentCultureIgnoreCase) && !request.Url.Scheme.Equals("https", StringComparison.CurrentCultureIgnoreCase))
                {
                    AuthorizationResult result = new AuthorizationResult(AuthorizationStatus.ErrorHttp);
                    result.Error = MsalError.NonHttpsRedirectNotSupported;
                    result.ErrorDescription = MsalErrorMessage.NonHttpsRedirectNotSupported;
                    callbackMethod(result);
                    this.DismissViewController(true, null);
                    return false;
                }


                return true;
            };

            _webView.LoadFinished += delegate
            {
                // If the title is too long, iOS automatically truncates it and adds ...
                this.Title = _webView.EvaluateJavascript(@"document.title") ?? "Sign in";
            };

            View.AddSubview(_webView);

            this.NavigationItem.LeftBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Cancel,
                this.CancelAuthentication);

            NSUrlRequest startRequest = new NSUrlRequest(new NSUrl(this._url));
            _webView.LoadRequest(startRequest);

            // if this is false, page will be 'zoomed in' to normal size
            //webView.ScalesPageToFit = true;
        }
 internal async Task AcquireAuthorizationAsync(IDictionary<string, string> headers)
 {
     Uri authorizationUri = this.CreateAuthorizationUri();
     this.authorizationResult = await this._webUi.AcquireAuthorizationAsync(authorizationUri, this._redirectUri, headers, this.CallState).ConfigureAwait(false);
 }
 public static void SetAuthorizationResult(AuthorizationResult authorizationResultInput)
 {
     authorizationResult = authorizationResultInput;
     returnedUriReady.Release();
 }
        private Thread StartUIThread(string headers)
        {
            // Start a new UI thread to run the browser dialog on so that we can block this one and present
            // a synchronous interface to callers.
            Thread uiSubThread = new Thread(
                () =>
                {
                    try
                    {
                        this.formsSyncContext = new WindowsFormsSynchronizationContext();

                        this.dialog = new SilentWindowsFormsAuthenticationDialog(this.OwnerWindow)
                        {
                            NavigationWaitMiliSecs = NavigationWaitMiliSecs
                        };

                        this.dialog.Done += this.UIDoneHandler;

                        this.threadInitializedEvent.Set();

                        this.dialog.AuthenticateAAD(this.RequestUri, this.CallbackUri, headers);

                        // Start and turn control over to the message loop.
                        Application.Run();

                        this.result = this.dialog.Result;
                    }
                    catch (Exception e)
                    {
                        PlatformPlugin.Logger.Error(null, e);
                        // Catch all exceptions to transfer them to the original calling thread.
                        this.uiException = e;
                    }
                });

            uiSubThread.SetApartmentState(ApartmentState.STA);
            uiSubThread.IsBackground = true;
            uiSubThread.Start();

            return uiSubThread;
        }
 private void CallbackMethod(AuthorizationResult result)
 {
     SetAuthorizationResult(result);
 }
        public void NoCacheLookup()
        {
            Authenticator authenticator = new Authenticator(TestConstants.DefaultAuthorityHomeTenant, false, Guid.NewGuid());
            TokenCache cache = new TokenCache();
            TokenCacheKey key = new TokenCacheKey(TestConstants.DefaultAuthorityHomeTenant,
                TestConstants.DefaultScope, TestConstants.DefaultClientId,
                TestConstants.DefaultUniqueId, TestConstants.DefaultDisplayableId, TestConstants.DefaultHomeObjectId,
                TestConstants.DefaultPolicy);
            AuthenticationResultEx ex = new AuthenticationResultEx();
            ex.Result = new AuthenticationResult("Bearer", key.ToString(),
                new DateTimeOffset(DateTime.UtcNow + TimeSpan.FromSeconds(3599)));
            ex.Result.User = new User
            {
                DisplayableId = TestConstants.DefaultDisplayableId,
                UniqueId = TestConstants.DefaultUniqueId,
                HomeObjectId = TestConstants.DefaultHomeObjectId
            };
            ex.Result.FamilyId = "1";
            ex.RefreshToken = "someRT";
            cache.tokenCacheDictionary[key] = ex;

            IWebUI ui = Substitute.For<IWebUI>();
            AuthorizationResult ar = new AuthorizationResult(AuthorizationStatus.Success,
                TestConstants.DefaultAuthorityHomeTenant + "?code=some-code");
            ui.AcquireAuthorizationAsync(Arg.Any<Uri>(), Arg.Any<Uri>(), Arg.Any<IDictionary<string, string>>(),
                Arg.Any<CallState>())
                .Returns(ar);

            MockHttpMessageHandler mockHandler = new MockHttpMessageHandler();
            mockHandler.Method = HttpMethod.Post;
            mockHandler.QueryParams = new Dictionary<string, string>() {{"p", "some-policy"}};

            mockHandler.ResponseMessage = MockHelpers.CreateSuccessTokenResponseMessage();
            HttpMessageHandlerFactory.MockHandler = mockHandler;

            AuthenticationRequestParameters parameters = new AuthenticationRequestParameters()
            {
                Authenticator = authenticator,
                ClientKey = new ClientKey(TestConstants.DefaultClientId),
                Policy = "some-policy",
                RestrictToSingleUser = TestConstants.DefaultRestrictToSingleUser,
                Scope = TestConstants.DefaultScope.ToArray(),
                TokenCache = cache
            };

            InteractiveRequest request = new InteractiveRequest(parameters,
                TestConstants.ScopeForAnotherResource.ToArray(),
                new Uri("some://uri"), new PlatformParameters(), TestConstants.DefaultDisplayableId,
                UiOptions.SelectAccount, "extra=qp", ui);
            Task<AuthenticationResult> task = request.RunAsync();
            task.Wait();
            AuthenticationResult result = task.Result;
            Assert.IsNotNull(result);
            Assert.AreEqual(2, cache.Count);
            Assert.AreEqual(result.Token, "some-access-token");

            //both cache entry authorities are TestConstants.DefaultAuthorityHomeTenant
            foreach (var item in cache.ReadItems(TestConstants.DefaultClientId))
            {
                Assert.AreEqual(TestConstants.DefaultAuthorityHomeTenant, item.Authority);
            }
        }
        private static AuthorizationResult ProcessAuthorizationResult(WebAuthenticationResult webAuthenticationResult, CallState callState)
        {
            AuthorizationResult result;
            switch (webAuthenticationResult.ResponseStatus)
            {
                case WebAuthenticationStatus.Success:
                    result = new AuthorizationResult(AuthorizationStatus.Success, webAuthenticationResult.ResponseData);
                    break;
                case WebAuthenticationStatus.ErrorHttp:
                    result = new AuthorizationResult(AuthorizationStatus.ErrorHttp, webAuthenticationResult.ResponseErrorDetail.ToString(CultureInfo.InvariantCulture));
                    break;
                case WebAuthenticationStatus.UserCancel:
                    result = new AuthorizationResult(AuthorizationStatus.UserCancel, null);
                    break;
                default:
                    result = new AuthorizationResult(AuthorizationStatus.UnknownError, null);
                    break;
            }

            return result;
        }