public async Task Credentials_ServerChallengesWithWindowsAuth_ClientSendsWindowsAuthHeader(string authScheme)
        {
            await LoopbackServerFactory.CreateClientAndServerAsync(
                async uri =>
            {
                using (HttpClientHandler handler = CreateHttpClientHandler())
                    using (HttpClient client = CreateHttpClient(handler))
                    {
                        handler.Credentials = new NetworkCredential("username", "password");
                        await client.GetAsync(uri);
                    }
            },
                async server =>
            {
                var responseHeader          = new HttpHeaderData[] { new HttpHeaderData("Www-authenticate", authScheme) };
                HttpRequestData requestData = await server.HandleRequestAsync(
                    HttpStatusCode.Unauthorized, responseHeader);
                Assert.Equal(0, requestData.GetHeaderValueCount("Authorization"));

                requestData            = await server.HandleRequestAsync();
                string authHeaderValue = requestData.GetSingleHeaderValue("Authorization");
                Assert.Contains(authScheme, authHeaderValue);
                _output.WriteLine(authHeaderValue);
            });
        }
        public async Task TestGetFromJsonAsync()
        {
            const string          json    = @"{""Name"":""David"",""Age"":24}";
            HttpHeaderData        header  = new HttpHeaderData("Content-Type", "application/json");
            List <HttpHeaderData> headers = new List <HttpHeaderData> {
                header
            };

            await HttpMessageHandlerLoopbackServer.CreateClientAndServerAsync(
                async (handler, uri) =>
            {
                using (HttpClient client = new HttpClient(handler))
                {
                    Person per = (Person)await client.GetFromJsonAsync(uri, typeof(Person));
                    per.Validate();

                    per = (Person)await client.GetFromJsonAsync(uri.ToString(), typeof(Person));
                    per.Validate();

                    per = await client.GetFromJsonAsync <Person>(uri);
                    per.Validate();

                    per = await client.GetFromJsonAsync <Person>(uri.ToString());
                    per.Validate();
                }
            },
                server => server.HandleRequestAsync(content: json, headers: headers));
        }
Esempio n. 3
0
        public async Task GetAsync_EmptyResponseHeader_Success()
        {
            IList <HttpHeaderData> headers = new HttpHeaderData[] {
                new HttpHeaderData("Date", $"{DateTimeOffset.UtcNow:R}"),
                new HttpHeaderData("x-empty", ""),
                new HttpHeaderData("x-last", "bye")
            };

            await LoopbackServerFactory.CreateClientAndServerAsync(async uri =>
            {
                using (HttpClient client = CreateHttpClient())
                {
                    HttpResponseMessage response = await client.GetAsync(uri).ConfigureAwait(false);
                    Assert.Equal(headers.Count, response.Headers.Count());
                    Assert.NotNull(response.Headers.GetValues("x-empty"));
                }
            },
                                                                   async server =>
            {
                await server.AcceptConnectionAsync(async connection =>
                {
                    await connection.ReadRequestDataAsync();
                    await connection.SendResponseAsync(HttpStatusCode.OK, headers);
                });
            });
        }
        public async Task TestGetFromJsonAsync()
        {
            const string          json        = @"{""Name"":""David"",""Age"":24}";
            const int             NumRequests = 4;
            HttpHeaderData        header      = new HttpHeaderData("Content-Type", "application/json");
            List <HttpHeaderData> headers     = new List <HttpHeaderData> {
                header
            };

            await LoopbackServer.CreateClientAndServerAsync(
                async uri =>
            {
                using (HttpClient client = new HttpClient())
                {
                    Person per = (Person)await client.GetFromJsonAsync(uri, typeof(Person));
                    per.Validate();

                    per = (Person)await client.GetFromJsonAsync(uri.ToString(), typeof(Person));
                    per.Validate();

                    per = await client.GetFromJsonAsync <Person>(uri);
                    per.Validate();

                    per = await client.GetFromJsonAsync <Person>(uri.ToString());
                    per.Validate();
                }
            },
                async server =>
            {
                for (int i = 0; i < NumRequests; i++)
                {
                    await server.HandleRequestAsync(content: json, headers: headers);
                }
            });
        }
Esempio n. 5
0
        public async Task HPack_HeaderEncoding(string headerName, string expectedValue, byte[] expectedEncoding)
        {
            await Http2LoopbackServer.CreateClientAndServerAsync(
                async uri =>
            {
                using HttpClient client = CreateHttpClient();

                using HttpRequestMessage request = new HttpRequestMessage();
                request.Method     = HttpMethod.Post;
                request.RequestUri = uri;
                request.Version    = HttpVersion.Version20;
                request.Content    = new StringContent("testing 123");
                request.Headers.Add(LiteralHeaderName, LiteralHeaderValue);

                (await client.SendAsync(request)).Dispose();
            },
                async server =>
            {
                Http2LoopbackConnection connection          = await server.EstablishConnectionAsync();
                (int streamId, HttpRequestData requestData) = await connection.ReadAndParseRequestHeaderAsync();

                HttpHeaderData header = requestData.Headers.Single(x => x.Name == headerName);
                Assert.Equal(expectedValue, header.Value);
                Assert.True(expectedEncoding.AsSpan().SequenceEqual(header.Raw));

                await connection.SendDefaultResponseAsync(streamId);
            });
        }
Esempio n. 6
0
        private void ValidateRequest(HttpRequestData requestData, string expectedMethod)
        {
            HttpHeaderData contentType = requestData.Headers.Where(x => x.Name == "Content-Type").First();

            Assert.Equal("application/json; charset=utf-8", contentType.Value);
            Assert.Equal(expectedMethod, requestData.Method);
        }
        public async Task Credentials_ServerChallengesWithWindowsAuth_ClientSendsWindowsAuthHeader(string authScheme)
        {
#if WINHTTPHANDLER_TEST
            if (UseVersion > HttpVersion.Version11)
            {
                throw new SkipTestException($"Test doesn't support {UseVersion} protocol.");
            }
#endif
            await LoopbackServerFactory.CreateClientAndServerAsync(
                async uri =>
            {
                using (HttpClientHandler handler = CreateHttpClientHandler())
                    using (HttpClient client = CreateHttpClient(handler))
                    {
                        handler.Credentials = new NetworkCredential("username", "password");
                        await client.GetAsync(uri);
                    }
            },
                async server =>
            {
                var responseHeader          = new HttpHeaderData[] { new HttpHeaderData("Www-authenticate", authScheme) };
                HttpRequestData requestData = await server.HandleRequestAsync(
                    HttpStatusCode.Unauthorized, responseHeader);
                Assert.Equal(0, requestData.GetHeaderValueCount("Authorization"));

                requestData            = await server.HandleRequestAsync();
                string authHeaderValue = requestData.GetSingleHeaderValue("Authorization");
                Assert.Contains(authScheme, authHeaderValue);
                _output.WriteLine(authHeaderValue);
            });
        }
Esempio n. 8
0
        public async Task Credentials_BrokenNtlmFromServer()
        {
            if (IsWinHttpHandler && UseVersion >= HttpVersion20.Value)
            {
                return;
            }

            await LoopbackServer.CreateClientAndServerAsync(
                async uri =>
            {
                using (HttpClientHandler handler = CreateHttpClientHandler())
                    using (HttpClient client = CreateHttpClient(handler))
                    {
                        handler.Credentials = new NetworkCredential("username", "password");
                        var response        = await client.GetAsync(uri);
                        Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
                    }
            },
                async server =>
            {
                var responseHeader          = new HttpHeaderData[] { new HttpHeaderData("WWW-Authenticate", "NTLM") };
                HttpRequestData requestData = await server.HandleRequestAsync(HttpStatusCode.Unauthorized, responseHeader);
                Assert.Equal(0, requestData.GetHeaderValueCount("Authorization"));

                // Establish a session connection
                using var connection   = await server.EstablishConnectionAsync();
                requestData            = await connection.ReadRequestDataAsync();
                string authHeaderValue = requestData.GetSingleHeaderValue("Authorization");
                Assert.Contains("NTLM", authHeaderValue);
                _output.WriteLine(authHeaderValue);

                // Incorrect NTLMv1 challenge from server (generated by Cyrus HTTP)
                responseHeader = new HttpHeaderData[] {
                    new HttpHeaderData("WWW-Authenticate", "NTLM TlRMTVNTUAACAAAAHAAcADAAAACV/wIAUwCrhitz1vsAAAAAAAAAAAAAAAAAAAAASgAuAEUATQBDAEwASQBFAE4AVAAuAEMATwBNAA=="),
                    new HttpHeaderData("Connection", "keep-alive")
                };
                await connection.SendResponseAsync(HttpStatusCode.Unauthorized, responseHeader);
                connection.CompleteRequestProcessing();

                // Wait for the client to close the connection
                try
                {
                    CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(1000);
                    await connection.WaitForCloseAsync(cancellationTokenSource.Token);
                }
                catch (OperationCanceledException)
                {
                    // On Linux the GSSAPI NTLM provider may try to continue with the authentication, so go along with it
                    requestData     = await connection.ReadRequestDataAsync();
                    authHeaderValue = requestData.GetSingleHeaderValue("Authorization");
                    Assert.Contains("NTLM", authHeaderValue);
                    _output.WriteLine(authHeaderValue);
                    await connection.SendResponseAsync(HttpStatusCode.Unauthorized);
                    connection.CompleteRequestProcessing();
                }
            });
        }
        public ActionResult GetHttpHeaders(HttpHeaderData data)
        {
            // This is an example to demonstrate IValueProvider and ValueProviderFactory
            // You may create your own way how to map Model.
            // When MVC can find a correct ValueProviderFactory, it will not go next factory.

            // ValueProvider provides how data is bind with default model binding.


            var userAgent = data.UserAgent;

            return(View());
        }
Esempio n. 10
0
        public async Task TestGetFromJsonAsync(string json, bool containsQuotedNumbers)
        {
            HttpHeaderData        header  = new HttpHeaderData("Content-Type", "application/json");
            List <HttpHeaderData> headers = new List <HttpHeaderData> {
                header
            };

            await HttpMessageHandlerLoopbackServer.CreateClientAndServerAsync(
                async (handler, uri) =>
            {
                using (HttpClient client = new HttpClient(handler))
                {
                    Person per = (Person)await client.GetFromJsonAsync(uri, typeof(Person));
                    per.Validate();

                    per = (Person)await client.GetFromJsonAsync(uri.ToString(), typeof(Person));
                    per.Validate();

                    per = await client.GetFromJsonAsync <Person>(uri);
                    per.Validate();

                    per = await client.GetFromJsonAsync <Person>(uri.ToString());
                    per.Validate();

                    if (!containsQuotedNumbers)
                    {
                        per = (Person)await client.GetFromJsonAsync(uri, typeof(Person), JsonContext.Default);
                        per.Validate();

                        per = (Person)await client.GetFromJsonAsync(uri.ToString(), typeof(Person), JsonContext.Default);
                        per.Validate();

                        per = await client.GetFromJsonAsync <Person>(uri, JsonContext.Default.Person);
                        per.Validate();

                        per = await client.GetFromJsonAsync <Person>(uri.ToString(), JsonContext.Default.Person);
                        per.Validate();
                    }
                }
            },
                server => server.HandleRequestAsync(content: json, headers: headers));
        }
        public async Task SendAsync_Expires_Success(string value, bool isValid)
        {
            await LoopbackServerFactory.CreateClientAndServerAsync(async uri =>
            {
                using (var client = CreateHttpClient())
                {
                    var message = new HttpRequestMessage(HttpMethod.Get, uri);
                    HttpResponseMessage response = await client.SendAsync(message);
                    Assert.NotNull(response.Content.Headers.Expires);
                    // Invalid date should be converted to MinValue so everything is expired.
                    Assert.Equal(isValid ? DateTime.Parse(value) : DateTimeOffset.MinValue, response.Content.Headers.Expires);
                }
            },
                                                                   async server =>
            {
                IList <HttpHeaderData> headers = new HttpHeaderData[] { new HttpHeaderData("Expires", value) };

                HttpRequestData requestData = await server.HandleRequestAsync(HttpStatusCode.OK, headers);
            });
        }
Esempio n. 12
0
        public async Task SendAsync_RequestHeaderInResponse_Success(string name, string value)
        {
            await LoopbackServerFactory.CreateClientAndServerAsync(async uri =>
            {
                using (HttpClient client = CreateHttpClient())
                {
                    var message = new HttpRequestMessage(HttpMethod.Get, uri)
                    {
                        Version = UseVersion
                    };
                    HttpResponseMessage response = await client.SendAsync(TestAsync, message);

                    Assert.Equal(value, response.Headers.GetValues(name).First());
                }
            },
                                                                   async server =>
            {
                IList <HttpHeaderData> headers = new HttpHeaderData[] { new HttpHeaderData(name, value) };

                HttpRequestData requestData = await server.HandleRequestAsync(HttpStatusCode.OK, headers);
            });
        }
        public async Task GetAsync_EmptyResponseHeader_Success()
        {
            IList <HttpHeaderData> headers = new HttpHeaderData[] {
                new HttpHeaderData("x-test", "SendAsync_EmptyHeader_Success"),
                new HttpHeaderData("x-empty", ""),
                new HttpHeaderData("x-last", "bye")
            };

            await LoopbackServerFactory.CreateClientAndServerAsync(async uri =>
            {
                using (HttpClient client = CreateHttpClient())
                {
                    HttpResponseMessage response = await client.GetAsync(uri).ConfigureAwait(false);
                    // HTTP/1.1 LoopbackServer adds Connection: close and Date to responses.
                    Assert.Equal(UseHttp2LoopbackServer ?  headers.Count : headers.Count + 2, response.Headers.Count());
                    Assert.NotNull(response.Headers.GetValues("x-empty"));
                }
            },
                                                                   async server =>
            {
                HttpRequestData requestData = await server.HandleRequestAsync(HttpStatusCode.OK, headers);
            });
        }