Exemplo n.º 1
0
        /// <summary>
        /// Method that returns the initial URL to be displayed in the web browser.
        /// </summary>
        /// <returns>
        /// A task that will return the initial URL.
        /// </returns>
        public override Task <Uri> GetInitialUrlAsync()
        {
            var req = OAuth1.CreateRequest(
                "GET",
                requestTokenUrl,
                new Dictionary <string, string>()
            {
                { "oauth_callback", callbackUrl.AbsoluteUri },
            },
                consumerKey,
                consumerSecret,
                "");

            return(req.GetResponseAsync().ContinueWith(respTask => {
                var content = respTask.Result.GetResponseText();

                var r = WebEx.FormDecode(content);

                token = r["oauth_token"];
                tokenSecret = r["oauth_token_secret"];

                string paramType = authorizeUrl.AbsoluteUri.IndexOf("?") >= 0 ? "&" : "?";

                var url = authorizeUrl.AbsoluteUri + paramType + "oauth_token=" + Uri.EscapeDataString(token);
                return new Uri(url);
            }));
        }
Exemplo n.º 2
0
        /// <summary>
        /// Event handler called when a page has completed loading.
        /// </summary>
        /// <param name='url'>
        /// The URL of the page.
        /// </param>
        public override void OnPageLoaded(Uri url)
        {
            var query    = WebEx.FormDecode(url.Query);
            var fragment = WebEx.FormDecode(url.Fragment);

            OnPageEncountered(url, query, fragment);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Asynchronously makes a request to the access token URL with the given parameters.
        /// </summary>
        /// <param name="queryValues">The parameters to make the request with.</param>
        /// <returns>The data provided in the response to the access token request.</returns>
        protected Task <IDictionary <string, string> > RequestAccessTokenAsync(IDictionary <string, string> queryValues)
        {
            var query = queryValues.FormEncode();

            var req = WebRequest.Create(accessTokenUrl);

            req.Method = "POST";
            var body = Encoding.UTF8.GetBytes(query);

            req.ContentLength = body.Length;
            req.ContentType   = "application/x-www-form-urlencoded";
            using (var s = req.GetRequestStream()) {
                s.Write(body, 0, body.Length);
            }
            return(req.GetResponseAsync().ContinueWith(task => {
                var text = task.Result.GetResponseText();

                // Parse the response
                var data = text.Contains("{") ? WebEx.JsonDecode(text) : WebEx.FormDecode(text);

                if (data.ContainsKey("error"))
                {
                    throw new AuthException("Error authenticating: " + data ["error"]);
                }
                else if (data.ContainsKey("access_token"))
                {
                    return data;
                }
                else
                {
                    throw new AuthException("Expected access_token in access token response, but did not receive one.");
                }
            }));
        }
Exemplo n.º 4
0
        /// <summary>
        /// Method that returns the initial URL to be displayed in the web browser.
        /// </summary>
        /// <returns>
        /// A task that will return the initial URL.
        /// </returns>
        public override Task <Uri> GetInitialUrlAsync()
        {
            /*
             *                  mc++
             *                  OriginalString property of the Uri object should be used instead of AbsoluteUri
             *                  otherwise trailing slash is added.
             */
            string oauth_callback_uri_absolute = callbackUrl.AbsoluteUri;
            string oauth_callback_uri_original = callbackUrl.OriginalString;

            System.Diagnostics.Debug.WriteLine("GetInitialUrlAsync callbackUrl.AbsoluteUri    = " + oauth_callback_uri_absolute);
            System.Diagnostics.Debug.WriteLine("GetInitialUrlAsync callbackUrl.OriginalString = " + oauth_callback_uri_original);

            string oauth_callback_uri = oauth_callback_uri_absolute;

            var req = OAuth1.CreateRequest
                      (
                "GET",
                requestTokenUrl,
                new Dictionary <string, string>()
            {
                { "oauth_callback", oauth_callback_uri },
            },
                consumerKey,
                consumerSecret,
                ""
                      );

            if (this.HttpWebClientFrameworkType == HttpWebClientFrameworkType.WebRequest)
            {
                return(req.GetResponseAsync()
                       .ContinueWith
                       (
                           respTask =>
                {
                    var content = respTask.Result.GetResponseText();

                    var r = WebEx.FormDecode(content);

                    token = r["oauth_token"];
                    tokenSecret = r["oauth_token_secret"];

                    string paramType = authorizeUrl.AbsoluteUri.IndexOf("?") >= 0 ? "&" : "?";

                    var url = authorizeUrl.AbsoluteUri + paramType + "oauth_token=" + Uri.EscapeDataString(token);
                    return new Uri(url);
                }
                       ));
            }
            else if (this.HttpWebClientFrameworkType == HttpWebClientFrameworkType.HttpClient)
            {
                throw new NotImplementedException("HttpClient implementation!");
            }

            return(null);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Event handler called when a page has completed loading.
        /// </summary>
        /// <param name='url'>
        /// The URL of the page.
        /// </param>
        public override void OnPageLoaded(Uri url)
        {
            IDictionary <string, string> query    = WebEx.FormDecode(url.Query);
            IDictionary <string, string> fragment = WebEx.FormDecode(url.Fragment);

            this.Query    = query;
            this.Fragment = fragment;

            OnPageEncountered(url, query, fragment);

            return;
        }
Exemplo n.º 6
0
        /// <summary>
        /// Event handler that watches for the callback URL to be loaded.
        /// </summary>
        /// <param name='url'>
        /// The URL of the loaded page.
        /// </param>
        public override void OnPageLoaded(Uri url)
        {
            if (
                url.Authority == callbackUrl.Authority
                //url.Host == callbackUrl.Host
                &&
                url.AbsolutePath == callbackUrl.AbsolutePath
                )
            {
                var query = url.Query;
                var r     = WebEx.FormDecode(query);

                r.TryGetValue("oauth_verifier", out verifier);

                #if DEBUG
                StringBuilder sb = new StringBuilder();
                sb.AppendLine($"OAuth1Authenticator.OnPageLoaded ");
                sb.AppendLine($"        url = {url.AbsoluteUri}");
                sb.AppendLine($"        oauth_verifier = {verifier}");
                System.Diagnostics.Debug.WriteLine(sb.ToString());
                #endif

                GetAccessTokenAsync().ContinueWith(getTokenTask =>
                {
                    if (getTokenTask.IsCanceled)
                    {
                        OnCancelled();
                    }
                    else if (getTokenTask.IsFaulted)
                    {
                        OnError(getTokenTask.Exception);
                    }
                }, TaskContinuationOptions.NotOnRanToCompletion);
            }
            else
            {
                // http[s]://www.xamarin.com != http[s]://xamarin.com
                #if DEBUG
                StringBuilder sb = new StringBuilder();
                sb.AppendLine($"OAuth1Authenticator.OnPageLoaded ");
                sb.AppendLine($"        mc++ fix");
                sb.AppendLine($"        url         = {url.AbsoluteUri}");
                sb.AppendLine($"        callbackUrl = {callbackUrl.AbsoluteUri}");
                sb.AppendLine($"        oauth_verifier = {verifier}");
                System.Diagnostics.Debug.WriteLine(sb.ToString());
                #endif
            }

            return;
        }
        /// <summary>
        /// Reads all the response data and interprets it as a string.
        /// </summary>
        /// <returns>
        /// The response text.
        /// </returns>
        public virtual string GetResponseText()
        {
            var encoding = Encoding.UTF8;

            if (Headers.ContainsKey("Content-Type"))
            {
                encoding = WebEx.GetEncodingFromContentType(Headers ["Content-Type"]);
            }

            using (var s = GetResponseStream()) {
                using (var r = new StreamReader(s, encoding)) {
                    return(r.ReadToEnd());
                }
            }
        }
        /// <summary>
        /// Asynchronously makes a request to the access token URL with the given parameters.
        /// </summary>
        /// <param name="queryValues">The parameters to make the request with.</param>
        /// <returns>The data provided in the response to the access token request.</returns>
        public async Task <IDictionary <string, string> > RequestAccessTokenAsync(IDictionary <string, string> queryValues)
        {
            // mc++ changed protected to public for extension methods RefreshToken (Adrian Stevens)
            var content = new FormUrlEncodedContent(queryValues);


            HttpClient          client   = new HttpClient();
            HttpResponseMessage response = await client.PostAsync(accessTokenUrl, content).ConfigureAwait(false);

            string text = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            // Parse the response
            var data = text.Contains("{") ? WebEx.JsonDecode(text) : WebEx.FormDecode(text);

            if (data.ContainsKey("error"))
            {
                throw new AuthException("Error authenticating: " + data["error"]);
            }
            #region
            //---------------------------------------------------------------------------------------
            /// Pull Request - manually added/fixed
            ///		OAuth2Authenticator changes to work with joind.in OAuth #91
            ///		https://github.com/xamarin/Xamarin.Auth/pull/91
            ///
            //else if (data.ContainsKey("access_token"))
            else if (data.ContainsKey(AccessTokenName))
            //---------------------------------------------------------------------------------------
            #endregion
            {
            }
            else
            {
                #region
                //---------------------------------------------------------------------------------------
                /// Pull Request - manually added/fixed
                ///		OAuth2Authenticator changes to work with joind.in OAuth #91
                ///		https://github.com/xamarin/Xamarin.Auth/pull/91
                ///
                //throw new AuthException ("Expected access_token in access token response, but did not receive one.");
                throw new AuthException("Expected " + AccessTokenName + " in access token response, but did not receive one.");
                //---------------------------------------------------------------------------------------
                #endregion
            }

            return(data);
        }
Exemplo n.º 9
0
        Task GetAccessTokenAsync()
        {
            var requestParams = new Dictionary <string, string> {
                { "oauth_token", token }
            };

            if (verifier != null)
            {
                requestParams["oauth_verifier"] = verifier;
            }

            var req = OAuth1.CreateRequest(
                "GET",
                accessTokenUrl,
                requestParams,
                consumerKey,
                consumerSecret,
                tokenSecret);

            return(req.GetResponseAsync().ContinueWith(respTask => {
                var content = respTask.Result.GetResponseText();

                var accountProperties = WebEx.FormDecode(content);
                accountProperties["oauth_consumer_key"] = consumerKey;
                accountProperties["oauth_consumer_secret"] = consumerSecret;

                if (getUsernameAsync != null)
                {
                    getUsernameAsync(accountProperties).ContinueWith(uTask => {
                        if (uTask.IsFaulted)
                        {
                            OnError(uTask.Exception);
                        }
                        else
                        {
                            OnSucceeded(uTask.Result, accountProperties);
                        }
                    });
                }
                else
                {
                    OnSucceeded("", accountProperties);
                }
            }));
        }
Exemplo n.º 10
0
        /// <summary>
        /// Event handler called when a new page is being loaded in the web browser.
        /// </summary>
        /// <param name='url'>
        /// The URL of the page.
        /// </param>
        public override void OnPageLoading(Uri url)
        {
            #if DEBUG
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            sb.AppendLine("WebRedirectAuthenticator OnPageLoading Called");
            sb.AppendLine("     AbsoluteUri  = ").AppendLine(url.AbsoluteUri);
            sb.AppendLine("     AbsolutePath = ").AppendLine(url.AbsolutePath);
            System.Diagnostics.Debug.WriteLine(sb.ToString());
            #endif

            var query    = WebEx.FormDecode(url.Query);
            var fragment = WebEx.FormDecode(url.Fragment);

            // mc++
            // TODO: schemas
            OnPageEncountered(url, query, fragment);

            return;
        }
Exemplo n.º 11
0
        /// <summary>
        /// Event handler that watches for the callback URL to be loaded.
        /// </summary>
        /// <param name='url'>
        /// The URL of the loaded page.
        /// </param>
        public override void OnPageLoaded(Uri url)
        {
            if (url.Host == callbackUrl.Host && url.AbsolutePath == callbackUrl.AbsolutePath)
            {
                var query = url.Query;
                var r     = WebEx.FormDecode(query);

                r.TryGetValue("oauth_verifier", out verifier);

                GetAccessTokenAsync().ContinueWith(getTokenTask => {
                    if (getTokenTask.IsCanceled)
                    {
                        OnCancelled();
                    }
                    else if (getTokenTask.IsFaulted)
                    {
                        OnError(getTokenTask.Exception);
                    }
                }, TaskContinuationOptions.NotOnRanToCompletion);
            }
        }
Exemplo n.º 12
0
        Task GetAccessTokenAsync()
        {
            #if DEBUG
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"OAuth1Authenticator.GetAccessTokenAsync ");
            sb.AppendLine($"        token = {token}");
            System.Diagnostics.Debug.WriteLine(sb.ToString());
            #endif

            var requestParams = new Dictionary <string, string>
            {
                { "oauth_token", token }
            };

            if (verifier != null)
            {
                requestParams["oauth_verifier"] = verifier;
                System.Diagnostics.Debug.WriteLine($"        verifier = {verifier}");
            }

            var req = OAuth1.CreateRequest(
                "GET",
                accessTokenUrl,
                requestParams,
                consumerKey,
                consumerSecret,
                tokenSecret);

            if (this.HttpWebClientFrameworkType == HttpWebClientFrameworkType.WebRequest)
            {
                return(req.GetResponseAsync().ContinueWith(respTask =>
                {
                    var content = respTask.Result.GetResponseText();

                    var accountProperties = WebEx.FormDecode(content);

                    accountProperties["oauth_consumer_key"] = consumerKey;
                    accountProperties["oauth_consumer_secret"] = consumerSecret;

                    if (getUsernameAsync != null)
                    {
                        getUsernameAsync(accountProperties).ContinueWith(uTask =>
                        {
                            if (uTask.IsFaulted)
                            {
                                OnError(uTask.Exception);
                            }
                            else
                            {
                                OnSucceeded(uTask.Result, accountProperties);
                            }
                        });
                    }
                    else
                    {
                        OnSucceeded("", accountProperties);
                    }
                }));
            }
            else if (this.HttpWebClientFrameworkType == HttpWebClientFrameworkType.HttpClient)
            {
                throw new NotImplementedException("HttpClient implementation!");
            }

            return(null);
        }