private static SetCookieHeaderValue RetrieveAntiforgeryCookie(HttpResponseMessage response) { return(response.Headers.GetValues(HeaderNames.SetCookie) .Select(setCookieValue => SetCookieHeaderValue.Parse(setCookieValue)) .Where(setCookieHeaderValue => setCookieHeaderValue.Name.StartsWith(".AspNetCore.Antiforgery.", StringComparison.Ordinal)) .FirstOrDefault()); }
public async Task CookieTempDataProviderCookie_DoesNotSetsSecureAttributeOnCookie(bool secureRequest) { // Arrange var protocol = secureRequest ? "https" : "http"; var nameValueCollection = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("value", "Foo"), }; var content = new FormUrlEncodedContent(nameValueCollection); // Act var response = await Client.PostAsync($"{protocol}://localhost/TempData/SetTempData", content); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.True(response.Headers.TryGetValues(HeaderNames.SetCookie, out IEnumerable <string> setCookieValues)); var setCookieHeader = setCookieValues .Select(setCookieValue => SetCookieHeaderValue.Parse(setCookieValue)) .FirstOrDefault(setCookieHeaderValue => setCookieHeaderValue.Name == CookieTempDataProvider.CookieName); Assert.NotNull(setCookieHeader); Assert.Equal("/", setCookieHeader.Path); Assert.Null(setCookieHeader.Domain.Value); Assert.False(setCookieHeader.Secure); Assert.Null(setCookieHeader.Expires); }
public void LoadTempData_ReturnsEmptyDictionary_AndClearsCookie_WhenDataIsInvalid() { // Arrange var dataProtector = new Mock <IDataProtector>(MockBehavior.Strict); dataProtector .Setup(d => d.Unprotect(It.IsAny <byte[]>())) .Throws(new Exception()); var tempDataProvider = GetProvider(dataProtector.Object); var expectedDataToUnprotect = Bytes; var base64AndUrlEncodedDataInCookie = WebEncoders.Base64UrlEncode(expectedDataToUnprotect); var context = new DefaultHttpContext(); context.Request.Cookies = new RequestCookieCollection(new Dictionary <string, string>() { { CookieTempDataProvider.CookieName, base64AndUrlEncodedDataInCookie } }); // Act var tempDataDictionary = tempDataProvider.LoadTempData(context); // Assert Assert.Empty(tempDataDictionary); var setCookieHeader = SetCookieHeaderValue.Parse(context.Response.Headers["Set-Cookie"].ToString()); Assert.Equal(CookieTempDataProvider.CookieName, setCookieHeader.Name.ToString()); Assert.Equal(string.Empty, setCookieHeader.Value.ToString()); }
public void SetCookieHeaderValue_Parse_AcceptsValidValues(SetCookieHeaderValue cookie, string expectedValue) { var header = SetCookieHeaderValue.Parse(expectedValue); Assert.Equal(cookie, header); Assert.Equal(expectedValue, header.ToString()); }
private static SetCookieHeaderValue RetrieveAntiforgeryToken(HttpResponseMessage response) { return(response.Headers.GetValues(HeaderNames.SetCookie) .Select(setCookieValue => SetCookieHeaderValue.Parse(setCookieValue)) .Where(setCookieHeaderValue => setCookieHeaderValue.Name == "XSRF-TOKEN") .FirstOrDefault()); }
public async Task RoundTripLargeData_WorksWithChunkingCookies(int size) { // Arrange var character = 'a'; var expected = new string(character, size); // Act 1 var response = await Client.GetAsync($"/TempData/SetLargeValueInTempData?size={size}&character={character}"); // Assert 1 Assert.Equal(HttpStatusCode.OK, response.StatusCode); IEnumerable <string> setCookieValues; Assert.True(response.Headers.TryGetValues(HeaderNames.SetCookie, out setCookieValues)); setCookieValues = setCookieValues.Where(cookie => cookie.Contains(CookieTempDataProvider.CookieName)); Assert.NotEmpty(setCookieValues); // Verify that all the cookies from CookieTempDataProvider are within the maximum size foreach (var cookie in setCookieValues) { Assert.True(cookie.Length <= ChunkingCookieManager.DefaultChunkSize); } var cookieTempDataProviderCookies = setCookieValues .Select(setCookieValue => SetCookieHeaderValue.Parse(setCookieValue)); foreach (var cookieTempDataProviderCookie in cookieTempDataProviderCookies) { Assert.NotNull(cookieTempDataProviderCookie.Value); Assert.Equal("/", cookieTempDataProviderCookie.Path); Assert.Null(cookieTempDataProviderCookie.Domain); Assert.False(cookieTempDataProviderCookie.Secure); } // Act 2 response = await Client.SendAsync(GetRequest("/TempData/GetLargeValueFromTempData", response)); // Assert 2 Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); Assert.Equal(expected, body); Assert.True(response.Headers.TryGetValues(HeaderNames.SetCookie, out setCookieValues)); var setCookieHeaderValue = setCookieValues .Select(setCookieValue => SetCookieHeaderValue.Parse(setCookieValue)) .FirstOrDefault(setCookieHeader => setCookieHeader.Name == CookieTempDataProvider.CookieName); Assert.NotNull(setCookieHeaderValue); Assert.Equal(string.Empty, setCookieHeaderValue.Value); Assert.Equal("/", setCookieHeaderValue.Path); Assert.Null(setCookieHeaderValue.Domain); Assert.NotNull(setCookieHeaderValue.Expires); Assert.True(setCookieHeaderValue.Expires < DateTimeOffset.Now); // expired cookie // Act 3 response = await Client.SendAsync(GetRequest("/TempData/GetLargeValueFromTempData", response)); // Assert 3 Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); }
public static SetCookieHeaderValue[] GetCookies(this HttpResponseHeaders headers) { return(headers .Where(header => header.Key == "Set-Cookie") .SelectMany(header => header.Value) .Select(value => SetCookieHeaderValue.Parse(value)) .ToArray()); }
private static string ExtractAntiForgeryCookieValueFrom(HttpResponseMessage AResponse) { var LAntiForgeryCookie = AResponse.Headers.GetValues("Set-Cookie").FirstOrDefault(AHeaders => AHeaders.Contains(ANTI_FORGERY_COOKIE_NAME)); if (LAntiForgeryCookie is null) { throw new ArgumentException($@"Cookie '{ANTI_FORGERY_COOKIE_NAME}' not found in HTTP response", nameof(AResponse)); } return(SetCookieHeaderValue.Parse(LAntiForgeryCookie).Value.ToString()); }
public async Task CookiePolicyAppliesToCookieAuthChunks() { var builder = new WebHostBuilder() .ConfigureServices(services => { services.AddAuthentication().AddCookie(o => { o.Cookie.Name = "TestCookie"; o.Cookie.HttpOnly = false; o.Cookie.SecurePolicy = CookieSecurePolicy.None; }); }) .Configure(app => { app.UseCookiePolicy(new CookiePolicyOptions { HttpOnly = HttpOnlyPolicy.Always, Secure = CookieSecurePolicy.Always, }); app.UseAuthentication(); app.Run(context => { return(context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity(new string('c', 1024 * 5), "Cookies"))))); }); }); var server = new TestServer(builder); var transaction = await server.SendAsync("http://example.com/login"); Assert.NotNull(transaction.SetCookie); Assert.Equal(3, transaction.SetCookie.Count); var cookie = SetCookieHeaderValue.Parse(transaction.SetCookie[0]); Assert.Equal("TestCookie", cookie.Name); Assert.Equal("chunks-2", cookie.Value); Assert.True(cookie.HttpOnly); Assert.True(cookie.Secure); Assert.Equal("/", cookie.Path); cookie = SetCookieHeaderValue.Parse(transaction.SetCookie[1]); Assert.Equal("TestCookieC1", cookie.Name); Assert.True(cookie.HttpOnly); Assert.True(cookie.Secure); Assert.Equal("/", cookie.Path); cookie = SetCookieHeaderValue.Parse(transaction.SetCookie[2]); Assert.Equal("TestCookieC2", cookie.Name); Assert.True(cookie.HttpOnly); Assert.True(cookie.Secure); Assert.Equal("/", cookie.Path); }
private static string ExtractAntiForgeryCookieValueFrom(HttpResponseMessage response) { string antiForgeryCookie = response.Headers.GetValues("Set-Cookie") .FirstOrDefault(v => v.Contains(AntiForgeryCookieName)); if (antiForgeryCookie is null) { throw new ArgumentException($"Cookie '{AntiForgeryCookieName}' not found in HttpResponse", nameof(response)); } return(SetCookieHeaderValue.Parse(antiForgeryCookie).Value.ToString()); }
private static string ExtractAntiForgeryCookieValueFrom(HttpResponseMessage response) { string antiForgeryCookie = response.Headers.GetValues("Set-Cookie").ToList()[0]; if (antiForgeryCookie is null) { throw new ArgumentException($"Cookie '{AntiForgeryCookieName}' not found in HTTP response", nameof(response)); } string antiForgeryCookieValue = SetCookieHeaderValue.Parse(antiForgeryCookie).Value.ToString(); return(antiForgeryCookieValue); }
public async Task Redirect_RetainsTempData_EvenIfAccessed_AndSetsAppropriateCookieValues() { // Arrange var nameValueCollection = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("value", "Foo"), }; var content = new FormUrlEncodedContent(nameValueCollection); // Act 1 var response = await Client.PostAsync("/TempData/SetTempData", content); // Assert 1 Assert.Equal(HttpStatusCode.OK, response.StatusCode); IEnumerable <string> setCookieValues; Assert.True(response.Headers.TryGetValues(HeaderNames.SetCookie, out setCookieValues)); var setCookieHeader = setCookieValues .Select(setCookieValue => SetCookieHeaderValue.Parse(setCookieValue)) .FirstOrDefault(setCookieHeaderValue => setCookieHeaderValue.Name == CookieTempDataProvider.CookieName); Assert.NotNull(setCookieHeader); Assert.Equal("/", setCookieHeader.Path); Assert.Null(setCookieHeader.Domain); Assert.False(setCookieHeader.Secure); Assert.Null(setCookieHeader.Expires); // Act 2 var redirectResponse = await Client.SendAsync(GetRequest("/TempData/GetTempDataAndRedirect", response)); // Assert 2 Assert.Equal(HttpStatusCode.Redirect, redirectResponse.StatusCode); // Act 3 response = await Client.SendAsync(GetRequest(redirectResponse.Headers.Location.ToString(), response)); // Assert 3 Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); Assert.Equal("Foo", body); Assert.True(response.Headers.TryGetValues(HeaderNames.SetCookie, out setCookieValues)); setCookieHeader = setCookieValues .Select(setCookieValue => SetCookieHeaderValue.Parse(setCookieValue)) .FirstOrDefault(setCookieHeaderValue => setCookieHeaderValue.Name == CookieTempDataProvider.CookieName); Assert.NotNull(setCookieHeader); Assert.Equal(string.Empty, setCookieHeader.Value); Assert.Equal("/", setCookieHeader.Path); Assert.Null(setCookieHeader.Domain); Assert.NotNull(setCookieHeader.Expires); Assert.True(setCookieHeader.Expires < DateTimeOffset.Now); // expired cookie }
private string ExtractAntiForgeryCookieValueFrom(HttpResponseMessage response) { var antiForgeryCookie = response.Headers.GetValues("Set-Cookie").FirstOrDefault(x => x.Contains(AntiForgeryCookieName)); if (antiForgeryCookie is null) { throw new ArgumentException($"Cookie '{AntiForgeryCookieName}' not found in HTTP response", nameof(response)); } var antiForgeryCookieValue = SetCookieHeaderValue.Parse(antiForgeryCookie).Value; return(antiForgeryCookieValue.Value); }
public async Task CookiePolicyAppliesToCookieAuth() { using var host = new HostBuilder() .ConfigureWebHost(webHostBuilder => { webHostBuilder .Configure(app => { app.UseCookiePolicy(new CookiePolicyOptions { HttpOnly = HttpOnlyPolicy.Always, Secure = CookieSecurePolicy.Always, OnAppendCookie = c => c.CookieOptions.Extensions.Add("extension") }); app.UseAuthentication(); app.Run(context => { return(context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(new ClaimsIdentity(new GenericIdentity("TestUser", "Cookies"))))); }); }) .UseTestServer(); }) .ConfigureServices(services => { services.AddAuthentication().AddCookie(o => { o.Cookie.Name = "TestCookie"; o.Cookie.HttpOnly = false; o.Cookie.SecurePolicy = CookieSecurePolicy.None; }); }) .Build(); var server = host.GetTestServer(); await host.StartAsync(); var transaction = await server.SendAsync("http://example.com/login"); Assert.NotNull(transaction.SetCookie); Assert.Equal(1, transaction.SetCookie.Count); var cookie = SetCookieHeaderValue.Parse(transaction.SetCookie[0]); Assert.Equal("TestCookie", cookie.Name); Assert.True(cookie.HttpOnly); Assert.True(cookie.Secure); Assert.Equal("/", cookie.Path); Assert.Contains("extension", cookie.Extensions); }
private static string ExtractAntiForgeryCookieValueFrom(HttpResponseMessage response) { //questo non รจ in grado di farlo il codice fraudolento!! string antiForgeryCookie = response.Headers.GetValues("Set-Cookie") .FirstOrDefault(x => x.Contains(AntiForgeryCookieName)); if (antiForgeryCookie is null) { throw new ArgumentException($"Cookie '{AntiForgeryCookieName}' not found in HTTP response", nameof(response)); } string antiForgeryCookieValue = SetCookieHeaderValue.Parse(antiForgeryCookie).Value.ToString(); return(antiForgeryCookieValue); }
public void SetCookieHeaderValue_Parse_RejectsInvalidValues(string value) { Assert.Throws <FormatException>(() => SetCookieHeaderValue.Parse(value)); }