/// <inheritdoc /> public async Task <AuthorizationCodeResponseUrl> ReceiveCodeAsync(AuthorizationCodeRequestUrl url, CancellationToken taskCancellationToken) { var authorizationUrl = url.Build().AbsoluteUri; // 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(RedirectUri); 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."); } var ret = await GetResponseFromListener(listener, taskCancellationToken).ConfigureAwait(false); // Note that a successful callback has been received. s_receivedCallback = true; return(ret); } }
/// <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, })); }
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); 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. 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(); } } }
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); }
/// <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); } }
/// <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 })); }
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(); } } }
public Task <AuthorizationCodeResponseUrl> ReceiveCodeAsync(AuthorizationCodeRequestUrl url, CancellationToken taskCancellationToken) => Task.FromResult(new AuthorizationCodeResponseUrl());