/// <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.");
                }
            }));
        }
コード例 #2
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 async Task <IDictionary <string, string> > RequestAccessTokenAsync(IDictionary <string, string> queryValues)
        {
            var query = queryValues.FormEncode();

            HttpClient client = new HttpClient();
            //var response = await client.PostAsync(accessTokenUrl.AbsoluteUri, new StringContent(query, Encoding.UTF8, "application/x-www-form-urlencoded"));
            //var text = await response.Content.ReadAsStringAsync();

            //// 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.");
            //}

            //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);
            //}
            var taskPost = client.PostAsync(accessTokenUrl.AbsoluteUri, new StringContent(query, Encoding.UTF8, "application/x-www-form-urlencoded"));

            taskPost.Wait();
            var taskReadResponse = taskPost.Result.Content.ReadAsStringAsync();

            taskReadResponse.Wait();

            var text = taskReadResponse.Result;

            // 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.");
            }
        }
コード例 #3
0
        protected async Task <IDictionary <string, string> > RequestAccessTokenAsync(CancellationToken cancellationToken)
        {
            var query = FieldsToFormUrlEncodedContent();

            using (var client = new HttpClient(new NativeMessageHandler()))
            {
                var response = await client.PostAsync(_accessTokenUrl, query, cancellationToken);

                var contentStream = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    if (response.Content.Headers.ContentType.MediaType.Contains("html"))
                    {
                        throw new AuthException($"{response.StatusCode}: {response.ReasonPhrase}");
                    }
                }

                var data = contentStream.Contains("{")
                        ? WebEx.JsonDecode(contentStream)
                        : WebEx.FormDecode(contentStream);

                if (data.ContainsKey("access_token") || data.ContainsKey("error"))
                {
                    return(data);
                }

                throw new AuthException("Expected an access_token or error header in the response message.");
            }
        }
コード例 #4
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 async Task <IDictionary <string, string> > RequestAccessTokenAsync(IDictionary <string, string> queryValues)
        {
            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"]);
            }
            else if (data.ContainsKey("access_token"))
            {
                return(data);
            }
            else
            {
                throw new AuthException("Expected access_token in access token response, but did not receive one.");
            }
        }
コード例 #5
0
        public void JsonDecode(string json, string arg, string value)
        {
            var    dict = WebEx.JsonDecode(json);
            string v;

            Assert.That(dict.TryGetValue(arg, out v), Is.True, "Dictionary did not contain argument '" + arg + "'");
            Assert.That(v, Is.EqualTo(value));
        }
コード例 #6
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>
        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();

            //If client secret is set, use HTTP BASIC auth to authenticate to the token endpoint
            if (!string.IsNullOrEmpty(this.ClientSecret))
            {
                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("basic", Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes($"{this.ClientId}:{this.ClientSecret}")));
            }

            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);
        }
コード例 #7
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>
        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();
            HttpRequestMessage Message = new HttpRequestMessage(HttpMethod.Post, this.accessTokenUrl);

            Message.Content = content;
            if (this.UserAgent != null)
            {
                Message.Headers.Add(@"User-Agent", this.UserAgent);
            }
            HttpResponseMessage response = await client.SendAsync(Message).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);
        }
コード例 #8
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>
        public async Task <IDictionary <string, string> > CustomRequestAccessTokenAsync(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);

            try
            {
                if (response.StatusCode != System.Net.HttpStatusCode.OK)
                {
                    LogUtils.LogMessage(LogSeverity.WARNING, "CustomOAuth2Authenticator failed to refresh token.", "Error from service: " + text);
                    System.Diagnostics.Debug.Print("Error from service: " + text);
                }
            }
            catch { }

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

            if (data.ContainsKey("error"))
            {
                throw new AuthException("Error authenticating: " + data["error"]);
            }
            //---------------------------------------------------------------------------------------
            /// 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(AccessTokenName))
            //---------------------------------------------------------------------------------------
            {
            }
            else
            {
                //---------------------------------------------------------------------------------------
                /// 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.");
                //---------------------------------------------------------------------------------------
            }

            return(data);
        }
コード例 #9
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>
        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"))
            {
                System.Diagnostics.Debug.WriteLine($"RequestAccessTokenAsync exception {text}");//log actual response from server
                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);
        }
コード例 #10
0
        static async Task <IDictionary <string, string> > RequestAccessTokenAsync(string accessTokenUrl, IDictionary <string, string> queryValues)
        {
            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
            IDictionary <string, string> data = text.Contains("{") ? WebEx.JsonDecode(text) : WebEx.FormDecode(text);

            if (data.ContainsKey("error"))
            {
                throw new AuthException(data["error_description"]);
            }

            return(data);
        }
        protected override void OnRedirectPageLoaded(Uri url, IDictionary <string, string> query, IDictionary <string, string> fragment)
        {
            if (query.ContainsKey("code"))
            {
                var autorizationCode = query["code"];
                var tokenUrl         = GetTokenUrl();
                try
                {
                    using (var client = new HttpClient())
                    {
                        var postBody = new Dictionary <string, string>();
                        postBody.Add("grant_type", "authorization_code");
                        postBody.Add("client_id", this.ClientId);
                        postBody.Add("code_verifier", this.verifier);
                        postBody.Add("redirect_uri", this.RedirectUrl.AbsoluteUri);
                        postBody.Add("code", autorizationCode);
                        var request = new HttpRequestMessage(HttpMethod.Post, tokenUrl);
                        request.Content = new FormUrlEncodedContent(postBody);
                        request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

                        var response = client.SendAsync(request).Result;
                        OnTokenReceived(new EventArgs());
                        response.EnsureSuccessStatusCode();
                        var res  = response.Content.ReadAsStringAsync().Result;
                        var data = res.Contains("{") ? WebEx.JsonDecode(res) : WebEx.FormDecode(res);
                        OnSucceeded(string.Empty, data);
                    }
                }
                catch
                {
                    OnError("An unexpected error occured while getting access token.");
                }
            }
            else
            {
                OnError("The expected authorization code not received");
            }

            base.OnRedirectPageLoaded(url, query, fragment);
        }