Exemple #1
0
        // if HttpListener is not used, you can remove async
        private async void FormOauth_Load(object sender, EventArgs e)
        {
            OauthBrowser.DocumentTitleChanged += (x, y) => { this.Text = OauthBrowser.DocumentTitle; };

            //start to open Web OAUTH login web page.
            OauthWrapper.AuthorizationCode = "";

            // Http Listener is Google recommended solution for desktop app,
            // and MS OAUTH supports it as well, but you need to add http://127.0.0.1 to
            // Azure portal -> Your app -> Authentication -> Mobile and desktop applications: redirect Uri, please check the following URI.
            if (!OauthWrapper.Provider.UseHttpListener)
            {
                OauthWrapper.Provider.ResetLocalRedirectUri();
                OauthBrowser.Navigate(OauthWrapper.Provider.GetFullAuthUri());
                return;
            }

            string httpRedirectUri = GetHttpRedirectUri();

            OauthWrapper.Provider.RedirectUri = httpRedirectUri;
            OauthBrowser.Navigate(OauthWrapper.Provider.GetFullAuthUri());

            try
            {
                await GetCodefromHttpListener(httpRedirectUri);
            }
            catch (Exception ep)
            {
                MessageBox.Show(ep.Message);
            }
            finally
            {
                this.Close();
            }
        }
Exemple #2
0
        private async void OauthBrowser_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
        {
            if (OauthViewer.Visibility == Visibility.Collapsed)
            {
                return;
            }

            OauthProgress.Visibility = Visibility.Collapsed;
            if (!args.IsSuccess)
            {
                MessageDialog dlg = new MessageDialog(args.WebErrorStatus.ToString() + ": " + args.Uri.AbsoluteUri);
                await dlg.ShowAsync();

                ShowOauthPanel(false);
                return;
            }

            if (string.IsNullOrWhiteSpace(args.Uri.Query))
            {
                return;
            }

            string code = string.Empty;

            try
            {
                WwwFormUrlDecoder decoder = new WwwFormUrlDecoder(args.Uri.Query);
                code = decoder.GetFirstValueByName("approvalCode");
            }
            catch { }

            if (string.IsNullOrWhiteSpace(code))
            {
                code = await OauthBrowser.InvokeScriptAsync("eval",
                                                            new string[] { "(function() { var el = document.getElementById(\"code\"); return (el==null)?'':el.value; })()" });
            }

            if (string.IsNullOrWhiteSpace(code))
            {
                return;
            }

            _oauthWrapper.AuthorizationCode = code;
            ShowOauthPanel(false);
        }
Exemple #3
0
        async Task GetCodefromHttpListener(string httpRedirectUri)
        {
            _httpListener = new HttpListener();
            _httpListener.Prefixes.Add(httpRedirectUri);
            _httpListener.Start();

            try
            {
                var context = await _httpListener.GetContextAsync();

                string responseString = string.Format("<html><head><title>Authorization is completed</title></head><body>AuthorizationCode is returned, please close current window and return to the app.</body></html>");
                var    buffer         = Encoding.UTF8.GetBytes(responseString);

                var response = context.Response;
                response.ContentLength64 = buffer.Length;
                var responseOutput = response.OutputStream;

                await responseOutput.WriteAsync(buffer, 0, buffer.Length);

                responseOutput.Close();
                _httpListener.Stop();

                OauthBrowser.Stop();

                if (context.Request.QueryString.Get("error") != null)
                {
                    MessageBox.Show("OAuth authorization error: {0}.", context.Request.QueryString.Get("error"));
                    return;
                }

                var code = context.Request.QueryString.Get("code");
                OauthWrapper.AuthorizationCode = code;
            }
            catch (ObjectDisposedException)
            {
                // this exception is thrown by closing window, don't handle it.
            }
        }
Exemple #4
0
        private async Task _doOauthAsync()
        {
            // AccessToken is existed, if it is not expired, use it directly, otherwise refresh it.
            if (!string.IsNullOrEmpty(_oauthWrapper.Provider.AccessToken))
            {
                if (!_oauthWrapper.IsAccessTokenExpired)
                {
                    return;
                }

                TextStatus.Text = "Refreshing access token ...";
                try
                {
                    await _oauthWrapper.RefreshAccessTokenAsync();

                    return;
                }
                catch
                {
                    TextStatus.Text = "Failed to refresh access token, try to get a new access token ...";
                }
            }

            OauthBrowser.Navigate(
                new Uri(_oauthWrapper.Provider.GetFullAuthUri())
                );

            ShowOauthPanel(true);
            while (OauthViewer.Visibility != Visibility.Collapsed)
            {
                await Task.Delay(100);
            }

            TextStatus.Text = "Requesting access token ...";
            await _oauthWrapper.RequestAccessTokenAndUserEmailAsync();
        }
 private void FormOauth_Load(object sender, EventArgs e)
 {
     //start to open Gmail OAUTH login web page.
     OauthBrowser.Navigate(OauthWrapper.OauthProvider.GenerateFullAuthUri());
 }
Exemple #6
0
        private async Task _doOauthAsync()
        {
            if (_oauthWrapper == null)
            {
                /*
                 *  To use Google OAUTH in your application, you must create a project in Google Developers Console.
                 *
                 * - Create your project at https://console.developers.google.com/project.
                 * - Select your project -> APIs & Services -> Dashboard -> Credentials;
                 * - Credentials -> Create Credentials -> OAuth client ID -> Web application or Other (Desktop Application).
                 *  It depends on your application type.
                 *
                 * - Input a name for your application, input your current ASP/ASP.NET URL at Authorized redirect URIs,
                 *  for example: http://localhost/gmailoauth/default.aspx. (Desktop Application doesn't require this step)
                 *  Click "Create", you will get your client id and client secret.
                 *
                 * - Finally you can also set detail information for your project at Credentials -> OAuth consent screen.
                 * - If you used https://mail.google.com scope, you should verify your application that is inroduced in cosent screen.
                 *  If you don't verify your application, your application is limited by some conditions.
                 *
                 * You must apply for your client id and client secret, don't use the client id in the sample project, because it is limited now.
                 * If you got "This app isn't verified" information, please click "advanced" -> Go to ... for test.
                 */
                OauthProviderInterface provider = GoogleOauthProvider.Create("1072602369179-aru4rj97ateiho9rt4pf5i8l1r01mc16.apps.googleusercontent.com",
                                                                             "Lnw8r5FvfKFNS_CSEucbdIE-");
                _oauthWrapper = new OauthDesktopWrapper(provider);
            }

            // AccessToken is existed, if it is not expired, use it directly, otherwise refresh it.
            if (!string.IsNullOrEmpty(_oauthWrapper.OauthProvider.AccessToken))
            {
                if (!_oauthWrapper.IsAccessTokenExpired)
                {
                    return;
                }

                TextStatus.Text = "Refreshing access token ...";
                try
                {
                    await _oauthWrapper.RefreshAccessTokenAsync();

                    return;
                }
                catch
                {
                    TextStatus.Text = "Failed to refresh access token, try to get a new access token ...";
                }
            }

            OauthBrowser.Navigate(
                new Uri(_oauthWrapper.OauthProvider.GenerateFullAuthUri())
                );

            ShowOauthPanel(true);
            while (OauthViewer.Visibility != Visibility.Collapsed)
            {
                await Task.Delay(100);
            }

            TextStatus.Text = "Requesting access token ...";
            await _oauthWrapper.RequestAccessTokenAndUserEmailAsync();
        }