/// <summary>
        /// Mimics the WebAuthenticationBroker's AuthenticateAsync method.
        /// </summary>
        public static Task <WebAuthenticationResult> AuthenticateAsync(WebAuthenticationOptions options, Uri startUri, Uri endUri)
        {
            if (options != WebAuthenticationOptions.None)
            {
                throw new NotImplementedException("This method does not support authentication options other than 'None'.");
            }

            PhoneApplicationFrame rootFrame = Application.Current.RootVisual as PhoneApplicationFrame;

            if (rootFrame == null)
            {
                throw new InvalidOperationException();
            }

            WebAuthenticationBroker.StartUri = startUri;
            WebAuthenticationBroker.EndUri   = endUri;
            WebAuthenticationBroker.AuthenticationInProgress = true;

            // Navigate to the login page.
            rootFrame.Navigate(new Uri("/Facebook.Client;component/loginpage.xaml", UriKind.Relative));

            Task <WebAuthenticationResult> task = Task <WebAuthenticationResult> .Factory.StartNew(() =>
            {
                authenticateFinishedEvent.WaitOne();
                return(new WebAuthenticationResult(responseData, responseStatus, responseErrorDetail));
            });

            return(task);
        }
 public static IAsyncOperation <AdnWebAuthenticationResult> AuthenticateAsync(
     WebAuthenticationOptions options,
     Uri startUri,
     Uri endUri)
 {
     return(AuthenticateAsyncTask(options, startUri, endUri).AsAsyncOperation());
 }
Example #3
0
 private async Task <WebAuthenticationResult> InvokeWABOnMainThreadAsync(
     Uri authorizationUri,
     Uri redirectUri,
     bool ssoMode,
     WebAuthenticationOptions options)
 {
     return(await CoreApplication.MainView.CoreWindow.Dispatcher.RunTaskAsync(
                async() =>
     {
         if (ssoMode)
         {
             return await
             WebAuthenticationBroker.AuthenticateAsync(options, authorizationUri)
             .AsTask()
             .ConfigureAwait(false);
         }
         else
         {
             return await WebAuthenticationBroker
             .AuthenticateAsync(options, authorizationUri, redirectUri)
             .AsTask()
             .ConfigureAwait(false);
         }
     })
            .ConfigureAwait(false));
 }
 private void SetOption( WebAuthenticationOptions option, bool value )
 {
     if ( value )
         options |= option;
     else
         options &= ~option;
 }
Example #5
0
        public async Task <AuthorizationResult> AcquireAuthorizationAsync(Uri authorizationUri, Uri redirectUri, IDictionary <string, string> additionalHeaders, CallState callState)
        {
            bool ssoMode = ReferenceEquals(redirectUri, Constant.SsoPlaceHolderUri);

            WebAuthenticationResult  webAuthenticationResult;
            WebAuthenticationOptions options = (this.useCorporateNetwork && (ssoMode || redirectUri.Scheme == Constant.MsAppScheme)) ? WebAuthenticationOptions.UseCorporateNetwork : WebAuthenticationOptions.None;

            try
            {
                if (ssoMode)
                {
                    webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(options, authorizationUri).AsTask().ConfigureAwait(false);
                }
                else
                {
                    webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(options, authorizationUri, redirectUri).AsTask().ConfigureAwait(false);
                }
            }

            catch (Exception ex)
            {
                PlatformPlugin.Logger.Error(callState, ex);
                throw new MsalException(MsalError.AuthenticationUiFailed, ex);
            }

            AuthorizationResult result = ProcessAuthorizationResult(webAuthenticationResult, callState);

            return(result);
        }
Example #6
0
 public async Task <WebAuthenticationResult> AuthenticateAsync(
     WebAuthenticationOptions options,
     Uri requestUri,
     Uri callbackUri,
     CancellationToken ct)
 {
     throw new NotImplementedException();
 }
 public async Task <WebAuthenticationResult> AuthenticateAsync(
     WebAuthenticationOptions options,
     Uri requestUri,
     Uri callbackUri,
     CancellationToken ct)
 {
     return(await this.AuthenticateAsyncCore(options, requestUri, callbackUri, ct));
 }
Example #8
0
        public static async Task <WebAuthenticationResult> AuthenticateAsync(WebAuthenticationOptions options, Uri requestUri, Uri callbackUri)
        {
            if (options != WebAuthenticationOptions.None)
            {
                throw new ArgumentException("WebAuthenticationBroker currently only supports WebAuthenticationOptions.None", "options");
            }

            redirectUri = callbackUri;
            dialog      = new ContentDialog();

            var grid = new Grid();

            grid.RowDefinitions.Add(new RowDefinition()
            {
                Height = Windows.UI.Xaml.GridLength.Auto
            });
            grid.RowDefinitions.Add(new RowDefinition()
            {
                Height = new Windows.UI.Xaml.GridLength(1, Windows.UI.Xaml.GridUnitType.Star)
            });

            var label = new TextBlock();

            label.Text = "Connecting to GitHub";
            label.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Left;
            label.Margin = new Windows.UI.Xaml.Thickness(0);
            grid.Children.Add(label);

            var closeButton = new Button();

            closeButton.Content             = "";
            closeButton.FontFamily          = new FontFamily("Segoe UI Symbol");
            closeButton.BorderBrush         = new SolidColorBrush(Windows.UI.Color.FromArgb(0, 0, 0, 0));
            closeButton.Background          = new SolidColorBrush(Windows.UI.Color.FromArgb(0, 0, 0, 0));
            closeButton.Margin              = new Windows.UI.Xaml.Thickness(0);
            closeButton.HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Right;
            closeButton.Click += (s, e) => { dialog.Hide(); };
            grid.Children.Add(closeButton);

            var webView = new WebView(WebViewExecutionMode.SameThread)
            {
                Source = requestUri
            };

            webView.AllowFocusOnInteraction = true;
            webView.SetValue(Grid.RowProperty, 1);
            webView.NavigationStarting += WebView_NavigationStarting;
            webView.NavigationFailed   += WebView_NavigationFailed;
            webView.MinWidth            = 480;
            webView.MinHeight           = 600;
            grid.Children.Add(webView);

            dialog.Content   = grid;
            dialog.GotFocus += (s, e) => { webView.Focus(Windows.UI.Xaml.FocusState.Programmatic); };
            var res = await dialog.ShowAsync();

            return(new WebAuthenticationResult(code, errorCode, errorCode > 0 ? WebAuthenticationStatus.ErrorHttp : string.IsNullOrEmpty(code) ? WebAuthenticationStatus.UserCancel : WebAuthenticationStatus.Success));
        }
        /// <summary>
        /// Mimics the WebAuthenticationBroker's AuthenticateAsync method.
        /// </summary>
        public static Task<WebAuthenticationResult> AuthenticateAsync(WebAuthenticationOptions options, Uri startUri, Uri endUri)
        {
            if (options != WebAuthenticationOptions.None)
            {
                throw new NotImplementedException("This method does not support authentication options other than 'None'.");
            }

            bool delegateToUI = false;
            PhoneApplicationFrame rootFrame = null;

            // Trying to do this in current thread. If not possible, try do to on UI thread.
            try
            {
                rootFrame = Application.Current.RootVisual as PhoneApplicationFrame;

                if (rootFrame == null)
                {
                    throw new InvalidOperationException();
                }
            }
            catch (InvalidOperationException)
            {
                delegateToUI = true;
            }

            WebAuthenticationBroker.StartUri = startUri;
            WebAuthenticationBroker.EndUri = endUri;
            WebAuthenticationBroker.AuthenticationInProgress = true;

            // Navigate to the login page.
            if (!delegateToUI)
            {

                rootFrame.Navigate(new Uri("/Facebook.Client;component/loginpage.xaml?systemtray=" + SystemTrayIsVisible.ToString(), UriKind.Relative));
            }
            else
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    rootFrame = Application.Current.RootVisual as PhoneApplicationFrame;

                    if (rootFrame == null)
                    {
                        return;
                    }

                    rootFrame.Navigate(new Uri("/Facebook.Client;component/loginpage.xaml?systemtray=" + SystemTrayIsVisible.ToString(), UriKind.Relative));
                });
            }

            Task<WebAuthenticationResult> task = Task<WebAuthenticationResult>.Factory.StartNew(() =>
            {
                authenticateFinishedEvent.WaitOne();
                return new WebAuthenticationResult(responseData, responseStatus, responseErrorDetail);
            });

            return task;
        }
Example #10
0
        public async Task <AuthorizationResult> AcquireAuthorizationAsync(Uri authorizationUri, Uri redirectUri, CallState callState)
        {
            bool ssoMode = ReferenceEquals(redirectUri, Constant.SsoPlaceHolderUri);

            if (this.promptBehavior == PromptBehavior.Never && !ssoMode && redirectUri.Scheme != Constant.MsAppScheme)
            {
                throw new ArgumentException(AdalErrorMessageEx.RedirectUriUnsupportedWithPromptBehaviorNever, "redirectUri");
            }

            WebAuthenticationResult webAuthenticationResult;

            WebAuthenticationOptions options = (this.useCorporateNetwork &&
                                                (ssoMode || redirectUri.Scheme == Constant.MsAppScheme))
                ? WebAuthenticationOptions.UseCorporateNetwork
                : WebAuthenticationOptions.None;

            if (this.promptBehavior == PromptBehavior.Never)
            {
                options |= WebAuthenticationOptions.SilentMode;
            }

            try
            {
                if (ssoMode)
                {
                    webAuthenticationResult =
                        await
                        WebAuthenticationBroker.AuthenticateAsync(options, authorizationUri)
                        .AsTask()
                        .ConfigureAwait(false);
                }
                else
                {
                    webAuthenticationResult =
                        await
                        WebAuthenticationBroker.AuthenticateAsync(options, authorizationUri, redirectUri)
                        .AsTask()
                        .ConfigureAwait(false);
                }
            }
            catch (FileNotFoundException ex)
            {
                throw new AdalException(AdalError.AuthenticationUiFailed, ex);
            }
            catch (Exception ex)
            {
                if (this.promptBehavior == PromptBehavior.Never)
                {
                    throw new AdalException(AdalError.UserInteractionRequired, ex);
                }

                throw new AdalException(AdalError.AuthenticationUiFailed, ex);
            }

            AuthorizationResult result = ProcessAuthorizationResult(webAuthenticationResult, callState);

            return(result);
        }
        /// <summary>
        /// Mimics the WebAuthenticationBroker's AuthenticateAsync method.
        /// </summary>
        public static Task <WebAuthenticationResult> AuthenticateAsync(WebAuthenticationOptions options, Uri startUri, Uri endUri)
        {
            if (options != WebAuthenticationOptions.None)
            {
                throw new NotImplementedException("This method does not support authentication options other than 'None'.");
            }

            bool delegateToUI = false;
            PhoneApplicationFrame rootFrame = null;

            // Trying to do this in current thread. If not possible, try do to on UI thread.
            try
            {
                rootFrame = Application.Current.RootVisual as PhoneApplicationFrame;

                if (rootFrame == null)
                {
                    throw new InvalidOperationException();
                }
            }
            catch (InvalidOperationException)
            {
                delegateToUI = true;
            }

            WebAuthenticationBroker.StartUri = startUri;
            WebAuthenticationBroker.EndUri   = endUri;
            WebAuthenticationBroker.AuthenticationInProgress = true;

            // Navigate to the login page.
            if (!delegateToUI)
            {
                rootFrame.Navigate(new Uri("/Facebook.Client;component/loginpage.xaml", UriKind.Relative));
            }
            else
            {
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    rootFrame = Application.Current.RootVisual as PhoneApplicationFrame;

                    if (rootFrame == null)
                    {
                        return;
                    }

                    rootFrame.Navigate(new Uri("/Facebook.Client;component/loginpage.xaml", UriKind.Relative));
                });
            }

            Task <WebAuthenticationResult> task = Task <WebAuthenticationResult> .Factory.StartNew(() =>
            {
                authenticateFinishedEvent.WaitOne();
                return(new WebAuthenticationResult(responseData, responseStatus, responseErrorDetail));
            });

            return(task);
        }
        public static IAsyncOperation <WebAuthenticationResult> AuthenticateAsync(WebAuthenticationOptions options, Uri requestUri, Uri callbackUri)
        {
            Task <WebAuthenticationResult> Builder(CancellationToken ct)
            {
                return(_authenticationBrokerProvider.AuthenticateAsync(options, requestUri, callbackUri, ct));
            }

            return(AsyncOperation.FromTask(Builder));
        }
Example #13
0
 /// <summary>
 ///     Constructor for LoginOptions
 /// </summary>
 /// <param name="loginUrl"></param>
 /// <param name="clientId"></param>
 /// <param name="callbackUrl"></param>
 /// <param name="scopes"></param>
 public LoginOptions(string loginUrl, string clientId, string callbackUrl, string displayType, string[] scopes, WebAuthenticationOptions brokerOptions, bool useTwoParamAuthAsyncMethod)
 {
     LoginUrl      = loginUrl;
     ClientId      = clientId;
     CallbackUrl   = callbackUrl;
     Scopes        = scopes;
     DisplayType   = displayType;
     BrokerOptions = brokerOptions;
     UseTwoParamAuthAsyncMethod = useTwoParamAuthAsyncMethod;
 }
        public async Task <AuthorizationResult> AuthenticateAsync(Uri authorizationUri, Uri redirectUri, CallState callState)
        {
            WebAuthenticationResult webAuthenticationResult;

            if (redirectUri.AbsoluteUri == WebAuthenticationBroker.GetCurrentApplicationCallbackUri().AbsoluteUri)
            {
                WebAuthenticationOptions options = this.useCorporateNetwork ? WebAuthenticationOptions.UseCorporateNetwork : WebAuthenticationOptions.None;

                if (this.promptBehavior == PromptBehavior.Never)
                {
                    // SSO Mode
                    options |= WebAuthenticationOptions.SilentMode;
                }

                try
                {
                    webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(options, authorizationUri);
                }
                catch (FileNotFoundException ex)
                {
                    throw new AdalException(AdalError.AuthenticationUiFailed, ex);
                }
                catch (Exception ex)
                {
                    if (this.promptBehavior == PromptBehavior.Never)
                    {
                        throw new AdalException(AdalError.UserInteractionRequired, ex);
                    }

                    throw;
                }
            }
            else if (this.promptBehavior == PromptBehavior.Never)
            {
                throw new ArgumentException(AdalErrorMessage.RedirectUriUnsupportedWithPromptBehaviorNever, "redirectUri");
            }
            else if (redirectUri.Scheme == "ms-app")
            {
                throw new ArgumentException(AdalErrorMessage.RedirectUriAppIdMismatch, "redirectUri");
            }
            else
            {
                try
                {
                    // Non-SSO Mode
                    webAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, authorizationUri, redirectUri);
                }
                catch (FileNotFoundException ex)
                {
                    throw new AdalException(AdalError.AuthenticationUiFailed, ex);
                }
            }

            return(ProcessAuthorizationResult(webAuthenticationResult, callState));
        }
Example #15
0
        public async Task <AuthorizationResult> AcquireAuthorizationAsync(
            Uri authorizationUri,
            Uri redirectUri,
            RequestContext requestContext,
            CancellationToken cancellationToken)
        {
            bool ssoMode = string.Equals(redirectUri.OriginalString, Constants.UapWEBRedirectUri, StringComparison.OrdinalIgnoreCase);

            WebAuthenticationResult  webAuthenticationResult;
            WebAuthenticationOptions options = (useCorporateNetwork &&
                                                (ssoMode || redirectUri.Scheme == Constants.MsAppScheme))
                ? WebAuthenticationOptions.UseCorporateNetwork
                : WebAuthenticationOptions.None;

            ThrowOnNetworkDown();
            if (silentMode)
            {
                options |= WebAuthenticationOptions.SilentMode;
            }

            try
            {
                webAuthenticationResult = await CoreApplication.MainView.CoreWindow.Dispatcher.RunTaskAsync(
                    async() =>
                {
                    if (ssoMode)
                    {
                        return(await
                               WebAuthenticationBroker.AuthenticateAsync(options, authorizationUri)
                               .AsTask()
                               .ConfigureAwait(false));
                    }
                    else
                    {
                        return(await WebAuthenticationBroker
                               .AuthenticateAsync(options, authorizationUri, redirectUri)
                               .AsTask()
                               .ConfigureAwait(false));
                    }
                })
                                          .ConfigureAwait(false);
            }

            catch (Exception ex)
            {
                requestContext.Logger.ErrorPii(ex);
                throw new MsalException(MsalError.AuthenticationUiFailedError, "WAB authentication failed",
                                        ex);
            }

            AuthorizationResult result = ProcessAuthorizationResult(webAuthenticationResult, requestContext);

            return(result);
        }
        protected override async Task LaunchBrowserCore(
            WebAuthenticationOptions options,
            Uri requestUri,
            Uri callbackUri,
            CancellationToken ct)
        {
            var builder = new CustomTabsIntent.Builder();
            var intent  = builder.Build();

            intent.LaunchUrl(
                ContextHelper.Current,
                Android.Net.Uri.Parse(requestUri.OriginalString));
        }
Example #17
0
        public async Task <AuthorizationResult> AcquireAuthorizationAsync(Uri authorizationUri, Uri redirectUri,
                                                                          RequestContext requestContext)
        {
            bool ssoMode = ReferenceEquals(redirectUri, Constants.SsoPlaceHolderUri);

            WebAuthenticationResult  webAuthenticationResult;
            WebAuthenticationOptions options = (useCorporateNetwork &&
                                                (ssoMode || redirectUri.Scheme == Constants.MsAppScheme))
                ? WebAuthenticationOptions.UseCorporateNetwork
                : WebAuthenticationOptions.None;

            ThrowOnNetworkDown();
            if (silentMode)
            {
                options |= WebAuthenticationOptions.SilentMode;
            }

            try
            {
                webAuthenticationResult = await CoreApplication.MainView.CoreWindow.Dispatcher.RunTaskAsync(
                    async() =>
                {
                    if (ssoMode)
                    {
                        return(await
                               WebAuthenticationBroker.AuthenticateAsync(options, authorizationUri)
                               .AsTask()
                               .ConfigureAwait(false));
                    }
                    else
                    {
                        return(await WebAuthenticationBroker
                               .AuthenticateAsync(options, authorizationUri, redirectUri)
                               .AsTask()
                               .ConfigureAwait(false));
                    }
                })
                                          .ConfigureAwait(false);
            }

            catch (Exception ex)
            {
                requestContext.Logger.Error(ex);
                throw new MsalException(MsalClientException.AuthenticationUiFailedError, "WAB authentication failed",
                                        ex);
            }

            AuthorizationResult result = ProcessAuthorizationResult(webAuthenticationResult, requestContext);

            return(result);
        }
        protected virtual async Task <WebAuthenticationResult> AuthenticateAsyncCore(
            WebAuthenticationOptions options,
            Uri requestUri,
            Uri callbackUri,
            CancellationToken ct)
        {
            // options are ignored for now

            // TODO: support ct

            var    urlNavigate = WebAssemblyRuntime.EscapeJs(requestUri.OriginalString);
            var    urlRedirect = WebAssemblyRuntime.EscapeJs(callbackUri.OriginalString);
            string js;

            var timeout = ((long)Timeout.TotalMilliseconds).ToString();

            var useIframe =
                options.HasFlag(WebAuthenticationOptions.SilentMode) ||
                !string.IsNullOrEmpty(WinRTFeatureConfiguration.WebAuthenticationBroker.IFrameHtmlId);

            if (useIframe)
            {
                var iframeId = WinRTFeatureConfiguration.WebAuthenticationBroker.IFrameHtmlId;
                js =
                    $@"Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateUsingIframe(""{iframeId}"", ""{urlNavigate}"", ""{urlRedirect}"", {timeout});";
            }
            else
            {
                var title = WebAssemblyRuntime.EscapeJs(WinRTFeatureConfiguration.WebAuthenticationBroker.WindowTitle ??
                                                        "Sign In");

                var windowWidth  = WinRTFeatureConfiguration.WebAuthenticationBroker.WindowWidth;
                var windowHeight = WinRTFeatureConfiguration.WebAuthenticationBroker.WindowHeight;
                js =
                    $@"Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateUsingWindow(""{urlNavigate}"", ""{urlRedirect}"", ""{title}"", {windowWidth}, {windowHeight}, {timeout});";
            }

            try
            {
                var results = (await WebAssemblyRuntime.InvokeAsync(js)).Split(new[] { '|' }, 2);

                return(results[0] switch
                {
                    "success" => new WebAuthenticationResult(results[1], 0, WebAuthenticationStatus.Success),
                    "cancel" => new WebAuthenticationResult(null, 0, WebAuthenticationStatus.UserCancel),
                    "timeout" => new WebAuthenticationResult(null, 0, WebAuthenticationStatus.UserCancel),
                    _ => new WebAuthenticationResult(null, 0, WebAuthenticationStatus.ErrorHttp)
                });
            }
Example #19
0
        public async Task <AuthorizationResult> AcquireAuthorizationAsync(
            Uri authorizationUri,
            Uri redirectUri,
            RequestContext requestContext,
            CancellationToken cancellationToken)
        {
            bool ssoMode = string.Equals(redirectUri.OriginalString, Constants.UapWEBRedirectUri, StringComparison.OrdinalIgnoreCase);

            WebAuthenticationResult  webAuthenticationResult;
            WebAuthenticationOptions options = (_useCorporateNetwork &&
                                                (ssoMode || redirectUri.Scheme == Constants.MsAppScheme))
                ? WebAuthenticationOptions.UseCorporateNetwork
                : WebAuthenticationOptions.None;

            if (_silentMode)
            {
                options |= WebAuthenticationOptions.SilentMode;
            }

            try
            {
                webAuthenticationResult = await RetryOperationHelper.ExecuteWithRetryAsync(
                    () => InvokeWABOnMainThreadAsync(authorizationUri, redirectUri, ssoMode, options),
                    WABRetryAttempts,
                    onAttemptFailed : (attemptNumber, exception) =>
                {
                    _requestContext.Logger.Warning($"Attempt {attemptNumber} to call WAB failed");
                    _requestContext.Logger.WarningPii(exception);
                })
                                          .ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                requestContext.Logger.ErrorPii(ex);
                throw new MsalException(
                          MsalError.AuthenticationUiFailedError,
                          "Web Authentication Broker (WAB) authentication failed. To collect WAB logs, please follow https://aka.ms/msal-net-wab-logs",
                          ex);
            }

            AuthorizationResult result = ProcessAuthorizationResult(webAuthenticationResult);

            return(result);
        }
Example #20
0
        /// <summary>
        /// Mimics the WebviewAuthentication's AuthenticateAsync method.
        /// </summary>
        public static void AuthenticateAsync(WebAuthenticationOptions options, Uri startUri, Uri endUri)
        {
            if (options != WebAuthenticationOptions.None)
            {
                throw new NotImplementedException("This method does not support authentication options other than 'None'.");
            }
            Popup dialogPopup = new Popup();

            var webDialog = new WebDialogUserControl();

            webDialog.ParentControlPopup = dialogPopup;
            dialogPopup.Child            = webDialog;

#if WP8 || WINDOWS_PHONE
            // Set where the popup will show up on the screen.
            dialogPopup.VerticalOffset   = 40;
            dialogPopup.HorizontalOffset = 0;
#endif

#if WP8
            dialogPopup.Height = Application.Current.Host.Content.ActualHeight - 40;
            dialogPopup.Width  = Application.Current.Host.Content.ActualWidth;
#endif

#if WINDOWS_PHONE
            dialogPopup.Height = Window.Current.Bounds.Height - 40;
            dialogPopup.Width  = Window.Current.Bounds.Width;
#endif

#if WINDOWS
            dialogPopup.Height = Window.Current.Bounds.Height;
            dialogPopup.Width  = Window.Current.Bounds.Width;
#endif


            webDialog.Height = dialogPopup.Height;
            webDialog.Width  = dialogPopup.Width;

            webDialog.LoginViaWebview(startUri);

            // Open the popup.
            dialogPopup.IsOpen = true;
        }
        private async Task <GoogleSession> PromptOAuthDialog(string clientId, WebAuthenticationOptions options)
        {
            var startUri = GetLoginUrl(clientId);
            var result   = await WebAuthenticationBroker.AuthenticateAsync("/GoogleOAuth;component/LoginPage.xaml", options, startUri);

            if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
            {
                throw new InvalidOperationException();
            }
            if (result.ResponseStatus == WebAuthenticationStatus.UserCancel)
            {
                throw new InvalidOperationException();
            }
            if (string.IsNullOrEmpty(result.ResponseData))
            {
                throw new InvalidCastException();
            }
            return(await GetToken(result.ResponseData));
        }
Example #22
0
        /// <summary>
        /// Starts the asynchronous authentication operation with three inputs.
        /// You can call this method multiple times in a single application or across multiple applications at the same time.
        /// </summary>
        /// <param name="options">The options for the authentication operation.</param>
        /// <param name="requestUri">The starting URI of the web service. This URI must be a secure address of https://.</param>
        /// <param name="callbackUri">The callback URI that indicates the completion of the web authentication.
        /// The broker matches this URI against every URI that it is about to navigate to.
        /// The broker never navigates to this URI, instead the broker returns the control back to the application when the user clicks a link or a web server redirection is made.</param>
        /// <returns>The way to query the status and get the results of the authentication operation.
        /// If you are getting an invalid parameter error, the most common cause is that you are not using HTTPS for the requestUri parameter.</returns>
        /// <remarks>When this method is used, no session state or persisted cookies are retained across multiple calls from the same or different apps.
        /// This method must be called on the UI thread.</remarks>
        public static async Task <WebAuthenticationResult> AuthenticateAsync(WebAuthenticationOptions options, Uri requestUri, Uri callbackUri)
        {
#if WINDOWS_UWP || WINDOWS_APP
            return(await Windows.Security.Authentication.Web.WebAuthenticationBroker.AuthenticateAsync((Windows.Security.Authentication.Web.WebAuthenticationOptions)((int)options), requestUri, callbackUri));
#elif WINDOWS_PHONE_APP
            var method = type10.GetRuntimeMethod("AuthenticateAsync", new Type[] { typeof(Windows.Security.Authentication.Web.WebAuthenticationOptions), typeof(Uri), typeof(Uri) });
            if (method != null)
            {
                IAsyncOperation <Windows.Security.Authentication.Web.WebAuthenticationResult> op = (IAsyncOperation <Windows.Security.Authentication.Web.WebAuthenticationResult>)method.Invoke(null, new object[] { (Windows.Security.Authentication.Web.WebAuthenticationOptions)((int)options), requestUri, callbackUri });
                var result = await op;
                return(result);
            }
            else
            {
                throw new PlatformNotSupportedException();
            }
#elif WINDOWS_PHONE
            Result = new WebAuthenticationResult(null, 0, WebAuthenticationStatus.UserCancel);

            Frame f = Application.Current.RootVisual as Frame;
            if (f != null)
            {
                if (!f.Dispatcher.CheckAccess())
                {
                    throw new InvalidOperationException("Must be called on UI thread.");
                }

                Handle = new AutoResetEvent(false);

                Uri navUri = new Uri(string.Format("/InTheHand;component/Security/Authentication/Web/WebAuthenticationPage.xaml?uri={0}&returnUri={1}", Uri.EscapeDataString(requestUri.ToString()), Uri.EscapeDataString(callbackUri.ToString())), UriKind.Relative);

                f.Navigate(navUri);

                await Task.Run(new Func <Task>(WaitResponse));
            }

            return(Result);
#else
            throw new PlatformNotSupportedException();
#endif
        }
        /// <summary>
        /// Starts the asynchronous authentication operation with two inputs.
        /// You can call this method multiple times in a single application or across multiple applications at the same time. 
        /// </summary>
        /// <param name="options">The options for the authentication operation.</param>
        /// <param name="requestUri">The starting URI of the web service. This URI must be a secure address of https://.</param>
        /// <returns>The way to query the status and get the results of the authentication operation.
        /// If you are getting an invalid parameter error, the most common cause is that you are not using HTTPS for the requestUri parameter.</returns>
        /// <remarks>There is no explicit callbackUri parameter in this method.
        /// The application's default URI is used internally as the terminator.
        /// For more information, see <see cref="GetCurrentApplicationCallbackUri"/>.
        /// This method must be called on the UI thread.
        /// When this method is used, session state or persisted cookies are retained across multiple calls from the same or different apps.</remarks>
        public static async Task<WebAuthenticationResult> AuthenticateAsync(WebAuthenticationOptions options, Uri requestUri)
        {
#if WINDOWS_UWP || WINDOWS_APP
            return await Windows.Security.Authentication.Web.WebAuthenticationBroker.AuthenticateAsync((Windows.Security.Authentication.Web.WebAuthenticationOptions)((int)options), requestUri);
#elif WINDOWS_PHONE_APP
            var method = type10.GetRuntimeMethod("AuthenticateAsync", new Type[] { typeof(Windows.Security.Authentication.Web.WebAuthenticationOptions), typeof(Uri) });
            if(method != null)
            {
                IAsyncOperation<Windows.Security.Authentication.Web.WebAuthenticationResult> op = (IAsyncOperation<Windows.Security.Authentication.Web.WebAuthenticationResult>)method.Invoke(null, new object[] { (Windows.Security.Authentication.Web.WebAuthenticationOptions)((int)options), requestUri });
                return await op;
            }
            else
            {
                throw new PlatformNotSupportedException();
            }
#elif WINDOWS_PHONE
            return await AuthenticateAsync(options, requestUri, GetCurrentApplicationCallbackUri());
#else
            throw new PlatformNotSupportedException();
#endif
        }
Example #24
0
        private static Task <WebAuthenticationResult> BrokerSigninAsync(
            BrowserOptions options,
            string brokerAbsolutePath,
            WebAuthenticationOptions wabOptions,
            CancellationToken cancellationToken)
        {
            IAsyncOperation <WebAuthenticationResult> result;
            var requestUri = new Uri(options.StartUrl);

            if (String.Equals(options.EndUrl, brokerAbsolutePath, StringComparison.Ordinal))
            {
                result = WebAuthenticationBroker.AuthenticateAsync(wabOptions, requestUri);
            }
            else
            {
                var callbackUri = new Uri(options.EndUrl);
                result = WebAuthenticationBroker.AuthenticateAsync(wabOptions, requestUri, callbackUri);
            }

            return(result.AsTask(cancellationToken));
        }
Example #25
0
        /// <summary>
        /// Starts the asynchronous authentication operation with two inputs.
        /// You can call this method multiple times in a single application or across multiple applications at the same time.
        /// </summary>
        /// <param name="options">The options for the authentication operation.</param>
        /// <param name="requestUri">The starting URI of the web service. This URI must be a secure address of https://.</param>
        /// <returns>The way to query the status and get the results of the authentication operation.
        /// If you are getting an invalid parameter error, the most common cause is that you are not using HTTPS for the requestUri parameter.</returns>
        /// <remarks>There is no explicit callbackUri parameter in this method.
        /// The application's default URI is used internally as the terminator.
        /// For more information, see <see cref="GetCurrentApplicationCallbackUri"/>.
        /// This method must be called on the UI thread.
        /// When this method is used, session state or persisted cookies are retained across multiple calls from the same or different apps.</remarks>
        public static async Task <WebAuthenticationResult> AuthenticateAsync(WebAuthenticationOptions options, Uri requestUri)
        {
#if WINDOWS_UWP || WINDOWS_APP
            return(await Windows.Security.Authentication.Web.WebAuthenticationBroker.AuthenticateAsync((Windows.Security.Authentication.Web.WebAuthenticationOptions)((int)options), requestUri));
#elif WINDOWS_PHONE_APP
            var method = type10.GetRuntimeMethod("AuthenticateAsync", new Type[] { typeof(Windows.Security.Authentication.Web.WebAuthenticationOptions), typeof(Uri) });
            if (method != null)
            {
                IAsyncOperation <Windows.Security.Authentication.Web.WebAuthenticationResult> op = (IAsyncOperation <Windows.Security.Authentication.Web.WebAuthenticationResult>)method.Invoke(null, new object[] { (Windows.Security.Authentication.Web.WebAuthenticationOptions)((int)options), requestUri });
                return(await op);
            }
            else
            {
                throw new PlatformNotSupportedException();
            }
#elif WINDOWS_PHONE
            return(await AuthenticateAsync(options, requestUri, GetCurrentApplicationCallbackUri()));
#else
            throw new PlatformNotSupportedException();
#endif
        }
 /// <summary>
 /// Mimics the WebAuthenticationBroker's AuthenticateAsync method.
 /// </summary>
 public static async Task<WebAuthenticationResult> AuthenticateAsync(WebAuthenticationOptions options, Uri startUri, Uri endUri)
 {
     if (options != WebAuthenticationOptions.None)
     {
         throw new NotImplementedException("This method does not support authentication options other than 'None'.");
     }
     PhoneApplicationFrame phoneApplicationFrame = Application.Current.RootVisual as PhoneApplicationFrame;
     if (phoneApplicationFrame == null)
     {
         throw new InvalidOperationException();
     }
     string loginPageUri = "/WebAuthenticationBroker;component/loginpage.xaml" 
         + "?startUri=" + Uri.EscapeDataString(startUri.AbsoluteUri)
         + "&endUri=" + Uri.EscapeDataString(endUri.AbsoluteUri);
     if (LoginPage.WebAuthenticationResultSource != null)
     {
         LoginPage.WebAuthenticationResultSource.TrySetCanceled();
     }
     LoginPage.WebAuthenticationResultSource = new TaskCompletionSource<WebAuthenticationResult>();
     phoneApplicationFrame.Navigate(new Uri(loginPageUri, UriKind.Relative));
     return await LoginPage.WebAuthenticationResultSource.Task;
 }
        public static async Task <ExternalLoginResult> GetExternalAccessTokenAsync(string externalLoginUri, bool silentMode = false)
        {
            Uri authorizationRequestUri = new Uri(new Uri(ClientFactory.BaseAddress), externalLoginUri);
            WebAuthenticationOptions webAuthenticationOptions = silentMode ? WebAuthenticationOptions.SilentMode : WebAuthenticationOptions.None;
            WebAuthenticationResult  authenticationResult     = await WebAuthenticationBroker.AuthenticateAsync(webAuthenticationOptions, authorizationRequestUri);

            ExternalLoginResult loginExternalResult = new ExternalLoginResult()
            {
                WebAuthenticationResult = authenticationResult
            };

            if (authenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
            {
                Uri    responseDataUri = new Uri(authenticationResult.ResponseData);
                string fragment        = responseDataUri.Fragment;
                if (fragment != null && fragment.Length > 0)
                {
                    WwwFormUrlDecoder wwwFormUrlDecoder = new WwwFormUrlDecoder(fragment.Substring(1));
                    loginExternalResult.AccessToken = wwwFormUrlDecoder.GetFirstValueByName("access_token");
                }
            }
            return(loginExternalResult);
        }
Example #28
0
        /// <summary>
        /// Mimics the WebAuthenticationBroker's AuthenticateAsync method.
        /// </summary>
        public static async Task <WebAuthenticationResult> AuthenticateAsync(WebAuthenticationOptions options, Uri startUri, Uri endUri)
        {
            if (options != WebAuthenticationOptions.None)
            {
                throw new NotImplementedException("This method does not support authentication options other than 'None'.");
            }
            PhoneApplicationFrame phoneApplicationFrame = Application.Current.RootVisual as PhoneApplicationFrame;

            if (phoneApplicationFrame == null)
            {
                throw new InvalidOperationException();
            }
            string loginPageUri = "/WebAuthenticationBroker;component/loginpage.xaml"
                                  + "?startUri=" + Uri.EscapeDataString(startUri.AbsoluteUri)
                                  + "&endUri=" + Uri.EscapeDataString(endUri.AbsoluteUri);

            if (LoginPage.WebAuthenticationResultSource != null)
            {
                LoginPage.WebAuthenticationResultSource.TrySetCanceled();
            }
            LoginPage.WebAuthenticationResultSource = new TaskCompletionSource <WebAuthenticationResult>();
            phoneApplicationFrame.Navigate(new Uri(loginPageUri, UriKind.Relative));
            return(await LoginPage.WebAuthenticationResultSource.Task);
        }
 private async Task<WebAuthenticationResult> AuthenticateAsync(Uri requestUri, Uri callbackUri, WebAuthenticationOptions authenticationOptions)
 {
     return callbackUri == null
         ? await WebAuthenticationBroker.AuthenticateAsync(authenticationOptions, requestUri)
         : await WebAuthenticationBroker.AuthenticateAsync(authenticationOptions, requestUri, callbackUri);
 }
        private async Task<FacebookOAuthResult> PromptOAuthDialog(string permissions, WebAuthenticationOptions options, FacebookLoginBehavior loginBehavior)
        {
#if !WINDOWS
            if (loginBehavior != FacebookLoginBehavior.LoginBehaviorWebViewOnly)
            {
                throw new NotImplementedException("Following login behavior is not supported on Windows Phone: " + loginBehavior.ToString());
            }
#endif
            // Use WebviewAuthentication to launch server side OAuth flow

            Uri startUri = await this.GetLoginUrl(permissions);
            Uri endUri = new Uri("https://www.facebook.com/connect/login_success.html");

            WebAuthenticationResult result = null;
#if WINDOWS
            if (loginBehavior == FacebookLoginBehavior.LoginBehaviorWebAuthenticationBroker)
            {
                result = await WebAuthenticationBroker.AuthenticateAsync(options, startUri, endUri);

                if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
                {
                    throw new HttpRequestException("An Http error happened. Error Code: " +
                                                   result.ResponseStatus.ToString());
                }
                else if (result.ResponseStatus == WebAuthenticationStatus.UserCancel)
                {
                    throw new FacebookOAuthException("Facebook.Client: User cancelled login in WebAuthBroker");
                }
            }
#endif
            var client = new FacebookClient();
            var authResult = client.ParseOAuthCallbackUrl(new Uri(result.ResponseData));
            return authResult;
        }
        public static Task <WebAuthenticationResult> AuthenticateAsync(string navigationPageUri, WebAuthenticationOptions options, Uri startUri)
        {
            if (options != WebAuthenticationOptions.None)
            {
                throw new NotImplementedException("This method does not support authentication options other than 'None'.");
            }
            var applicationFrame = Application.Current.RootVisual as PhoneApplicationFrame;

            if (applicationFrame == null)
            {
                throw new InvalidOperationException();
            }
            StartUri = startUri;
            AuthenticationInProgress = true;
            applicationFrame.Navigate(new Uri(navigationPageUri, UriKind.Relative));
            return(Task <WebAuthenticationResult> .Factory.StartNew(() =>
            {
                AuthenticateFinishedEvent.WaitOne();
                return new WebAuthenticationResult(_responseData, _responseStatus, _responseErrorDetail);
            }));
        }
        /// <summary>
        /// Mimics the WebAuthenticationBroker's AuthenticateAsync method.
        /// </summary>
        public static Task<WebAuthenticationResult> AuthenticateAsync(WebAuthenticationOptions options, Uri startUri, Uri endUri)
        {
            if (options != WebAuthenticationOptions.None)
            {
                throw new NotImplementedException("This method does not support authentication options other than 'None'.");
            }

            PhoneApplicationFrame rootFrame = Application.Current.RootVisual as PhoneApplicationFrame;

            if (rootFrame == null)
            {
                throw new InvalidOperationException();
            }

            WebAuthenticationBroker.StartUri = startUri;
            WebAuthenticationBroker.EndUri = endUri;
            WebAuthenticationBroker.AuthenticationInProgress = true;

            // Navigate to the login page.
            rootFrame.Navigate(new Uri("/Facebook.Client;component/loginpage.xaml", UriKind.Relative));

            Task<WebAuthenticationResult> task = Task<WebAuthenticationResult>.Factory.StartNew(() =>
            {
                authenticateFinishedEvent.WaitOne();
                return new WebAuthenticationResult(responseData, responseStatus, responseErrorDetail);
            });

            return task;
        }
        public static async Task <CustomWebAuthenticationResult> AuthenticateAsync(
            WebAuthenticationOptions options,
            Uri requestUri,
            Uri callbackUri,
            bool showUrl)
        {
            if (options != WebAuthenticationOptions.None)
            {
                throw new ArgumentException("WebAuthenticationBroker currently only supports WebAuthenticationOptions.None", "options");
            }

            redirectUri = callbackUri;
            dialog      = new ContentDialog();

            var grid = new Grid
            {
                VerticalAlignment = VerticalAlignment.Center
            };

            grid.RowDefinitions.Add(new RowDefinition()
            {
                Height = GridLength.Auto
            });
            grid.RowDefinitions.Add(new RowDefinition()
            {
                Height = new GridLength(0.1, GridUnitType.Star)
            });
            grid.RowDefinitions.Add(new RowDefinition()
            {
                Height = GridLength.Auto
            });
            grid.RowDefinitions.Add(new RowDefinition()
            {
                Height = new GridLength(1, GridUnitType.Star)
            });

            var label = new TextBlock
            {
                Text = "Connect to a service",
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment   = VerticalAlignment.Center,
                Margin = new Thickness(0)
            };

            grid.Children.Add(label);

            var closeButton = new Button
            {
                Content             = "",
                FontFamily          = new FontFamily("Segoe UI Symbol"),
                BorderBrush         = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)),
                Background          = new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)),
                Margin              = new Thickness(0),
                HorizontalAlignment = HorizontalAlignment.Right,
                VerticalAlignment   = VerticalAlignment.Center
            };

            closeButton.Click += (s, e) => { dialog.Hide(); };
            grid.Children.Add(closeButton);

            _address = new TextBox
            {
                Text         = string.Empty,
                Margin       = new Thickness(0, 5, 0, 5),
                IsReadOnly   = true,
                TextWrapping = TextWrapping.Wrap,
                FontSize     = 12,
            };
            _address.SetValue(Grid.RowProperty, 1);

            if (showUrl)
            {
                grid.Children.Add(_address);

                var splitter = new GridSplitter();
                splitter.SetValue(Grid.RowProperty, 2);
                splitter.Element = new TextBlock
                {
                    HorizontalAlignment = HorizontalAlignment.Center,
                    IsHitTestVisible    = false,
                    VerticalAlignment   = VerticalAlignment.Center,
                    Text       = "\uE76F",
                    Foreground = new SolidColorBrush(Colors.White),
                    FontFamily = new FontFamily("Segoe MDL2 Assets")
                };
                grid.Children.Add(splitter);
            }

            var webView = new WebView(WebViewExecutionMode.SameThread)
            {
                Source = requestUri
            };

            webView.NavigationStarting += WebView_NavigationStarting;
            webView.NavigationFailed   += WebView_NavigationFailed;
            webView.ContentLoading     += (sender, args) =>
            {
                _address.Text = args.Uri.ToString();
            };

            webView.MinWidth  = 460;
            webView.MinHeight = 600;

            var scrollViewer = new ScrollViewer
            {
                HorizontalAlignment = HorizontalAlignment.Stretch,
                Content             = webView
            };

            scrollViewer.SetValue(Grid.RowProperty, 3);

            grid.Children.Add(scrollViewer);
            dialog.Content = grid;

            //dialog.GotFocus += (s, e) => { webView.Focus(Windows.UI.Xaml.FocusState.Programmatic); };
            var res = await dialog.ShowAsync();

            return(new CustomWebAuthenticationResult(code, errorCode, errorCode > 0 ? CustomWebAuthenticationStatus.ErrorHttp : string.IsNullOrEmpty(code) ? CustomWebAuthenticationStatus.UserCancel : CustomWebAuthenticationStatus.Success));
        }
 private bool GetOption( WebAuthenticationOptions option )
 {
     return ( options & option ) == option;
 }
		/// <summary>
		/// Starts the asynchronous authentication operation with two inputs. You can call this method multiple times in a single application or across multiple applications at the same time.
		/// </summary>
		/// <param name="options">The options for the authentication operation.</param>
		/// <param name="requestUri">The starting URI of the web service. This URI must be a secure address of https://.</param>
		/// <returns>The way to query the status and get the results of the authentication operation. If you are getting an invalid parameter error, the most common cause is that you are not using HTTPS for the requestUri parameter.</returns>
		public static IAsyncOperation<WebAuthenticationResult> AuthenticateAsync(WebAuthenticationOptions options, Uri requestUri)
		{
			return AuthenticateAsync(options, requestUri, GetCurrentApplicationCallbackUri());
		}
		/// <summary>
		/// Starts the asynchronous authentication operation with three inputs. You can call this method multiple times in a single application or across multiple applications at the same time.
		/// </summary>
		/// <param name="options">The options for the authentication operation.</param>
		/// <param name="requestUri">The starting URI of the web service. This URI must be a secure address of https://.</param>
		/// <param name="callbackUri">The callback URI that indicates the completion of the web authentication. The broker matches this URI against every URI that it is about to navigate to. The broker never navigates to this URI, instead the broker returns the control back to the application when the user clicks a link or a web server redirection is made.</param>
		/// <returns>The way to query the status and get the results of the authentication operation. If you are getting an invalid parameter error, the most common cause is that you are not using HTTPS for the requestUri parameter.</returns>
		public static IAsyncOperation<WebAuthenticationResult> AuthenticateAsync(WebAuthenticationOptions options, Uri requestUri, Uri callbackUri)
		{
			var tcs = new TaskCompletionSource<WebAuthenticationResult>();

			if (options != WebAuthenticationOptions.None)
				throw new NotImplementedException();

			var t = new Thread((ThreadStart)delegate
			{
				var result = WebAuthenticationResult.UserCancel;

				// TODO: Create a Dialog/Window class.
				var backWin = new Form
				{
					BackColor = global::System.Drawing.Color.Black,
					Opacity = 0.55,
					WindowState = FormWindowState.Maximized,
					FormBorderStyle = FormBorderStyle.None,
					TopMost = true
				};

				var win = new Form
				{
					FormBorderStyle = FormBorderStyle.None,
					TopMost = true
				};

				bool ignoreWindowSizeChange = false;
				EventHandler winSizeChanged = delegate
				{
					if (ignoreWindowSizeChange)
						return;
					win.Top = (backWin.Height - win.Height) / 2;
					win.Left = backWin.Left;
				};

				win.SizeChanged += winSizeChanged;
				backWin.SizeChanged += delegate
				{
					ignoreWindowSizeChange = true;
					win.Width = backWin.Width;
					win.Height = backWin.Height - 230;
					ignoreWindowSizeChange = false;
					winSizeChanged(backWin, EventArgs.Empty);
				};

				var headerPanel = new Panel { Width = 566, Height = 80 };
				var bodyPanel = new Panel
				{
					Top = 80,
					BackColor = global::System.Drawing.Color.White,
				};

				var backButton = new BackButton
				{
					Location = new global::System.Drawing.Point(0, 35),
					TabStop = false
				};
				headerPanel.Controls.Add(backButton);
				backButton.Click += (s, e) => win.Close();

				var lbl = new Label
				{
					Location = new global::System.Drawing.Point(35, 30),
					Font = new global::System.Drawing.Font("Segoe UI", 19.5f),
					Text = WinRT.NET.Forms.Properties.Resources.AuthenticationBrokerTitle,
					AutoSize = true
				};
				headerPanel.Controls.Add(lbl);
				win.Controls.Add(headerPanel);
				win.Controls.Add(bodyPanel);

				var browser = new WebBrowser { Width = 566 };
				win.SizeChanged += delegate
				{
					bodyPanel.Width = win.Width;
					bodyPanel.Height = win.Height - bodyPanel.Top;
					browser.Height = win.Height - 80;
					browser.Left = (win.Width - browser.Width) / 2;
					headerPanel.Left = browser.Left;
				};

				browser.PreviewKeyDown += (sender, e) =>
				{
					if (e.KeyCode == Keys.Escape)
						win.DialogResult = DialogResult.Abort;
				};
				bodyPanel.Controls.Add(browser);
				win.Deactivate += (sender, e) =>
				{
					if (win.CanFocus)
						win.DialogResult = DialogResult.Abort;
				};

				browser.Navigated += (sender, e) =>
				{
					if (e.Url.GetLeftPart(UriPartial.Path).EndsWith(callbackUri.ToString()))
					{
						result = WebAuthenticationResult.FromResponseData(e.Url.ToString());
						win.DialogResult = DialogResult.OK;
					}
				};

				browser.Navigate(requestUri);

				backWin.Show();
				win.ShowDialog();
				backWin.Close();

				tcs.TrySetResult(result);
			});

			t.SetApartmentState(ApartmentState.STA);
			t.Start();

			return tcs.Task.AsAsyncOperation();
		}
        private static async Task<AdnWebAuthenticationResult> AuthenticateAsyncTask(
            WebAuthenticationOptions options,
            Uri startUri,
            Uri endUri)
        {
            TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();

            WebAuthenticationStatus responseStatus = WebAuthenticationStatus.Success;

            string responseData = "";

            Popup popUp = new Popup
            {
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment = VerticalAlignment.Stretch,

                Width = 800,
                Height = Window.Current.Bounds.Height
            };

            var webAuthView = new AdnWebAuthView
            {
                Width = Window.Current.Bounds.Width,
                Height = Window.Current.Bounds.Height
            };

            webAuthView.CancelledEvent += (s, e) =>
            {
                responseStatus = WebAuthenticationStatus.UserCancel;

                popUp.IsOpen = false;

                tcs.TrySetResult(1);
            };

            webAuthView.UriChangedEvent += (s, e) =>
            {
                if (e != null)
                {
                    if (e.Uri.AbsoluteUri.StartsWith(
                        endUri.AbsoluteUri,
                        StringComparison.OrdinalIgnoreCase))
                    {
                        responseStatus = WebAuthenticationStatus.Success;
                        responseData = e.Uri.AbsoluteUri;

                        popUp.IsOpen = false;

                        tcs.TrySetResult(1);
                    }
                }
            };

            webAuthView.NavFailedEvent += (s, e) =>
            {
                if (e.Uri.AbsoluteUri.StartsWith(
                    endUri.AbsoluteUri,
                    StringComparison.OrdinalIgnoreCase))
                {
                    responseStatus = WebAuthenticationStatus.Success;
                    responseData = e.Uri.AbsoluteUri;
                }
                else
                {
                    responseStatus = WebAuthenticationStatus.ErrorHttp;
                    responseData = e.Uri.AbsoluteUri;
                }

                popUp.IsOpen = false;

                tcs.TrySetResult(1);
            };

            popUp.Child = webAuthView;
            popUp.IsOpen = true;
            webAuthView.Navigate(startUri);

            await tcs.Task;

            return new AdnWebAuthenticationResult
            {
                ResponseStatus = responseStatus,
                ResponseData = responseData
            };
        }
 public static IAsyncOperation<AdnWebAuthenticationResult> AuthenticateAsync(
     WebAuthenticationOptions options,
     Uri startUri,
     Uri endUri)
 {
     return AuthenticateAsyncTask(options, startUri, endUri).AsAsyncOperation();
 }
        /// <summary>
        /// Mimics the WebviewAuthentication's AuthenticateAsync method.
        /// </summary>
        public static void AuthenticateAsync(WebAuthenticationOptions options, Uri startUri, Uri endUri)
        {
            if (options != WebAuthenticationOptions.None)
            {
                throw new NotImplementedException("This method does not support authentication options other than 'None'.");
            }
            Popup dialogPopup = new Popup();

            var webDialog = new WebDialogUserControl();

            webDialog.ParentControlPopup = dialogPopup;
            dialogPopup.Child = webDialog;

#if WP8 || WINDOWS_PHONE
            // Set where the popup will show up on the screen.
            dialogPopup.VerticalOffset = 40;
            dialogPopup.HorizontalOffset = 0;
#endif

#if WP8
            dialogPopup.Height = Application.Current.Host.Content.ActualHeight - 40;
            dialogPopup.Width = Application.Current.Host.Content.ActualWidth;
#endif

#if WINDOWS_PHONE
            dialogPopup.Height = Window.Current.Bounds.Height - 40;
            dialogPopup.Width = Window.Current.Bounds.Width;
#endif

#if WINDOWS
            dialogPopup.Height = Window.Current.Bounds.Height;
            dialogPopup.Width = Window.Current.Bounds.Width;
#endif


            webDialog.Height = dialogPopup.Height;
            webDialog.Width = dialogPopup.Width;

            webDialog.LoginViaWebview(startUri);

            // Open the popup.
            dialogPopup.IsOpen = true;
        }
        public async Task<WebAuthenticationResult> Authenticate(WebAuthenticationOptions webAuthenticationOptions, Uri url, Uri callback)
        {
            WebAuthenticationBroker.AuthenticateAndContinue(url, callback, null, webAuthenticationOptions);

            return null;
        }
Example #41
0
 private async Task <WebAuthenticationResult> AuthenticateAsync(Uri requestUri, Uri callbackUri, WebAuthenticationOptions authenticationOptions)
 {
     return(callbackUri == null
         ? await WebAuthenticationBroker.AuthenticateAsync(authenticationOptions, requestUri)
         : await WebAuthenticationBroker.AuthenticateAsync(authenticationOptions, requestUri, callbackUri));
 }
Example #42
0
 public static Task <WebAuthenticationResult> AuthenticateAsync(WebAuthenticationOptions options, Uri requestUri)
 {
     return(AuthenticateAsync(options, requestUri, Windows.Security.Authentication.Web.WebAuthenticationBroker.GetCurrentApplicationCallbackUri()));
 }
        /// <summary>
        /// Starts the asynchronous authentication operation with three inputs.
        /// You can call this method multiple times in a single application or across multiple applications at the same time. 
        /// </summary>
        /// <param name="options">The options for the authentication operation.</param>
        /// <param name="requestUri">The starting URI of the web service. This URI must be a secure address of https://.</param>
        /// <param name="callbackUri">The callback URI that indicates the completion of the web authentication.
        /// The broker matches this URI against every URI that it is about to navigate to.
        /// The broker never navigates to this URI, instead the broker returns the control back to the application when the user clicks a link or a web server redirection is made.</param>
        /// <returns>The way to query the status and get the results of the authentication operation.
        /// If you are getting an invalid parameter error, the most common cause is that you are not using HTTPS for the requestUri parameter.</returns>
        /// <remarks>When this method is used, no session state or persisted cookies are retained across multiple calls from the same or different apps.
        /// This method must be called on the UI thread.</remarks>
        public static async Task<WebAuthenticationResult> AuthenticateAsync(WebAuthenticationOptions options, Uri requestUri, Uri callbackUri)
        {
#if WINDOWS_UWP || WINDOWS_APP
            return await Windows.Security.Authentication.Web.WebAuthenticationBroker.AuthenticateAsync((Windows.Security.Authentication.Web.WebAuthenticationOptions)((int)options), requestUri, callbackUri);
#elif WINDOWS_PHONE_APP
            var method = type10.GetRuntimeMethod("AuthenticateAsync", new Type[] { typeof(Windows.Security.Authentication.Web.WebAuthenticationOptions), typeof(Uri), typeof(Uri) });
            if (method != null)
            {
                IAsyncOperation<Windows.Security.Authentication.Web.WebAuthenticationResult> op = (IAsyncOperation<Windows.Security.Authentication.Web.WebAuthenticationResult>)method.Invoke(null, new object[] { (Windows.Security.Authentication.Web.WebAuthenticationOptions)((int)options), requestUri, callbackUri });
                var result = await op;
                return result;
            }
            else
            {
                throw new PlatformNotSupportedException();
            }
#elif WINDOWS_PHONE
            Result = new WebAuthenticationResult(null, 0, WebAuthenticationStatus.UserCancel);

            Frame f = Application.Current.RootVisual as Frame;
            if (f != null)
            {
                if (!f.Dispatcher.CheckAccess())
                {
                    throw new InvalidOperationException("Must be called on UI thread.");
                }

                Handle = new AutoResetEvent(false);

                Uri navUri = new Uri(string.Format("/InTheHand;component/Security/Authentication/Web/WebAuthenticationPage.xaml?uri={0}&returnUri={1}", Uri.EscapeDataString(requestUri.ToString()), Uri.EscapeDataString(callbackUri.ToString())), UriKind.Relative);

                f.Navigate(navUri);
                
                await Task.Run(new Func<Task>(WaitResponse));
            }

            return Result;
#else
            throw new PlatformNotSupportedException();
#endif
        }
 public static Task <CustomWebAuthenticationResult> AuthenticateAsync(
     WebAuthenticationOptions options,
     Uri requestUri,
     bool showUrl)
 => AuthenticateAsync(options, requestUri, WebAuthenticationBroker.GetCurrentApplicationCallbackUri(), showUrl);
        private async Task<FacebookOAuthResult> PromptOAuthDialog(string permissions, WebAuthenticationOptions options)
        {
            // Use WebAuthenticationBroker to launch server side OAuth flow

            Uri startUri = this.GetLoginUrl(permissions);
            Uri endUri = new Uri("https://www.facebook.com/connect/login_success.html");

            var result = await WebAuthenticationBroker.AuthenticateAsync(options, startUri, endUri);


            if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
            {
                throw new InvalidOperationException();
            }
            else if (result.ResponseStatus == WebAuthenticationStatus.UserCancel)
            {
                throw new InvalidOperationException();
            }

            var client = new FacebookClient();
            var authResult = client.ParseOAuthCallbackUrl(new Uri(result.ResponseData));
            return authResult;
        }
Example #46
0
        private async Task <FacebookOAuthResult> PromptOAuthDialog(string permissions, WebAuthenticationOptions options)
        {
            // Use WebAuthenticationBroker to launch server side OAuth flow
            Uri startUri = GetLoginUrl(permissions);
            Uri endUri   = new Uri("https://www.facebook.com/connect/login_success.html");
            var result   = await WebAuthenticationBroker.AuthenticateAsync(options, startUri, endUri);

            if (result.ResponseStatus == WebAuthenticationStatus.ErrorHttp)
            {
                throw new InvalidOperationException();
            }
            else if (result.ResponseStatus == WebAuthenticationStatus.UserCancel)
            {
                throw new InvalidOperationException();
            }
            var client     = new FacebookClient();
            var authResult = client.ParseOAuthCallbackUrl(new Uri(result.ResponseData));

            return(authResult);
        }
 public async Task<WebAuthenticationResult> Authenticate(WebAuthenticationOptions webAuthenticationOptions, Uri url, Uri callback)
 {
     return await WebAuthenticationBroker.AuthenticateAsync(webAuthenticationOptions, url, callback);
 }