예제 #1
0
    public async Task Register()
    {
        using (var http = new HttpClient())
        {
            var formData = new Dictionary <string, string>();
            formData.Add(nameof(name), name);
            formData.Add(ServerAddress.DEVICE_UID, UnityEngine.SystemInfo.deviceUniqueIdentifier);
            formData.Add(nameof(hash), hash);
            formData.Add(nameof(salt), salt);
            formData.Add(nameof(gender), gender);
            formData.Add(nameof(birthday), birthday);

            var registerForm = new FormUrlEncodedContent(formData);

            var response = await http.PostAsync(ServerAddress.RegisterFormAddress, registerForm);

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

            var intResult = Convert.ToInt32(result);

            RegisterCompleted.Invoke((RegisterResult)intResult);

            registerForm.Dispose();
        }
    }
예제 #2
0
        /// <summary>
        /// Sends a PUT type request including the parameters values from
        /// a key value dictionary object
        /// </summary>
        /// <param name="urlBase">Main resource address</param>
        /// <param name="method">Method resource address part</param>
        /// <param name="parameters">Parameters to include in request</param>
        /// <returns>HttpResponseMessage</returns>
        public async Task <HttpResponseMessage> Put(string urlBase, string method, Dictionary <string, string> parameters)
        {
            //Verify http request integrity
            if (!urlBase.IsWebDirectory(out Uri uri) || method.IsNotValid() || parameters.IsNotValid())
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }
            HttpResponseMessage response;

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.BaseAddress = new Uri(urlBase);
                    AddHeaders(client);
                    using (HttpContent content = new FormUrlEncodedContent(parameters))
                    {
                        response = await client.PutAsync(method, content);

                        content.Dispose();
                    }
                    client.Dispose();
                }
            }
            catch (Exception ex)
            {
                response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(JsonConvert.SerializeObject(ex))
                };
            }
            return(response);
        }
예제 #3
0
 protected virtual void Dispose(bool disposing)
 {
     if (!disposed)
     {
         if (disposing)
         {
             if (_http != null)
             {
                 _http.Dispose();
             }
             if (_content != null)
             {
                 _content.Dispose();
             }
             if (_contentForToken != null)
             {
                 _contentForToken.Dispose();
             }
             if (_response != null)
             {
                 _response.Dispose();
             }
         }
     }
     disposed = true;
 }
예제 #4
0
 public void Dispose()
 {
     handler.Dispose();
     client.Dispose();
     content.Dispose();
     response.Dispose();
 }
예제 #5
0
        public async Task <TokenResponse> ValidateTokenAsync(string code, string clientId, string clientSecret, Uri redirectUri)
        {
            var parameters = new KeyValuePair <string, string>[] {
                new KeyValuePair <string, string>("grant_type", "authorization_code"),
                new KeyValuePair <string, string>("code", code),
                new KeyValuePair <string, string>("client_id", clientId),
                new KeyValuePair <string, string>("client_secret", clientSecret),
                new KeyValuePair <string, string>("redirect_uri", redirectUri.AbsoluteUri)
            };

            var formContent = new FormUrlEncodedContent(parameters);
            var request     = new HttpRequestMessage(HttpMethod.Post, "api/oauth2/token")
            {
                Content = formContent
            };

            HttpResponseMessage responseMessage = default;

            try
            {
                responseMessage = await HttpClient.SendAsync(request);

                responseMessage.EnsureSuccessStatusCode();
            }
            catch
            {
                formContent.Dispose();
                request.Dispose();
                responseMessage?.Dispose();

                throw;
            }
            formContent.Dispose();
            request.Dispose();

            var token = JsonSerializer.Deserialize <TokenResponse>(await responseMessage.Content.ReadAsStringAsync());

            responseMessage.Dispose();

            return(token);
        }
예제 #6
0
        protected void WriteRequestBody(HttpRequestMessage httpRequestMessage, object body, MediaTypeHeaderValue contentType)
        {
            if (body is string)
            {
                using (var stringWriter = new StringWriter())
                {
                    stringWriter.Write(body as string);

                    httpRequestMessage.Content = new StringContent(stringWriter.ToString());

                    if (httpRequestMessage.Content.Headers.ContentLength > 0)
                    {
                        httpRequestMessage.Content.Headers.ContentType = contentType;
                    }
                }
            }
            else if (body is IDictionary <string, string> )
            {
                var formContent = new FormUrlEncodedContent(body as IDictionary <string, string>);

                if (ShareFileClient.Logging.IsDebugEnabled)
                {
                    try
                    {
                        var contentAsString = formContent.ReadAsStringAsync();
                    }
                    catch (Exception)
                    {
                        formContent.Dispose();
                        throw;
                    }
                }

                httpRequestMessage.Content = formContent;
            }
            else
            {
                var stringWriter = new StringWriter();
                using (var textWriter = new JsonTextWriter(stringWriter))
                {
                    var serializationWatch = new ActionStopwatch("SerializeRequest", ShareFileClient.Logging, RequestId);
                    ShareFileClient.Serializer.Serialize(textWriter, body);
                    ShareFileClient.Logging.Trace(serializationWatch);

                    httpRequestMessage.Content = new StringContent(stringWriter.ToString());

                    if (httpRequestMessage.Content.Headers.ContentLength > 0)
                    {
                        httpRequestMessage.Content.Headers.ContentType = contentType;
                    }
                }
            }
        }
예제 #7
0
        protected override async Task <OAuthTokenResponse> ExchangeCodeAsync([NotNull] string code, [NotNull] string redirectUri)
        {
            var credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{Options.ClientId}:{Options.ClientSecret}"));

            HttpRequestMessage    request  = null;
            HttpResponseMessage   response = null;
            FormUrlEncodedContent formUrlEncodedContent = null;

            try
            {
                request = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint);
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                request.Headers.Authorization = new AuthenticationHeaderValue("Basic", credentials);

                // When a custom user agent is specified in the options, add it to the request headers
                // to override the default (generic) user agent used by the OAuth2 base middleware.
                if (!string.IsNullOrEmpty(Options.UserAgent))
                {
                    request.Headers.UserAgent.ParseAdd(Options.UserAgent);
                }

                formUrlEncodedContent = new FormUrlEncodedContent(new Dictionary <string, string>
                {
                    ["grant_type"]   = "authorization_code",
                    ["redirect_uri"] = redirectUri,
                    ["code"]         = code
                });
                request.Content = formUrlEncodedContent;

                response = await Backchannel.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, Context.RequestAborted);

                if (!response.IsSuccessStatusCode)
                {
                    Logger.LogError("An error occurred while retrieving an access token: the remote server " +
                                    "returned a {Status} response with the following payload: {Headers} {Body}.",
                                    /* Status: */ response.StatusCode,
                                    /* Headers: */ response.Headers.ToString(),
                                    /* Body: */ await response.Content.ReadAsStringAsync());

                    return(OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token.")));
                }

                var payload = JObject.Parse(await response.Content.ReadAsStringAsync());

                return(OAuthTokenResponse.Success(payload));
            }
            finally
            {
                formUrlEncodedContent?.Dispose();
                request?.Dispose();
                response?.Dispose();
            }
        }
예제 #8
0
        protected override async Task <OAuthTokenResponse> ExchangeCodeAsync([NotNull] string code, [NotNull] string redirectUri)
        {
            HttpRequestMessage    request  = null;
            HttpResponseMessage   response = null;
            FormUrlEncodedContent formUrlEncodedContent = null;

            try
            {
                request = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint);
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                formUrlEncodedContent = new FormUrlEncodedContent(new Dictionary <string, string>
                {
                    ["client_id"]     = Options.ClientId,
                    ["redirect_uri"]  = redirectUri,
                    ["client_secret"] = Options.ClientSecret,
                    ["code"]          = code,
                    ["grant_type"]    = "authorization_code"
                });
                request.Content = formUrlEncodedContent;

                response = await Backchannel.SendAsync(request, Context.RequestAborted);

                if (!response.IsSuccessStatusCode)
                {
                    Logger.LogError("An error occurred while retrieving an access token: the remote server " +
                                    "returned a {Status} response with the following payload: {Headers} {Body}.",
                                    /* Status: */ response.StatusCode,
                                    /* Headers: */ response.Headers.ToString(),
                                    /* Body: */ await response.Content.ReadAsStringAsync());

                    return(OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token.")));
                }

                // Note: Yammer doesn't return a standard OAuth2 response. To make this middleware compatible
                // with the OAuth2 generic middleware, a compliant JSON payload is generated manually.
                // See https://developer.yammer.com/docs/oauth-2 for more information about this process.
                var payload = JObject.Parse(await response.Content.ReadAsStringAsync())["access_token"].Value <JObject>();
                payload["access_token"]  = payload["token"];
                payload["token_type"]    = string.Empty;
                payload["refresh_token"] = string.Empty;
                payload["expires_in"]    = string.Empty;

                return(OAuthTokenResponse.Success(payload));
            }
            finally
            {
                formUrlEncodedContent?.Dispose();
                request?.Dispose();
                response?.Dispose();
            }
        }
예제 #9
0
        public void AddItem(string item)
        {
            var values = new Dictionary <string, string>
            {
                { "name", item }
            };
            var content  = new FormUrlEncodedContent(values);
            var response = client.PostAsync(url, content).Result.Content.ReadAsStringAsync().Result;

            content.Dispose();

            items.Add(JsonConvert.DeserializeObject <Item>(response));
        }
        protected override async Task <OAuthTokenResponse> ExchangeCodeAsync([NotNull] string code, [NotNull] string redirectUri)
        {
            HttpRequestMessage    request  = null;
            HttpResponseMessage   response = null;
            FormUrlEncodedContent formUrlEncodedContent = null;

            try
            {
                request = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint);
                formUrlEncodedContent = new FormUrlEncodedContent(new Dictionary <string, string>
                {
                    ["client_id"]     = Options.ClientId,
                    ["redirect_uri"]  = redirectUri,
                    ["client_secret"] = Options.ClientSecret,
                    ["code"]          = code,
                    ["grant_type"]    = "authorization_code"
                });
                request.Content = formUrlEncodedContent;

                response = await Backchannel.SendAsync(request, Context.RequestAborted);

                if (!response.IsSuccessStatusCode)
                {
                    Logger.LogError("An error occurred while retrieving an access token: the remote server " +
                                    "returned a {Status} response with the following payload: {Headers} {Body}.",
                                    /* Status: */ response.StatusCode,
                                    /* Headers: */ response.Headers.ToString(),
                                    /* Body: */ await response.Content.ReadAsStringAsync());

                    return(OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token.")));
                }

                // Note: StackExchange's token endpoint doesn't return JSON but uses application/x-www-form-urlencoded.
                // Since OAuthTokenResponse expects a JSON payload, a JObject is manually created using the returned values.
                var content = QueryHelpers.ParseQuery(await response.Content.ReadAsStringAsync());

                var payload = new JObject();
                foreach (var item in content)
                {
                    payload[item.Key] = (string)item.Value;
                }

                return(OAuthTokenResponse.Success(payload));
            }
            finally
            {
                formUrlEncodedContent?.Dispose();
                request?.Dispose();
                response?.Dispose();
            }
        }
예제 #11
0
    public async Task Login(string username, string password)
    {
        using (var http = new HttpClient())
        {
            var formContent = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("name", username),
            });

            try
            {
                var req = await http.PostAsync(ServerAddress.LoginFormAddress, formContent);

                var result = await req.Content.ReadAsStringAsync();

                var splittedResult = result.Split('|');

                var intResult = Convert.ToInt32(splittedResult[0]);
                if (intResult != (int)LoginResult.Success)
                {
                    OnLogin?.Invoke(LoginResult.Failed_Username, null, null, Gender.Female);
                    return;
                }

                var hash = splittedResult[1];
                var salt = splittedResult[2];

                var isPasswordValid = HashSalt.VerifyPassword(password, hash, salt);
                if (isPasswordValid == false)
                {
                    OnLogin?.Invoke(LoginResult.Failed_Password, null, null, Gender.Female);
                    return;
                }

                var name     = splittedResult[3];
                var gender   = (Gender)Enum.Parse(typeof(Gender), splittedResult[4]);
                var birthday = splittedResult[5];

                OnLogin?.Invoke(LoginResult.Success, name, birthday, gender);
            }
            catch
            {
                OnLogin?.Invoke(LoginResult.Failed_MySQL, null, null, Gender.Female);
            }


            formContent.Dispose();
        }
    }
        protected override async Task <OAuthTokenResponse> ExchangeCodeAsync([NotNull] string code, [NotNull] string redirectUri)
        {
            HttpRequestMessage    request = null;
            FormUrlEncodedContent formUrlEncodedContent = null;
            HttpResponseMessage   response = null;

            try
            {
                request = new HttpRequestMessage(HttpMethod.Post, Options.TokenEndpoint);
                request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));

                formUrlEncodedContent = new FormUrlEncodedContent(new Dictionary <string, string>
                {
                    ["redirect_uri"]          = redirectUri,
                    ["client_assertion"]      = Options.ClientSecret,
                    ["assertion"]             = code,
                    ["grant_type"]            = "urn:ietf:params:oauth:grant-type:jwt-bearer",
                    ["client_assertion_type"] = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
                });
                request.Content = formUrlEncodedContent;

                response = await Backchannel.SendAsync(request, Context.RequestAborted);

                if (!response.IsSuccessStatusCode)
                {
                    Logger.LogError("An error occurred while retrieving an access token: the remote server " +
                                    "returned a {Status} response with the following payload: {Headers} {Body}.",
                                    /* Status: */ response.StatusCode,
                                    /* Headers: */ response.Headers.ToString(),
                                    /* Body: */ await response.Content.ReadAsStringAsync());

                    return(OAuthTokenResponse.Failed(new Exception("An error occurred while retrieving an access token.")));
                }

                var payload = JObject.Parse(await response.Content.ReadAsStringAsync());

                return(OAuthTokenResponse.Success(payload));
            }
            finally
            {
                formUrlEncodedContent?.Dispose();
                request?.Dispose();
                response?.Dispose();
            }
        }
        public async Task When_ShellSendsPostData_ItsSendItToRegisteredApplication()
        {
            var path     = "path1";
            var shellUri = new Uri(string.Concat(path, "/edit?id=1"), UriKind.Relative);
            var client   = factory.CreateClientWithWebHostBuilder();

            var formContent = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("field1", "value1"),
                new KeyValuePair <string, string>("field2", "value2"),
            });

            var response = await client.PostAsync(shellUri, formContent).ConfigureAwait(false);

            response.EnsureSuccessStatusCode();
            var responseHtml = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

            Assert.Contains("POST, http://www.path1.com/path1/edit, path1, Body, field1=value1, field2=value2", responseHtml, StringComparison.OrdinalIgnoreCase);
            formContent.Dispose();
        }
예제 #14
0
        private void SendCommand(int command)
        {
            string playerUrl = DEFAULT_HOST + ":" + DEFAULT_PORT + COMMANDS;

            var values = new Dictionary <string, string> {
                { "wm_command", command.ToString(CultureInfo.InvariantCulture) }
            };


            try {
#pragma warning disable CA2000 // Dispose objects before losing scope
                var content = new FormUrlEncodedContent(values);

                _ = client.PostAsync(new Uri(playerUrl), content).ContinueWith((requestTask) => {
                    content.Dispose();
                }, TaskScheduler.Current);

#pragma warning restore CA2000 // Dispose objects before losing scope
            } catch { }
        }
예제 #15
0
        /// <summary>
        /// Pobranie danych tokena autoryzującego, używane przy logowaniu
        /// </summary>
        /// <param name="login">Login</param>
        /// <param name="password">Hasło</param>
        /// <returns>Dictionary zawierający dane tokena</returns>
        public Dictionary <string, string> GetToken(string login, string password)
        {
            HttpContent content = new FormUrlEncodedContent(new Dictionary <string, string>()
            {
                { "grant_type", "password" },
                { "username", login },
                { "password", password }
            });

            try
            {
                using (HttpResponseMessage responseMessage = Task.Run(async() => { return(await _httpClient.PostAsync("Token", content)); }).Result)
                {
                    if (responseMessage.StatusCode == HttpStatusCode.OK)
                    {
                        content = responseMessage.Content;
                        string jsonString = Task.Run(async() => { return(await content.ReadAsStringAsync()); }).Result;
                        Dictionary <string, string> tokenData = JsonConvert.DeserializeObject <Dictionary <string, string> >(jsonString);
                        return(tokenData);
                    }
                    else if (responseMessage.StatusCode == HttpStatusCode.BadRequest)
                    {
                        _lastErrorMessage = "Niepoprawne dane logowania";
                    }
                    else
                    {
                        _lastErrorMessage = "Błąd połączenia z serwerem";
                    }
                }
            }
            catch (Exception exc)
            {
                _lastErrorMessage = "Błąd połączenia z serwerem";
            }
            finally
            {
                content.Dispose();
            }

            return(null);
        }
예제 #16
0
    private async Task <string> GetUsers(string keyword)
    {
        // TODO : Handle exception from http

        using (var http = new HttpClient())
        {
            var formValue = new Dictionary <string, string>()
            {
                { "keyword", keyword }
            };

            var form = new FormUrlEncodedContent(formValue);

            var content = await http.PostAsync(ServerAddress.SearchUserFormAdderss, form);

            var result = await content.Content.ReadAsStringAsync();

            form.Dispose();
            return(result);
        }
    }
예제 #17
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
            }

            if (responsibleForClient && client != null)
            {
                client.Dispose();
            }
            if (content != null)
            {
                content.Dispose();
            }

            disposed = true;
        }
예제 #18
0
        public HttpResponseEventArgs Post(string url, Dictionary <string, string> args)
        {
            HttpResponseEventArgs result = new HttpResponseEventArgs();

            try
            {
                // if (executing)
                //     throw new Exception("Another request is executing.");
                if (!Initialized)
                {
                    throw new Exception("Client was not initialized.");
                }
                while (executing)
                {
                    Thread.Sleep(100);
                }
                executing = true;

                var content = new FormUrlEncodedContent(args);
                using (HttpResponseMessage response = http.PostAsync(url, content).Result)
                {
                    result.SuccessfulRequest = response.IsSuccessStatusCode;
                    result.StatusCode        = Convert.ToInt32(response.StatusCode);
                    result.HTMLInString      = response.Content.ReadAsStringAsync().Result;
                }
                content.Dispose();
            }
            catch (Exception ex)
            {
                result.SuccessfulRequest = false;
                result.Message           = ex.Message;
            }
            finally
            {
                executing = false;
            }
            return(result);
        }
예제 #19
0
        } // MAIN CHECKER

        async void Send(string message, string user, string avatar)
        {
            lb_hint.Text         = "Please wait";
            Content.Enabled      = false;
            Username.Enabled     = false;
            Avatar.Enabled       = false;
            webhookinput.Enabled = false;
            messagesend.Enabled  = false;
            try
            {
                var msg = new Dictionary <string, string>
                {
                    { "content", message },
                    { "username", user },
                    { "avatar_url", avatar },
                };
                Content.Text = "";
                FormUrlEncodedContent emsg = new FormUrlEncodedContent(msg);
                HttpResponseMessage   resp = await client.PostAsync(url, emsg);

                emsg.Dispose();
                resp.Dispose();
                msg                  = null;
                lb_hint.Text         = "";
                webhookinput.Enabled = true;
                Content.Enabled      = true;
                Username.Enabled     = true;
                Avatar.Enabled       = true;
                Content.Focus();
            }
            catch (Exception err)
            {
                //MessageBox.Show(err.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                lb_hint.Text      = $"{err.GetType().Name}: {err.Message}";
                lb_hint.ForeColor = Color.Red;
            }
        } // MAIN SENDER
예제 #20
0
        public static async Task <string> GetImagesCode(string id)
        {
            using (var handler = new HttpClientHandler
            {
                CookieContainer = cookies,
                UseProxy = true,
                //Proxy = new WebProxy("proxy.hinet.net", 80),
            })
                using (var client = new HttpClient(handler))
                {
                    client.BaseAddress = new Uri("http://imgspice.com");
                    var content = new FormUrlEncodedContent(new[]
                    {
                        new KeyValuePair <string, string>("op", "my_files"),
                        new KeyValuePair <string, string>("fld_id", "0"),
                        new KeyValuePair <string, string>("key", id),
                        new KeyValuePair <string, string>("create_new_folder", ""),
                        new KeyValuePair <string, string>("pub", "1"),
                        new KeyValuePair <string, string>("pub", "1"),
                        new KeyValuePair <string, string>("to_folder", ""),
                        new KeyValuePair <string, string>("domain", ""),
                    });

                    var fileIds = new List <string>();

                    using (var response = await client.PostAsync("/", content))
                    {
                        var result = await response.Content.ReadAsStringAsync();

                        const string search = "file_id\" value=\"";
                        foreach (var s in result.AllIndexesOf(search))
                        {
                            var start = s + search.Length;
                            var end   = result.IndexOf("\"", start);
                            if (end - start < 10)
                            {
                                fileIds.Add(result.Substring(start, end - start));
                            }
                        }
                    }

                    if (!fileIds.Any())
                    {
                        return(string.Empty);
                    }
                    content.Dispose();

                    var postData = new List <KeyValuePair <string, string> >();
                    postData.Add(new KeyValuePair <string, string>("op", "my_files"));
                    postData.Add(new KeyValuePair <string, string>("fld_id", "0"));
                    postData.Add(new KeyValuePair <string, string>("key", id));
                    postData.Add(new KeyValuePair <string, string>("create_new_folder", ""));
                    foreach (var fileId in fileIds)
                    {
                        postData.Add(new KeyValuePair <string, string>("file_id", fileId));
                        postData.Add(new KeyValuePair <string, string>("pub", "1"));
                    }
                    postData.Add(new KeyValuePair <string, string>("to_folder", ""));
                    postData.Add(new KeyValuePair <string, string>("domain", "http://imgspice.com"));
                    content = new FormUrlEncodedContent(postData);

                    using (var response = await client.PostAsync("/", content))
                    {
                        var result = await response.Content.ReadAsStringAsync();

                        var start = result.IndexOf("All Images : HTML Codes for Sites", 0);
                        if (start >= 0)
                        {
                            start = result.IndexOf("<a href=", start);
                            var end = result.IndexOf("</textarea>", start);
                            if (end >= 0)
                            {
                                return(result.Substring(start, end - start).Replace(Environment.NewLine, "").Replace("\n", ""));
                            }
                        }
                    }
                    return(string.Empty);
                }
        }
예제 #21
0
        /// <summary>
        /// Get an Access Token in order to call an API.
        /// </summary>
        /// <param name="httpClient">A <see cref="HttpClient"/> param.</param>
        /// <param name="endpoint">The OpenId's Endpoint.</param>
        /// <param name="auth0ClientId">The Auth0's client id.</param>
        /// <param name="code">The code received from Auth0.</param>
        /// <param name="audience">The Auth0's audience domain.</param>
        /// <param name="codeVerifier">The code verification token used in the authentication flow</param>
        /// <param name="redirectUri">URL to redirect the user after the logout.</param>
        /// <param name="secret">The Auth0's client secret</param>
        /// <returns>A <see cref="Task{TResult}"/> representing the result of the asynchronous operation.</returns>
        public static async Task <SessionInfo> GetAccessToken(
            HttpClient httpClient,
            string endpoint,
            string auth0ClientId,
            string code,
            string audience          = null,
            string codeVerifier      = null,
            string redirectUri       = null,
            string secret            = null,
            RequestModes requestMode = RequestModes.Json)
        {
            if (httpClient is null)
            {
                throw new ArgumentNullException(nameof(httpClient));
            }

            if (string.IsNullOrEmpty(endpoint))
            {
                throw new ArgumentException(Resources.NullArgumentExceptionError, nameof(endpoint));
            }

            if (string.IsNullOrEmpty(auth0ClientId))
            {
                throw new ArgumentException(Resources.NullArgumentExceptionError, nameof(auth0ClientId));
            }

            if (string.IsNullOrEmpty(codeVerifier) && string.IsNullOrEmpty(secret))
            {
                throw new ArgumentException(Resources.MissingPKCERequiredParamError, $"{nameof(secret)} or {nameof(codeVerifier)}");
            }

            if (!string.IsNullOrEmpty(codeVerifier) && !string.IsNullOrEmpty(secret))
            {
                throw new ArgumentException(Resources.DuplicatedPKCERequiredParamError, $"{nameof(secret)} and {nameof(codeVerifier)}");
            }
            SessionInfo response = null;

            if (RequestModes.Json == requestMode)
            {
                using (HttpContent content = new StringContent(
                           JsonSerializer.Serialize(
                               new
                {
                    grant_type = "authorization_code",
                    client_id = auth0ClientId,
                    audience,
                    code,
                    code_verifier = codeVerifier,
                    redirect_uri = redirectUri,
                    client_secret = secret,
                },
                               new JsonSerializerOptions
                {
                    IgnoreNullValues = true,
                }), Encoding.UTF8,
                           Resources.ApplicationJsonMediaType
                           )
                       )
                {
                    HttpResponseMessage httpResponseMessage = await httpClient.PostAsync($@"{endpoint}", content).ConfigureAwait(false);

                    var responseText = await httpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);

                    if (httpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK)
                    {
                        response = JsonSerializer.Deserialize <SessionInfo>(responseText);
                    }
                }
            }
            else
            {
                var formContent = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair <string, string>("grant_type", "authorization_code"),
                    new KeyValuePair <string, string>("client_id", auth0ClientId),
                    new KeyValuePair <string, string>("audience", audience),
                    new KeyValuePair <string, string>("code", code),
                    new KeyValuePair <string, string>("code_verifier", codeVerifier),
                    new KeyValuePair <string, string>("redirect_uri", redirectUri),
                    new KeyValuePair <string, string>("client_secret", secret),
                });
                HttpResponseMessage httpResponseMessage = await httpClient.PostAsync($@"{endpoint}", formContent).ConfigureAwait(false);

                formContent.Dispose();
                var responseText = await httpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);

                if (httpResponseMessage.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    response = JsonSerializer.Deserialize <SessionInfo>(responseText);
                }
            }

            return(response);
        }
예제 #22
0
파일: PostPage.cs 프로젝트: AkioSarkiz/MBF
        public HttpResponseMessage GetContent(Dictionary <string, string> cookies, string _token, string login, string password)
        {
            var cookieContainer = new CookieContainer();

            using (var handler = new HttpClientHandler()
            {
                //AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.None,
                CookieContainer = cookieContainer,
                Proxy = Proxy
            })

                using (var client = new HttpClient(handler))
                {
                    // установка заголовков
                    client.DefaultRequestHeaders.Add("Connection", "keep-alive");
                    client.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                    client.DefaultRequestHeaders.Add("Accept-Encoding", "gzip, deflate, br");
                    client.DefaultRequestHeaders.Add("Accept-Language", "am,uk;q=0.7,ru;q=0.3");
                    client.DefaultRequestHeaders.Add("Host", "mangalib.me");
                    client.DefaultRequestHeaders.Add("Referer", "https://mangalib.me/login");
                    client.DefaultRequestHeaders.Add("TE", "Trailers");
                    client.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");
                    client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0");

                    // POST данные для отправки
                    var postData = new FormUrlEncodedContent(new[]
                    {
                        new KeyValuePair <string, string>("email", login),
                        new KeyValuePair <string, string>("password", password),
                        new KeyValuePair <string, string>("_token", _token)
                    });

                #if DEBUG
                    Console.WriteLine(Resources.Log8, login, password, _token);
                #endif


                    // Установка куки
                    foreach (var obj in cookies)
                    {
                        cookieContainer.Add(new Uri(BaseUrl), new Cookie(obj.Key, obj.Value));
                    #if DEBUG
                        Console.Write(Resources.Log9, obj.Key, obj.Value);
                    #endif
                    }

                    // запрос
                    HttpResponseMessage response = client.PostAsync(new Uri(RequestUrl), postData).Result;

                    TreatmentPostData treatment = new TreatmentPostData(response);

                    if (treatment.Tests())
                    {
                        Loger.AddSuccess(string.Format(CultureInfo.CurrentCulture, "{0}, {1}", login, password));
                    #if !DEBUG
                        Console.Write("Login: "******";\tPassword: "******"\tStatus: OK");
                    #endif
                    }
                    Console.WriteLine("Login: "******";\tPassword: "******"\tStatus: NOT");
                    Loger.AddLog(string.Format(CultureInfo.CurrentCulture, "{0}, {1}", login, password));

                    postData.Dispose();
                    return(response);
                }
        }