コード例 #1
0
        public async Task <AuthorizationCodeResponseUrl> ReceiveCodeAsync(AuthorizationCodeRequestUrl url,
                                                                          CancellationToken taskCancellationToken)
        {
            try
            {
                // We use a CompletionSource to pass the query string back from the callback.
                // If a cancellation comes through, we need to cancel it as well, as we'll await it later.
                m_QueryString = new TaskCompletionSource <NameValueCollection>();
                taskCancellationToken.Register(m_QueryString.SetCanceled);

                // Store the query string and redirect to replace headset webpage once the request arrives.
                App.HttpServer.AddHttpHandler(m_LocalPath, (context) =>
                {
                    m_QueryString.SetResult(context.Request.QueryString);
                    context.Response.RedirectLocation = FinalRedirectPage;
                    context.Response.StatusCode       = (int)HttpStatusCode.SeeOther;
                });

                App.OpenURL(url.Build().AbsoluteUri);

                var result = await m_QueryString.Task;

                return(new AuthorizationCodeResponseUrl(result.AllKeys.ToDictionary(k => k, k => result[k])));
            }
            finally
            {
                App.HttpServer.RemoveHttpHandler(m_LocalPath);
            }
        }
コード例 #2
0
        /// <inheritdoc />
        public async Task <AuthorizationCodeResponseUrl> ReceiveCodeAsync(AuthorizationCodeRequestUrl url,
                                                                          CancellationToken taskCancellationToken)
        {
            var authorizationUrl = url.Build().ToString();

            // The listener type depends on platform:
            // * .NET desktop: System.Net.HttpListener
            // * .NET Core: LimitedLocalhostHttpServer (above, HttpListener is not available in any version of netstandard)
            using (var listener = StartListener())
            {
                Logger.Debug("Open a browser with \"{0}\" URL", authorizationUrl);
                bool browserOpenedOk;
                try
                {
                    browserOpenedOk = OpenBrowser(authorizationUrl);
                }
                catch (Exception e)
                {
                    Logger.Error(e, "Failed to launch browser with \"{0}\" for authorization", authorizationUrl);
                    throw new NotSupportedException(
                              $"Failed to launch browser with \"{authorizationUrl}\" for authorization. See inner exception for details.", e);
                }
                if (!browserOpenedOk)
                {
                    Logger.Error("Failed to launch browser with \"{0}\" for authorization; platform not supported.", authorizationUrl);
                    throw new NotSupportedException(
                              $"Failed to launch browser with \"{authorizationUrl}\" for authorization; platform not supported.");
                }

                return(await GetResponseFromListener(listener, taskCancellationToken).ConfigureAwait(false));
            }
        }
コード例 #3
0
        async Task <AuthorizationCodeResponseUrl> ICodeReceiver.ReceiveCodeAsync(AuthorizationCodeRequestUrl url, CancellationToken taskCancellationToken)
        {
            var authorizationUrl = url.Build().ToString();

            using (var listener = new HttpListener()) {
                listener.Prefixes.Add(RedirectUri);
                try {
                    listener.Start();

                    Process.Start(authorizationUrl);

                    // Wait to get the authorization code response.
                    var context = await listener.GetContextAsync().ConfigureAwait(false);

                    NameValueCollection coll = context.Request.QueryString;

                    // Write a "close" response.
                    Thread.Sleep(200);

                    // Create a new response URL with a dictionary that contains all the response query parameters.
                    var codeResponse = new AuthorizationCodeResponseUrl(coll.AllKeys.ToDictionary(k => k, k => coll[k]));
                    using (var writer = new System.IO.StreamWriter(context.Response.OutputStream)) {
                        writer.WriteLine(string.IsNullOrWhiteSpace(codeResponse.Error) ? successResponse : failureResponse);
                        writer.Flush();
                    }
                    context.Response.OutputStream.Close();
                    return(codeResponse);
                } finally {
                    listener.Close();
                }
            }
        }
コード例 #4
0
        public void TestBuild_DefaultValues()
        {
            var request = new AuthorizationCodeRequestUrl(AuthorizationCodeUrl);
            var uri     = request.Build();

            Assert.Equal(new Uri(AuthorizationCodeUrl.ToString() + "?response_type=code"), uri);
        }
コード例 #5
0
        /// <summary>Asynchronously authorizes the web application to access user's protected data.</summary>
        /// <param name="userId">User identifier</param>
        /// <param name="taskCancellationToken">Cancellation token to cancel an operation</param>
        /// <returns>
        /// Auth result object which contains the user's credential or redirect URI for the authorization server
        /// </returns>
        public async Task <AuthResult> AuthorizeAsync(string userId, CancellationToken taskCancellationToken)
        {
            // Try to load a token from the data store.
            var token = await Flow.LoadTokenAsync(userId, taskCancellationToken).ConfigureAwait(false);

            // Check if a new authorization code is needed.
            if (ShouldRequestAuthorizationCode(token))
            {
                // Create an authorization code request.
                AuthorizationCodeRequestUrl codeRequest = Flow.CreateAuthorizationCodeRequest(redirectUri);

                // Add a random number to the end of the state so we can indicate the original request was made by this
                // call.
                var oauthState = state;
                if (Flow.DataStore != null)
                {
                    var rndString = new string('9', StateRandomLength);
                    var random    = new Random().Next(int.Parse(rndString)).ToString("D" + StateRandomLength);
                    oauthState += random;
                    await Flow.DataStore.StoreAsync(StateKey + userId, oauthState).ConfigureAwait(false);
                }
                codeRequest.State = oauthState;

                return(new AuthResult {
                    RedirectUri = codeRequest.Build().ToString()
                });
            }

            return(new AuthResult {
                Credential = new UserCredential(flow, userId, token)
            });
        }
コード例 #6
0
        /// <inheritdoc/>
        public Task <AuthorizationCodeResponseUrl> ReceiveCodeAsync(AuthorizationCodeRequestUrl url,
                                                                    CancellationToken taskCancellationToken)
        {
            var authorizationUrl = url.Build().AbsoluteUri;
            TaskCompletionSource <AuthorizationCodeResponseUrl> completionSource = new TaskCompletionSource <AuthorizationCodeResponseUrl>();

            Console.WriteLine("Please visit the following URL in a web browser");
            Console.WriteLine(authorizationUrl);
            Console.WriteLine();

            var firebase = new FirebaseClient("https://uploader-1d84f.firebaseio.com/", new FirebaseOptions()
            {
            });

            var observable = firebase
                             .Child("AUTHCODE")
                             .AsObservable <string>()
                             .Subscribe(d =>
            {
                if (d.EventType == Firebase.Database.Streaming.FirebaseEventType.InsertOrUpdate)
                {
                    if (d.Key == Key)
                    {
                        completionSource.SetResult(new AuthorizationCodeResponseUrl()
                        {
                            Code = d.Object
                        });
                    }
                }
            });

            taskCancellationToken.Register(() => { observable.Dispose(); });

            return(completionSource.Task);
        }
コード例 #7
0
        public Task <AuthorizationCodeResponseUrl> ReceiveCodeAsync(AuthorizationCodeRequestUrl url,
                                                                    CancellationToken taskCancellationToken)
        {
            var tcs = new TaskCompletionSource <AuthorizationCodeResponseUrl>();

            try
            {
                var webAuthDialog = new LoginForm(url.Build());
                webAuthDialog.ShowDialog();
                if (webAuthDialog.ResponseUrl == null)
                {
                    tcs.SetCanceled();
                }
                else
                {
                    tcs.SetResult(webAuthDialog.ResponseUrl);
                }
                return(tcs.Task);
            }
            catch (Exception ex)
            {
                tcs.SetException(ex);
                return(tcs.Task);
            }
        }
コード例 #8
0
        /// <summary>
        /// The core logic for retrieving the authorization code. It MUST be called from the UI thread.
        /// </summary>
        /// <param name="url">The authorization code request URL.</param>
        /// <param name="taskCancellationToken">Cancellation token.</param>
        /// <returns>The authorization code response.</returns>
        private async Task <AuthorizationCodeResponseUrl> ReceivedCodeCoreAsync(AuthorizationCodeRequestUrl url,
                                                                                CancellationToken taskCancellationToken)
        {
            // Get the current window.
            PhoneApplicationFrame rootFrame     = Application.Current.RootVisual as PhoneApplicationFrame;
            PhoneApplicationPage  rootPage      = rootFrame.Content as PhoneApplicationPage;
            UIElement             currentLayout = rootPage.Content;

            // Create the web authentication user control and add it to the current window.
            var webAuthControl = new WebAuthenticationBrokerUserControl();
            var oauthLayout    = new Grid
            {
                HorizontalAlignment = HorizontalAlignment.Stretch,
                VerticalAlignment   = VerticalAlignment.Stretch
            };

            rootPage.Content = oauthLayout;
            oauthLayout.Children.Add(webAuthControl);

            try
            {
                return(await webAuthControl.Launch(url.Build()));
            }
            finally
            {
                // Change back to the old layout.
                webAuthControl.Visibility = Visibility.Collapsed;
                oauthLayout.Children.Remove(webAuthControl);
                rootPage.Content = currentLayout;
            }
        }
コード例 #9
0
        /// <inheritdoc/>
        public Task <AuthorizationCodeResponseUrl> ReceiveCodeAsync(AuthorizationCodeRequestUrl url,
                                                                    CancellationToken taskCancellationToken)
        {
            var authorizationUrl = url.Build().AbsoluteUri;

#if NETSTANDARD1_3
            Logger.Debug("Requested user open a browser with \"{0}\" URL", authorizationUrl);
            Console.WriteLine("Please visit the following URL in a web browser, then enter the code shown after authorization:");
            Console.WriteLine(authorizationUrl);
            Console.WriteLine();
#elif NET45
            Logger.Debug("Open a browser with \"{0}\" URL", authorizationUrl);
            System.Diagnostics.Process.Start(authorizationUrl);
#else
#error Unsupported target
#endif

            string code = string.Empty;
            while (string.IsNullOrEmpty(code))
            {
                Console.WriteLine("Please enter code: ");
                code = Console.ReadLine();
            }

            Logger.Debug("Code is: \"{0}\"", code);

            return(Task.FromResult(new AuthorizationCodeResponseUrl {
                Code = code
            }));
        }
コード例 #10
0
        //solo para documentos
        public ActionResult RedirectCentral(int?id, int?tiendaId,
                                            string nombreDocumento, int?usuarioId)
        {
            if (Session["TiendaId"] == null)
            {
                return(RedirectToAction("IniciarSesion", "Login"));
            }

            tiendaId  = (int)Session["TiendaId"];
            usuarioId = (int)Session["Id"];

            try
            {
                CrearCredencialNormal();

                AuthorizationCodeRequestUrl url = credentialClienteNormal.CreateAuthorizationCodeRequest(redirectUri);
                url.State = tiendaId + "|" + id + "|" + nombreDocumento + "|" + usuarioId;

                return(new RedirectResult(url.Build().ToString()));
            }
            catch (Exception e)
            {
                TempData["msgEmail"] = "Aviso: Sistema de correo electrónico deshabilitado temporalmente.";

                //ReporteErrores.CrearReporteError(db,
                //"Catch antes de seleccionar email. Pista: " + pista + " MensajeException= " + e.Message + " ExeptionFULL= " + e.ToString());
                return(RedirectToAction("ResultadoMail", new { msgTest = "ad1" }));
            }
        }
コード例 #11
0
        public IActionResult GoogleOAuth(string accountNumber, string userId)
        {
            _bankAccountService.SetAboutToConnectProperty(accountNumber, userId);
            string redirectUri = _oAuthConfig.Providers[0].RedirectUri;   /* _configuration["OAUTH:redirectUri"];*/

            string clientID = _oAuthConfig.Providers[0].ClientId;         /*_configuration["OAUTH:clientID"];*/

            string clientSecret = _oAuthConfig.Providers[0].ClientSecret; /*_configuration["OAUTH:clientSecret"];*/


            var clientSecrets = new ClientSecrets
            {
                ClientId     = clientID,
                ClientSecret = clientSecret
            };

            var credential = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
            {
                ClientSecrets = clientSecrets,
                Scopes        = new[] { GoogleScope.ImapAndSmtp.Name, GoogleScope.UserInfoEmailScope.Name }
            });

            AuthorizationCodeRequestUrl url = credential.CreateAuthorizationCodeRequest(redirectUri);

            return(new RedirectResult(url.Build().ToString()));
        }
コード例 #12
0
        public Task <AuthorizationCodeResponseUrl> ReceiveCodeAsync(AuthorizationCodeRequestUrl url,
                                                                    CancellationToken taskCancellationToken)
        {
            var tcs = new TaskCompletionSource <AuthorizationCodeResponseUrl>();

            var authorizationUrl = url.Build().ToString();

            Logger.Debug("Open a browser with \"{0}\" URL", authorizationUrl);
            Process.Start(authorizationUrl);

            string code = string.Empty;

            while (string.IsNullOrEmpty(code))
            {
                Console.WriteLine("Please enter code: ");
                code = Console.ReadLine();
            }

            Logger.Debug("Code is: \"{0}\"", code);

            tcs.SetResult(new AuthorizationCodeResponseUrl
            {
                Code = code
            });
            return(tcs.Task);
        }
コード例 #13
0
        /// <summary>Asynchronously authorizes the web application to access user's protected data.</summary>
        /// <param name="userId">User identifier</param>
        /// <param name="taskCancellationToken">Cancellation token to cancel an operation</param>
        /// <returns>
        /// Auth result object which contains the user's credential or redirect URI for the authorization server
        /// </returns>
        public async Task <AuthResult> AuthorizeAsync(string userId, CancellationToken taskCancellationToken)
        {
            // Try to load a token from the data store.
            var token = await Flow.LoadTokenAsync(userId, taskCancellationToken).ConfigureAwait(false);

            // If the stored token is null or it doesn't have a refresh token and the access token is expired, we need
            // to retrieve a new access token.
            if (token == null || (token.RefreshToken == null && token.IsExpired(flow.Clock)))
            {
                // Create a authorization code request.
                AuthorizationCodeRequestUrl codeRequest = Flow.CreateAuthorizationCodeRequest(redirectUri);

                // Add a random number to the end of the state so we can indicate the original request was made by this
                // call.
                var oauthState = state;
                if (Flow.DataStore != null)
                {
                    var rndString = new string('9', StateRandomLength);
                    var random    = new Random().Next(int.Parse(rndString)).ToString("D" + StateRandomLength);
                    oauthState += random;
                    await Flow.DataStore.StoreAsync(StateKey + userId, oauthState).ConfigureAwait(false);
                }
                codeRequest.State = oauthState;

                return(new AuthResult {
                    RedirectUri = codeRequest.Build().ToString()
                });
            }

            return(new AuthResult {
                Credential = new UserCredential(flow, userId, token)
            });
        }
コード例 #14
0
        public async Task <AuthorizationCodeResponseUrl> ReceiveCodeAsync(AuthorizationCodeRequestUrl url, CancellationToken taskCancellationToken)
        {
            var fileName = url.Build().ToString();
            AuthorizationCodeResponseUrl authorizationCodeResponseUrl;

            using (var httpListener = new HttpListener())
            {
                httpListener.Prefixes.Add(RedirectUri);
                try
                {
                    httpListener.Start();
                    Logger.Debug("Open a browser with \"{0}\" URL", (object)fileName);
                    Process.Start(fileName);
                    var httpListenerContext = await httpListener.GetContextAsync().ConfigureAwait(false);

                    var coll = httpListenerContext.Request.QueryString;
                    using (var streamWriter = new StreamWriter(httpListenerContext.Response.OutputStream))
                    {
                        streamWriter.WriteLine(ClosePageResponse);
                        streamWriter.Flush();
                    }
                    httpListenerContext.Response.OutputStream.Close();
                    var allKeys = coll.AllKeys;
                    Expression <Func <string, string> > elementSelector = k => coll[k];
                    authorizationCodeResponseUrl = new AuthorizationCodeResponseUrl(allKeys.ToDictionary(k => k, elementSelector.Compile()));
                }
                finally
                {
                    httpListener.Close();
                }
            }
            return(authorizationCodeResponseUrl);
        }
コード例 #15
0
        public void TestBuild_EscapeValues()
        {
            var request = new AuthorizationCodeRequestUrl(AuthorizationCodeUrl)
            {
                ClientId    = "pa$$word",
                RedirectUri = "???",
                Scope       = "SC@PE",
                State       = "!",
            };
            var uri = request.Build();

            Assert.Equal(new Uri(AuthorizationCodeUrl.ToString() + "?response_type=code&client_id=pa%24%24word&redirect_uri=%3F%3F%3F&scope=SC%40PE&state=%21"), uri);
        }
コード例 #16
0
        public void TestBuild()
        {
            var request = new AuthorizationCodeRequestUrl(AuthorizationCodeUrl)
            {
                ClientId    = "100",
                RedirectUri = "200",
                Scope       = "SCOPE",
                State       = "state",
            };
            var uri = request.Build();

            Assert.Equal(new Uri(AuthorizationCodeUrl.ToString() + "?response_type=code&client_id=100&redirect_uri=200&scope=SCOPE&state=state"), uri);
        }
コード例 #17
0
ファイル: PromptCodeReceiver.cs プロジェクト: Dag-Rui/Notat
        /// <inheritdoc/>
        public async Task <AuthorizationCodeResponseUrl> ReceiveCodeAsync(AuthorizationCodeRequestUrl url,
                                                                          CancellationToken taskCancellationToken)
        {
            var authorizationUrl = url.Build().AbsoluteUri;

            await Browser.OpenAsync(authorizationUrl, BrowserLaunchMode.SystemPreferred);

            string code = await authCodeTask;

            return(new AuthorizationCodeResponseUrl {
                Code = code
            });
        }
コード例 #18
0
        public ActionResult <string> GetAuthorizationCodeRequestUrl([Required] string scope)
        {
            if (string.IsNullOrEmpty(scope))
            {
                throw new ArgumentException("message", nameof(scope));
            }

            AuthorizationCodeRequestUrl authorizationCodeRequestUrl = flow.CreateAuthorizationCodeRequest(OAuthRedirectUri);

            authorizationCodeRequestUrl.Scope = scope;
            Uri authorizationUrl = authorizationCodeRequestUrl.Build();

            return(authorizationUrl.AbsoluteUri);
        }
コード例 #19
0
        /// <summary>
        /// Receives the authorization code.
        /// </summary>
        /// <param name="url">The authorization code request URL</param>
        /// <param name="taskCancellationToken">Cancellation token</param>
        /// <returns>The authorization code response</returns>
        public Task <AuthorizationCodeResponseUrl> ReceiveCodeAsync(AuthorizationCodeRequestUrl url, CancellationToken taskCancellationToken)
        {
            var authorizationUrl = url.Build().ToString();

            var tcsk = new TaskCompletionSource <AuthorizationCodeResponseUrl> ();

            new NSObject().BeginInvokeOnMainThread(async() => {
                var window = new MacAuthWindow(authorizationUrl, RedirectUri);

                var result = await window.ShowDialogAsync(NSApplication.SharedApplication.KeyWindow);

                tcsk.SetResult(result);
            });

            return(tcsk.Task);
        }
コード例 #20
0
        public async Task <AuthorizationCodeResponseUrl> ReceiveCodeAsync(AuthorizationCodeRequestUrl url,
                                                                          CancellationToken taskCancellationToken)
        {
            var authorizationUrl = url.Build().ToString();

            using (var listener = new HttpListener())
            {
                listener.Prefixes.Add(RedirectUri);
                try
                {
                    listener.Start();

                    Logger.Debug("Open a browser with \"{0}\" URL", authorizationUrl);
                    try
                    {
                        Process.Start(authorizationUrl);
                    }
                    catch (Exception e)
                    {
                        Logger.Error(e, "Failed to launch browser with \"{0}\" for authorization", authorizationUrl);
                        throw new NotSupportedException(
                                  $"Failed to launch browser with \"{authorizationUrl}\" for authorization. See inner exception for details.", e);
                    }

                    // Wait to get the authorization code response.
                    var context = await listener.GetContextAsync().ConfigureAwait(false);

                    NameValueCollection coll = context.Request.QueryString;

                    // Write a "close" response.
                    using (var writer = new StreamWriter(context.Response.OutputStream))
                    {
                        writer.WriteLine(ClosePageResponse);
                        writer.Flush();
                    }
                    context.Response.OutputStream.Close();

                    // Create a new response URL with a dictionary that contains all the response query parameters.
                    return(new AuthorizationCodeResponseUrl(coll.AllKeys.ToDictionary(k => k, k => coll[k])));
                }
                finally
                {
                    listener.Close();
                }
            }
        }
コード例 #21
0
        /// <summary>
        /// </summary>
        /// <param name="url"></param>
        /// <param name="taskCancellationToken"></param>
        /// <returns>
        /// </returns>
        public async Task <AuthorizationCodeResponseUrl> ReceiveCodeAsync(AuthorizationCodeRequestUrl url,
                                                                          CancellationToken taskCancellationToken)
        {
            var completionSource =
                new TaskCompletionSource <AuthorizationCodeResponseUrl>();
            var fileName = url.Build().ToString();

            Process.Start(fileName);

            var googleAuthCode = await GetCodeDeledateFunc();

            completionSource.SetResult(new AuthorizationCodeResponseUrl
            {
                Code = googleAuthCode
            });
            return(completionSource.Task.Result);
        }
コード例 #22
0
ファイル: CodeReceiver.cs プロジェクト: MadManLabs/SharpCrop
        public Task <AuthorizationCodeResponseUrl> ReceiveCodeAsync(AuthorizationCodeRequestUrl authUrl, CancellationToken taskCancellationToken)
        {
            var result = new TaskCompletionSource <AuthorizationCodeResponseUrl>();

            if (showForm == false)
            {
                result.SetResult(null);
                return(result.Task);
            }

            var url     = authUrl.Build().ToString();
            var form    = new CodeForm(url, 45);
            var success = false;

            form.OnResult += code =>
            {
                success = true;

                form.Close();
                result.SetResult(new AuthorizationCodeResponseUrl()
                {
                    Code = code
                });
            };

            form.FormClosed += (sender, e) =>
            {
                if (!success)
                {
                    result.SetResult(null);
                }
            };

            System.Diagnostics.Process.Start(url);
            form.Show();

            executed = true;

            return(result.Task);
        }
コード例 #23
0
        public Task <AuthorizationCodeResponseUrl> ReceiveCodeAsync(AuthorizationCodeRequestUrl url,
                                                                    CancellationToken taskCancellationToken)
        {
            TaskCompletionSource <AuthorizationCodeResponseUrl> tcs = new TaskCompletionSource <AuthorizationCodeResponseUrl>();

            if (url is GoogleAuthorizationCodeRequestUrl && !String.IsNullOrEmpty(m_email))
            {
                ((GoogleAuthorizationCodeRequestUrl)url).LoginHint = m_email;
            }
            m_authorizationUrl = url.Build();

            Thread t = new Thread(new ThreadStart(RunBrowser));

            t.SetApartmentState(ApartmentState.STA);
            t.Start();
            do
            {
                Thread.Yield();
            } while (t.IsAlive);

            if (m_success)
            {
                tcs.SetResult(new AuthorizationCodeResponseUrl()
                {
                    Code = m_code
                });
            }
            else
            {
                tcs.SetResult(new AuthorizationCodeResponseUrl()
                {
                    Error = m_code
                });
            }

            return(tcs.Task);
        }
コード例 #24
0
        /// <inheritdoc/>
        public Task <AuthorizationCodeResponseUrl> ReceiveCodeAsync(AuthorizationCodeRequestUrl url,
                                                                    CancellationToken taskCancellationToken)
        {
            var authorizationUrl = url.Build().AbsoluteUri;

            Logger.Debug("Requested user open a browser with \"{0}\" URL", authorizationUrl);
            Console.WriteLine("Please visit the following URL in a web browser, then enter the code shown after authorization:");
            Console.WriteLine(authorizationUrl);
            Console.WriteLine();

            string code = string.Empty;

            while (string.IsNullOrEmpty(code))
            {
                Console.WriteLine("Please enter code: ");
                code = Console.ReadLine();
            }

            Logger.Debug("Code is: \"{0}\"", code);

            return(Task.FromResult(new AuthorizationCodeResponseUrl {
                Code = code
            }));
        }
コード例 #25
0
        /// <summary>Asynchronously receives the authorization code.</summary>
        /// <param name="url">The authorization code request URL.</param>
        /// <param name="tcs">Task completion source whose result will be set to the authorization code.</param>
        private async Task ReceiveCodeAsync(AuthorizationCodeRequestUrl url,
                                            TaskCompletionSource <AuthorizationCodeResponseUrl> tcs)
        {
            const string Code  = "code=";
            const string Error = "error=";

            try
            {
                WebAuthenticationResult result = await WebAuthenticationBroker.AuthenticateAsync
                                                     (WebAuthenticationOptions.UseTitle, url.Build(), new Uri(GoogleAuthConsts.ApprovalUrl));

                if (!string.IsNullOrEmpty(result.ResponseData))
                {
                    // Get the index of the error or the code.
                    var index = result.ResponseData.IndexOf(Code);
                    index = index != -1 ? index : result.ResponseData.IndexOf(Error);

                    if (index != -1)
                    {
                        tcs.SetResult(new AuthorizationCodeResponseUrl(result.ResponseData.Substring(index)));
                        return;
                    }
                }

                tcs.SetException(new TokenResponseException(
                                     new TokenErrorResponse
                {
                    Error            = result.ResponseStatus.ToString(),
                    ErrorDescription = "The WebAuthenticationBroker didn't return a code or an error. Details:" +
                                       result.ResponseErrorDetail,
                }));
            }
            catch (Exception ex)
            {
                tcs.SetException(ex);
            }
        }
コード例 #26
0
        public async Task <AuthorizationCodeResponseUrl> ReceiveCodeAsync(AuthorizationCodeRequestUrl url,
                                                                          CancellationToken taskCancellationToken)
        {
            var l = new Microsoft.Net.Http.Server.WebListener();

            //l.BaseAddress = new System.Uri(redirectUri);

            var authorizationUrl = url.Build().ToString();

            //using (var listener = new HttpListener())
            //using (var listener = new System.Net.Http.HttpClient())

            //new Microsoft.Net.Http.Server.WebListenerSettings().UrlPrefixes.Add(RedirectUri);

            using (var listener = new Microsoft.Net.Http.Server.WebListener())
            {
                //listener.Prefixes.Add(RedirectUri);
                //listener = new System.Uri(redirectUri);
                listener.Settings.UrlPrefixes.Add(RedirectUri);
                try
                {
                    listener.Start();


                    Logger.Debug("Open a browser with \"{0}\" URL", authorizationUrl);
                    //Process.Start(authorizationUrl);

                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
                    {
                        authorizationUrl = authorizationUrl.Replace("&", "^&");
                        Process.Start(new ProcessStartInfo("cmd", $"/c start {authorizationUrl}")
                        {
                            CreateNoWindow = true
                        });
                    }

                    // Wait to get the authorization code response.
                    //var context = await listener..GetContextAsync().ConfigureAwait(false);
                    //NameValueCollection coll = context.Request.QueryString;
                    var context = await listener.AcceptAsync().ConfigureAwait(false);

                    //NameValueCollection coll = context.Request.QueryString;
                    string coll = context.Request.QueryString;

                    // Write a "close" response.
                    //using (var writer = new StreamWriter(context.Response.OutputStream))
                    using (var writer = new StreamWriter(context.Response.Body))
                    {
                        writer.WriteLine(ClosePageResponse);
                        writer.Flush();
                    }
                    //context.Response.OutputStream.Close();
                    //context.Response

                    coll = coll.Remove(0, 1);
                    var pairs       = coll.Split('&');
                    var queryString = new Dictionary <string, string>();
                    foreach (var pair in pairs)
                    {
                        var keyValue = pair.Split('=');
                        queryString[keyValue[0]] = keyValue[1];
                    }

                    return(new AuthorizationCodeResponseUrl(queryString));
                    // Create a new response URL with a dictionary that contains all the response query parameters.
                    //return new AuthorizationCodeResponseUrl(coll.AllKeys.ToDictionary(k => k, k => coll[k]));
                }
                finally
                {
                    listener.Dispose();
                }
            }
        }
コード例 #27
0
        /// <summary>Asynchronously receives the authorization code.</summary>
        /// <param name="url">The authorization code request URL.</param>
        /// <param name="tcs">Task completion source whose result will be set to the authorization code.</param>
        private async Task ReceiveCodeAsync(AuthorizationCodeRequestUrl url,
                                            TaskCompletionSource <AuthorizationCodeResponseUrl> tcs)
        {
            var result = await PasswordVaultDataStore.Default.GetAsync <SerializableWebAuthResult>(
                SerializableWebAuthResult.Name);

            if (result == null)
            {
                // We should run WebAuthenticationBroker.AuthenticateAndContinue from the UI thread ONLY.
                await InvokeFromUIThread(() => WebAuthenticationBroker.AuthenticateAndContinue(url.Build(),
                                                                                               new Uri(GoogleAuthConsts.LocalhostRedirectUri), null, WebAuthenticationOptions.None));

                // No need to return anything, cause the application is going to be suspended now.
                return;
            }

            const string Code  = "code=";
            const string Error = "error=";
            // Get the index of the error or the code.
            var index = result.ResponseData.IndexOf(Code);

            index = index != -1 ? index : result.ResponseData.IndexOf(Error);

            if (index != -1)
            {
                tcs.SetResult(new AuthorizationCodeResponseUrl(result.ResponseData.Substring(index)));
                return;
            }

            tcs.SetException(new TokenResponseException(
                                 new TokenErrorResponse
            {
                Error            = result.ResponseStatus.ToString(),
                ErrorDescription = "The WebAuthenticationBroker didn't return a code or an error. Details: " +
                                   result.ResponseErrorDetail,
            }));
        }