Esempio n. 1
0
        public async Task MultipleFormPostWithingASingleView_AreAllowed()
        {
            // Arrange
            // Do a get request.
            var getResponse = await Client.GetAsync("http://localhost/Antiforgery/Login");

            var responseBody = await getResponse.Content.ReadAsStringAsync();

            // Get the AF token for the second login. If the cookies are generated twice(i.e are different),
            // this AF token will not work with the first cookie.
            var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(
                responseBody,
                "/Antiforgery/UseFacebookLogin");
            var cookieToken = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse);

            var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Antiforgery/Login");

            request.Headers.Add("Cookie", cookieToken.Key + "=" + cookieToken.Value);
            var nameValueCollection = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("__RequestVerificationToken", formToken),
                new KeyValuePair <string, string>("UserName", "abra"),
                new KeyValuePair <string, string>("Password", "cadabra"),
            };

            request.Content = new FormUrlEncodedContent(nameValueCollection);

            // Act
            var response = await Client.SendAsync(request);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal("OK", await response.Content.ReadAsStringAsync());
        }
Esempio n. 2
0
        public async Task ReRegisteringAntiforgeryTokenInsideFormTagHelper_DoesNotAddDuplicateAntiforgeryTokenFields()
        {
            // Arrange
            var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8");
            var outputFile        = "compiler/resources/TagHelpersWebSite.Employee.DuplicateAntiforgeryTokenRegistration.html";
            var expectedContent   =
                await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile : false);

            // Act
            var response = await Client.GetAsync("http://localhost/Employee/DuplicateAntiforgeryTokenRegistration");

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

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(expectedMediaType, response.Content.Headers.ContentType);

            responseContent = responseContent.Trim();

            var forgeryToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(
                responseContent, "/Employee/DuplicateAntiforgeryTokenRegistration");

#if GENERATE_BASELINES
            // Reverse usual substitution and insert a format item into the new file content.
            responseContent = responseContent.Replace(forgeryToken, "{0}");
            ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent);
#else
            expectedContent = string.Format(expectedContent, forgeryToken);
            Assert.Equal(
                expectedContent.Trim(),
                responseContent,
                ignoreLineEndingDifferences: true);
#endif
        }
Esempio n. 3
0
        public async Task PageConventions_CustomizedModelCanPostToHandlers()
        {
            // Arrange
            var getPage = await Client.GetAsync("/CustomModelTypeModel");

            var token  = AntiforgeryTestHelper.RetrieveAntiforgeryToken(await getPage.Content.ReadAsStringAsync(), "");
            var cookie = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getPage);

            var message = new HttpRequestMessage(HttpMethod.Post, "/CustomModelTypeModel");

            message.Content = new FormUrlEncodedContent(new Dictionary <string, string>
            {
                ["__RequestVerificationToken"] = token,
                ["ConfirmPassword"]            = "",
                ["Password"] = "",
                ["Email"]    = ""
            });
            message.Headers.TryAddWithoutValidation("Cookie", $"{cookie.Key}={cookie.Value}");

            // Act
            var response = await Client.SendAsync(message);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            var content = await response.Content.ReadAsStringAsync();

            Assert.Contains("is required.", content);
        }
Esempio n. 4
0
        public async Task SetCookieAndHeaderBeforeFlushAsync_PostToForm()
        {
            // Arrange
            // do a get response.
            var getResponse = await Client.GetAsync("http://localhost/Antiforgery/FlushAsyncLogin");

            var responseBody = await getResponse.Content.ReadAsStringAsync();

            var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(
                responseBody,
                "Antiforgery/FlushAsyncLogin");
            var cookieToken = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse);

            var request = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Antiforgery/FlushAsyncLogin");

            request.Headers.Add("Cookie", cookieToken.Key + "=" + cookieToken.Value);
            var nameValueCollection = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("__RequestVerificationToken", formToken),
                new KeyValuePair <string, string>("UserName", "test"),
                new KeyValuePair <string, string>("Password", "password"),
            };

            request.Content = new FormUrlEncodedContent(nameValueCollection);

            // Act
            var response = await Client.SendAsync(request);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal("OK", await response.Content.ReadAsStringAsync());
        }
Esempio n. 5
0
        public async Task Antiforgery_HeaderNotSet_SendsBadRequest()
        {
            // Arrange
            var getResponse = await Client.GetAsync("http://localhost/Antiforgery/Login");

            var responseBody = await getResponse.Content.ReadAsStringAsync();

            var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(
                responseBody,
                "Antiforgery/Login");

            var request             = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Antiforgery/Login");
            var nameValueCollection = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("__RequestVerificationToken", formToken),
                new KeyValuePair <string, string>("UserName", "test"),
                new KeyValuePair <string, string>("Password", "password"),
            };

            request.Content = new FormUrlEncodedContent(nameValueCollection);

            // Act
            var response = await Client.SendAsync(request);

            // Assert
            Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
        }
Esempio n. 6
0
        public async Task HelloWorldWithPageModelHandler_CanPostContent()
        {
            // Arrange
            var getRequest  = new HttpRequestMessage(HttpMethod.Get, "http://localhost/HelloWorldWithPageModelHandler?message=message");
            var getResponse = await Client.SendAsync(getRequest);

            var getResponseBody = await getResponse.Content.ReadAsStringAsync();

            var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(getResponseBody, "/HelloWorlWithPageModelHandler");
            var cookie    = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse);


            var postRequest = new HttpRequestMessage(HttpMethod.Post, "http://localhost/HelloWorldWithPageModelHandler");

            postRequest.Headers.Add("Cookie", cookie.Key + "=" + cookie.Value);
            postRequest.Headers.Add("RequestVerificationToken", formToken);

            // Act
            var response = await Client.SendAsync(postRequest);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

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

            Assert.StartsWith("Hello, You posted!", content.Trim());
        }
Esempio n. 7
0
        public async Task PageConventions_CustomizedModelCanWorkWithModelState_EnforcesBindRequired()
        {
            // Arrange
            var getPage = await Client.GetAsync("/CustomModelTypeModel?Attempts=0");

            var token  = AntiforgeryTestHelper.RetrieveAntiforgeryToken(await getPage.Content.ReadAsStringAsync(), "");
            var cookie = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getPage);

            var message = new HttpRequestMessage(HttpMethod.Post, "/CustomModelTypeModel")
            {
                Content = new FormUrlEncodedContent(new Dictionary <string, string>
                {
                    ["__RequestVerificationToken"] = token,
                    ["Email"]           = "*****@*****.**",
                    ["Password"]        = "******",
                    ["ConfirmPassword"] = "******",
                })
            };

            message.Headers.TryAddWithoutValidation("Cookie", $"{cookie.Key}={cookie.Value}");

            // Act
            var response = await Client.SendAsync(message);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            var responseText = await response.Content.ReadAsStringAsync();

            Assert.Contains(
                "A value for the &#x27;Attempts&#x27; parameter or property was not provided.",
                responseText);
        }
Esempio n. 8
0
        public async Task PageConventions_CustomizedModelCanWorkWithModelState()
        {
            // Arrange
            var getPage = await Client.GetAsync("/CustomModelTypeModel");

            var token  = AntiforgeryTestHelper.RetrieveAntiforgeryToken(await getPage.Content.ReadAsStringAsync(), "");
            var cookie = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getPage);

            var message = new HttpRequestMessage(HttpMethod.Post, "/CustomModelTypeModel");

            message.Content = new FormUrlEncodedContent(new Dictionary <string, string>
            {
                ["__RequestVerificationToken"] = token,
                ["Email"]           = "*****@*****.**",
                ["Password"]        = "******",
                ["ConfirmPassword"] = "******",
            });
            message.Headers.TryAddWithoutValidation("Cookie", $"{cookie.Key}={cookie.Value}");

            // Act
            var response = await Client.SendAsync(message);

            // Assert
            Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
            Assert.Equal("/", response.Headers.Location.ToString());
        }
Esempio n. 9
0
        private async Task AddAntiforgeryHeaders(HttpRequestMessage request)
        {
            var getResponse = await Client.GetAsync(request.RequestUri);

            Assert.Equal(HttpStatusCode.OK, getResponse.StatusCode);
            var getResponseBody = await getResponse.Content.ReadAsStringAsync();

            var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(getResponseBody, "");
            var cookie    = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse);

            request.Headers.Add("Cookie", cookie.Key + "=" + cookie.Value);
            request.Headers.Add("RequestVerificationToken", formToken);
        }
Esempio n. 10
0
        public async Task HtmlGenerationWebSite_GeneratesExpectedResults(string action, string antiforgeryPath)
        {
            // Arrange
            var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8");
            var outputFile        = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home." + action + ".html";
            var expectedContent   =
                await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile : false);

            // Act
            // The host is not important as everything runs in memory and tests are isolated from each other.
            var response = await Client.GetAsync("http://localhost/HtmlGeneration_Home/" + action);

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

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(expectedMediaType, response.Content.Headers.ContentType);

            responseContent = responseContent.Trim();
            if (antiforgeryPath == null)
            {
#if GENERATE_BASELINES
                ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent);
#else
                // Mono issue - https://github.com/aspnet/External/issues/19
                Assert.Equal(
                    PlatformNormalizer.NormalizeContent(expectedContent.Trim()),
                    responseContent,
                    ignoreLineEndingDifferences: true);
#endif
            }
            else
            {
                var forgeryToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseContent, antiforgeryPath);
#if GENERATE_BASELINES
                // Reverse usual substitution and insert a format item into the new file content.
                responseContent = responseContent.Replace(forgeryToken, "{0}");
                ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent);
#else
                expectedContent = string.Format(expectedContent, forgeryToken);
                // Mono issue - https://github.com/aspnet/External/issues/19
                Assert.Equal(
                    PlatformNormalizer.NormalizeContent(expectedContent.Trim()),
                    responseContent,
                    ignoreLineEndingDifferences: true);
#endif
            }
        }
        public async Task FormTagHelper_WithPageHandler_AllowsPostingToSelf()
        {
            //Arrange
            var expected =
                @"<form action=""/TagHelper/PostWithHandler/Edit"" method=""post""><input name=""__RequestVerificationToken"" type=""hidden"" value=""{0}"" /></form>
<form method=""post"" action=""/TagHelper/PostWithHandler/Edit""><input name=""__RequestVerificationToken"" type=""hidden"" value=""{0}"" /></form>
<form method=""post"" action=""/TagHelper/PostWithHandler/Edit/10""></form>";

            // Act
            var response = await Client.GetStringAsync("/TagHelper/PostWithHandler");

            // Assert
            var responseContent = response.Trim();
            var forgeryToken    = AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseContent, "/TagHelper/PostWithHandler");
            var expectedContent = string.Format(expected, forgeryToken);

            Assert.Equal(expectedContent, responseContent, ignoreLineEndingDifferences: true);
        }
Esempio n. 12
0
        public async Task ValidationTagHelpers_GeneratesExpectedSpansAndDivs()
        {
            // Arrange
            var outputFile      = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Customer.Index.html";
            var expectedContent =
                await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile : false);

            var request             = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Customer/HtmlGeneration_Customer");
            var nameValueCollection = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Number", string.Empty),
                new KeyValuePair <string, string>("Name", string.Empty),
                new KeyValuePair <string, string>("Email", string.Empty),
                new KeyValuePair <string, string>("PhoneNumber", string.Empty),
                new KeyValuePair <string, string>("Password", string.Empty)
            };

            request.Content = new FormUrlEncodedContent(nameValueCollection);

            // Act
            var response = await Client.SendAsync(request);

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

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            responseContent = responseContent.Trim();
            var forgeryToken =
                AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseContent, "Customer/HtmlGeneration_Customer");

#if GENERATE_BASELINES
            // Reverse usual substitution and insert a format item into the new file content.
            responseContent = responseContent.Replace(forgeryToken, "{0}");
            ResourceFile.UpdateFile(_resourcesAssembly, outputFile, expectedContent, responseContent);
#else
            expectedContent = string.Format(expectedContent, forgeryToken);
            // Mono issue - https://github.com/aspnet/External/issues/19
            Assert.Equal(
                PlatformNormalizer.NormalizeContent(expectedContent.Trim()),
                responseContent,
                ignoreLineEndingDifferences: true);
#endif
        }
Esempio n. 13
0
        public async Task Get_ReturnsOkAndAntiforgeryToken(string path)
        {
            // Arrange & Act
            var response = await Client.GetAsync(path);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal("text/html", response.Content.Headers.ContentType.MediaType);

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

            Assert.NotNull(html);
            Assert.NotEmpty(html);

            var token = AntiforgeryTestHelper.RetrieveAntiforgeryToken(html, "/");

            Assert.NotNull(token);
            Assert.NotEmpty(token);
        }
Esempio n. 14
0
        public async Task TempData_TempDataPropertyOnPageModel_PopulatesTempData()
        {
            // Arrange 1
            var getRequest  = new HttpRequestMessage(HttpMethod.Get, "http://localhost/TempData/TempDataPageModelProperty");
            var getResponse = await Client.SendAsync(getRequest);

            var getResponseBody = await getResponse.Content.ReadAsStringAsync();

            var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(getResponseBody, "/TempData/TempDataPageModelProperty");
            var cookie    = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse);

            var url     = "http://localhost/TempData/TempDataPageModelProperty";
            var request = new HttpRequestMessage(HttpMethod.Post, url);

            request.Headers.Add("Cookie", cookie.Key + "=" + cookie.Value);
            request.Headers.Add("RequestVerificationToken", formToken);

            // Act 1
            var response = await Client.SendAsync(request);

            // Assert 1
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            var content = await response.Content.ReadAsStringAsync();

            Assert.StartsWith("Message: Secret post", content.Trim());
            Assert.EndsWith("TempData:", content.Trim());

            // Arrange 2
            request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/TempData/TempDataPageModelProperty");
            request.Headers.Add("Cookie", GetCookie(response));

            // Act 2
            response = await Client.SendAsync(request);

            // Assert 2
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            content = await response.Content.ReadAsStringAsync();

            Assert.StartsWith("Message: Secret post", content.Trim());
            Assert.EndsWith("TempData: Secret post", content.Trim());
        }
Esempio n. 15
0
        public async Task Post_ReturnsOkAndNewPerson(string path)
        {
            // Arrange & Act 1
            var html = await Client.GetStringAsync(path);

            // Assert 1 (guard)
            Assert.NotEmpty(html);

            // Arrange 2
            var token = AntiforgeryTestHelper.RetrieveAntiforgeryToken(html, "/");
            var name  = Guid.NewGuid().ToString();

            name = name.Substring(startIndex: 0, length: name.LastIndexOf('-'));
            var form = new Dictionary <string, string>
            {
                { "__RequestVerificationToken", token },
                { "Age", "12" },
                { "BirthDate", "2006-03-01T09:51:43.041-07:00" },
                { "Name", name },
            };

            var content = new FormUrlEncodedContent(form);
            var request = new HttpRequestMessage(HttpMethod.Post, path)
            {
                Content = content,
            };

            // Act 2
            var response = await Client.SendAsync(request);

            // Assert 2
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

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

            Assert.NotNull(body);
            Assert.Contains($@"value=""{name}""", body);
        }
Esempio n. 16
0
        public async Task PageModel_Handler_ReturnTypeImplementsIActionResult()
        {
            // Arrange
            var getResponse = await Client.GetAsync("http://localhost/ModelHandlerTestPage");

            var getResponseBody = await getResponse.Content.ReadAsStringAsync();

            var formToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(getResponseBody, "/ModelHandlerTestPage");
            var cookie    = AntiforgeryTestHelper.RetrieveAntiforgeryCookie(getResponse);

            var postRequest = new HttpRequestMessage(HttpMethod.Post, "http://localhost/ModelHandlerTestPage/CustomActionResult");

            postRequest.Headers.Add("Cookie", cookie.Key + "=" + cookie.Value);
            postRequest.Headers.Add("RequestVerificationToken", formToken);
            // Act
            var response = await Client.SendAsync(postRequest);

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            var content = await response.Content.ReadAsStringAsync();

            Assert.Equal("CustomActionResult", content);
        }
Esempio n. 17
0
        public async Task ReRegisteringAntiforgeryTokenInsideFormTagHelper_DoesNotAddDuplicateAntiforgeryTokenFields()
        {
            // Arrange
            var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8");
            var outputFile        = "compiler/resources/TagHelpersWebSite.Employee.DuplicateAntiforgeryTokenRegistration.html";
            var expectedContent   =
                await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile : false);

            // Act
            var response = await Client.GetAsync("http://localhost/Employee/DuplicateAntiforgeryTokenRegistration");

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

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(expectedMediaType, response.Content.Headers.ContentType);

            responseContent = responseContent.Trim();

            var forgeryToken = AntiforgeryTestHelper.RetrieveAntiforgeryToken(
                responseContent, "/Employee/DuplicateAntiforgeryTokenRegistration");

            ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent, forgeryToken);
        }
Esempio n. 18
0
        public async Task HtmlGenerationWebSite_GenerateEncodedResults(string action, string antiforgeryPath)
        {
            // Arrange
            var expectedMediaType = MediaTypeHeaderValue.Parse("text/html; charset=utf-8");
            var outputFile        = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Home." + action + ".Encoded.html";
            var expectedContent   =
                await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile : false);

            // Act
            // The host is not important as everything runs in memory and tests are isolated from each other.
            var response = await EncodedClient.GetAsync("http://localhost/HtmlGeneration_Home/" + action);

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

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);
            Assert.Equal(expectedMediaType, response.Content.Headers.ContentType);

            responseContent = responseContent.Trim();
            if (antiforgeryPath == null)
            {
                ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent);
            }
            else
            {
                ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent, token: AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseContent, antiforgeryPath));
            }
        }
Esempio n. 19
0
        public async Task ValidationTagHelpers_GeneratesExpectedSpansAndDivs()
        {
            // Arrange
            var outputFile      = "compiler/resources/HtmlGenerationWebSite.HtmlGeneration_Customer.Index.html";
            var expectedContent =
                await ResourceFile.ReadResourceAsync(_resourcesAssembly, outputFile, sourceFile : false);

            var request             = new HttpRequestMessage(HttpMethod.Post, "http://localhost/Customer/HtmlGeneration_Customer");
            var nameValueCollection = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Number", string.Empty),
                new KeyValuePair <string, string>("Name", string.Empty),
                new KeyValuePair <string, string>("Email", string.Empty),
                new KeyValuePair <string, string>("PhoneNumber", string.Empty),
                new KeyValuePair <string, string>("Password", string.Empty)
            };

            request.Content = new FormUrlEncodedContent(nameValueCollection);

            // Act
            var response = await Client.SendAsync(request);

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

            // Assert
            Assert.Equal(HttpStatusCode.OK, response.StatusCode);

            responseContent = responseContent.Trim();
            ResourceFile.UpdateOrVerify(_resourcesAssembly, outputFile, expectedContent, responseContent, token: AntiforgeryTestHelper.RetrieveAntiforgeryToken(responseContent, "Customer/HtmlGeneration_Customer"));
        }