public async Task <bool> ConnectAsync(string host) { return(await System.Threading.Tasks.Task.Run(() => { mutex.WaitOne(); try { ClearSessionFields(); this.host = host; var httpWebRequest = (HttpWebRequest)WebRequest.Create(this.host + AUTHENTICATION_URL); httpWebRequest.Method = RestConnector.METHOD_GET; httpWebRequest.ContentType = RestConnector.CONTENT_TYPE_JSON; httpWebRequest.CookieContainer = new CookieContainer(); using (var httpResponse = httpWebRequest.GetResponse()) { using (var reader = new StreamReader(httpResponse.GetResponseStream())) { var objText = reader.ReadToEnd(); connectionInfo = (SsoConnectionInfo)jSerialiser.Deserialize(objText, typeof(SsoConnectionInfo)); } } if (connectionListener != null) { connectionListener.OpenBrowser(connectionInfo.authentication_url); } long pollingTimeoutTimestamp = pollingTimeoutSeconds; SsoConnectionInfo accessTokenConnectionInfo = new SsoConnectionInfo(); while (pollingTimeoutTimestamp >= 0) { try { // check whether the user closed the browser dialg if (connectionListener != null) { if (!connectionListener.IsOpen()) { break; } } var pollRequest = (HttpWebRequest)WebRequest.Create(this.host + AUTHENTICATION_URL); pollRequest.Method = RestConnector.METHOD_POST; pollRequest.ContentType = RestConnector.CONTENT_TYPE_JSON; pollRequest.CookieContainer = new CookieContainer(); Stream stream = pollRequest.GetRequestStream(); using (var streamWriter = new StreamWriter(stream)) { string json = jSerialiser.Serialize(connectionInfo); streamWriter.Write(json); } using (var httpResponse = pollRequest.GetResponse()) using (var reader = new StreamReader(httpResponse.GetResponseStream())) { var objText = reader.ReadToEnd(); accessTokenConnectionInfo = (SsoConnectionInfo)jSerialiser.Deserialize(objText, typeof(SsoConnectionInfo)); } } catch (Exception) { Thread.Sleep(1000); // Do not DOS the server, not cool pollingTimeoutTimestamp--; // update connection listener on timeout progress if (connectionListener != null) { connectionListener.UpdateTimeout((int)pollingTimeoutTimestamp); } continue; } cookieValue = accessTokenConnectionInfo.access_token; cookieName = accessTokenConnectionInfo.cookie_name; if (connectionListener != null) { connectionListener.CloseBrowser(); } return true; } // check whether the user forgot about the browser dialg if (connectionListener != null) { if (connectionListener.IsOpen()) { connectionListener.CloseBrowser(); } } return false; } finally { mutex.ReleaseMutex(); } })); }