예제 #1
0
        public async Task ChallengeSetsNonceAndStateCookies(OpenIdConnectRedirectBehavior method)
        {
            var settings = new TestSettings(o =>
            {
                o.AuthenticationMethod = method;
                o.ClientId             = "Test Id";
                o.Authority            = TestServerBuilder.DefaultAuthority;
            });
            var server      = settings.CreateTestServer();
            var transaction = await server.SendAsync(ChallengeEndpoint);

            Assert.Contains("samesite=none", transaction.SetCookie.First());
            var challengeCookies = SetCookieHeaderValue.ParseList(transaction.SetCookie);
            var nonceCookie      = challengeCookies.Where(cookie => cookie.Name.StartsWith(OpenIdConnectDefaults.CookieNoncePrefix, StringComparison.Ordinal)).Single();

            Assert.True(nonceCookie.Expires.HasValue);
            Assert.True(nonceCookie.Expires > DateTime.UtcNow);
            Assert.True(nonceCookie.HttpOnly);
            Assert.Equal("/signin-oidc", nonceCookie.Path);
            Assert.Equal("N", nonceCookie.Value);
            Assert.Equal(Net.Http.Headers.SameSiteMode.None, nonceCookie.SameSite);

            var correlationCookie = challengeCookies.Where(cookie => cookie.Name.StartsWith(".AspNetCore.Correlation.", StringComparison.Ordinal)).Single();

            Assert.True(correlationCookie.Expires.HasValue);
            Assert.True(nonceCookie.Expires > DateTime.UtcNow);
            Assert.True(correlationCookie.HttpOnly);
            Assert.Equal("/signin-oidc", correlationCookie.Path);
            Assert.False(StringSegment.IsNullOrEmpty(correlationCookie.Value));
            Assert.Equal(Net.Http.Headers.SameSiteMode.None, correlationCookie.SameSite);

            Assert.Equal(2, challengeCookies.Count);
        }
예제 #2
0
        public async Task DeleteCookieDoesNotRequireConsent()
        {
            var httpContext = await RunTestAsync(options =>
            {
                options.CheckConsentNeeded = context => true;
            },
                                                 requestContext => { },
                                                 context =>
            {
                var feature = context.Features.Get <ITrackingConsentFeature>();
                Assert.True(feature.IsConsentNeeded);
                Assert.False(feature.HasConsent);
                Assert.False(feature.CanTrack);
                context.Response.Cookies.Delete("Test");
                return(Task.CompletedTask);
            });

            var cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers.SetCookie);

            Assert.Equal(1, cookies.Count);
            var testCookie = cookies[0];

            Assert.Equal("Test", testCookie.Name);
            Assert.Equal("", testCookie.Value);
            Assert.Equal(Net.Http.Headers.SameSiteMode.Unspecified, testCookie.SameSite);
            Assert.NotNull(testCookie.Expires);
        }
예제 #3
0
        public static AntiForgeryRequestTokens GetFromApplication(TestApplication app)
        {
            var homeResponseTask = app.Server.CreateRequest("/").GetAsync();

            homeResponseTask.ConfigureAwait(false);
            homeResponseTask.Wait();

            var homeRes = homeResponseTask.Result;

            if (!homeRes.Headers.TryGetValues(HeaderNames.SetCookie, out var cookies))
            {
                cookies = Enumerable.Empty <string>();
            }
            var antiForgeryCookie = SetCookieHeaderValue.ParseList(cookies.ToList()).FirstOrDefault(cookie => cookie.Name.ToString().StartsWith(".AspNetCore.Antiforgery"));

            if (antiForgeryCookie == null)
            {
                throw new InvalidOperationException("无法从服务器获取 AntiForgery Cookie");
            }

            var          htmlContent      = homeRes.ReadAllContent();
            const string tokenStart       = "window.__RequestVerificationToken";
            var          tokenHtmlContent = htmlContent.Substring(htmlContent.LastIndexOf(tokenStart));
            var          tokenPattern     = new Regex(@"^window\.__RequestVerificationToken[^']+'(?<token>[^']+)';");

            var token     = tokenPattern.Match(tokenHtmlContent).Groups["token"].Value;
            var reqCookie = new Cookie(antiForgeryCookie.Name.ToString(), antiForgeryCookie.Value.ToString());

            return(new AntiForgeryRequestTokens
            {
                VerificationToken = token,
                Cookie = reqCookie
            });
        }
        public async Task EnsureAdminAuthenticationCookie()
        {
            if (authenticationCookie != null)
            {
                return;
            }

            var formData = await EnsureAntiforgeryTokenForm(new Dictionary <string, string>
            {
                { "Email", "*****@*****.**" },
                { "Password", "123" }
            });

            var response = await this.Client.PostAsync("/Identity/Account/Login", new FormUrlEncodedContent(formData));

            Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);

            if (response.Headers.TryGetValues("Set-Cookie", out IEnumerable <string> values))
            {
                authenticationCookie = SetCookieHeaderValue.ParseList(values.ToList()).SingleOrDefault(c => c.Name.StartsWith(".AspNetCore.Identity.Application", StringComparison.InvariantCultureIgnoreCase));
            }

            Assert.NotNull(authenticationCookie);

            this.Client.DefaultRequestHeaders.Add("Cookie", new CookieHeaderValue(authenticationCookie.Name, authenticationCookie.Value).ToString());

            // The current pair of antiforgery cookie-token is not valid anymore
            // Since the tokens are generated based on the authenticated user!
            // We need a new token after authentication (The cookie can stay the same)
            antiforgeryToken = null;
        }
        protected async Task <string> EnsureAntiforgeryToken()
        {
            if (antiforgeryToken != null)
            {
                return(antiforgeryToken);
            }

            var response = await this.Client.GetAsync("/Identity/Account/Login");

            response.EnsureSuccessStatusCode();

            if (response.Headers.TryGetValues("Set-Cookie", out IEnumerable <string> values))
            {
                antiforgeryCookie = SetCookieHeaderValue.ParseList(values.ToList()).SingleOrDefault(c => c.Name.StartsWith(".AspNetCore.AntiForgery.", StringComparison.InvariantCultureIgnoreCase));
            }

            Assert.NotNull(antiforgeryCookie);

            this.Client.DefaultRequestHeaders.Add("Cookie", new CookieHeaderValue(antiforgeryCookie.Name, antiforgeryCookie.Value).ToString());

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

            var match = AntiforgeryFormFieldRegex.Match(responseHtml);

            antiforgeryToken = match.Success ? match.Groups[1].Captures[0].Value : null;

            Assert.NotNull(antiforgeryToken);

            return(antiforgeryToken);
        }
예제 #6
0
        public async Task ExpiredSession_LogsWarning()
        {
            var sink          = new TestSink();
            var loggerFactory = new TestLoggerFactory(sink, enabled: true);
            var builder       = new WebHostBuilder()
                                .Configure(app =>
            {
                app.UseSession();
                app.Run(context =>
                {
                    int?value = context.Session.GetInt32("Key");
                    if (context.Request.Path == new PathString("/first"))
                    {
                        Assert.False(value.HasValue);
                        value = 1;
                        context.Session.SetInt32("Key", 1);
                    }
                    else if (context.Request.Path == new PathString("/second"))
                    {
                        Assert.False(value.HasValue);
                        value = 2;
                    }
                    return(context.Response.WriteAsync(value.Value.ToString()));
                });
            })
                                .ConfigureServices(services =>
            {
                services.AddSingleton(typeof(ILoggerFactory), loggerFactory);

                services.AddMemoryCache();
                services.AddDistributedMemoryCache();

                services.AddSession(o => o.IdleTimeout = TimeSpan.FromMilliseconds(30));
            });

            using (var server = new TestServer(builder))
            {
                var client   = server.CreateClient();
                var response = await client.GetAsync("first");

                response.EnsureSuccessStatusCode();

                client = server.CreateClient();
                var cookie = SetCookieHeaderValue.ParseList(response.Headers.GetValues("Set-Cookie").ToList()).First();
                client.DefaultRequestHeaders.Add("Cookie", new CookieHeaderValue(cookie.Name, cookie.Value).ToString());
                Thread.Sleep(50);
                Assert.Equal("2", await client.GetStringAsync("/second"));

                var sessionLogMessages = sink.Writes.OnlyMessagesFromSource <DistributedSession>().ToArray();

                Assert.Equal(3, sessionLogMessages.Length);
                Assert.Contains("started", sessionLogMessages[0].State.ToString());
                Assert.Contains("stored", sessionLogMessages[1].State.ToString());
                Assert.Contains("expired", sessionLogMessages[2].State.ToString());
                Assert.Equal(LogLevel.Information, sessionLogMessages[0].LogLevel);
                Assert.Equal(LogLevel.Debug, sessionLogMessages[1].LogLevel);
                Assert.Equal(LogLevel.Warning, sessionLogMessages[2].LogLevel);
            }
        }
예제 #7
0
        public async Task RefreshesSession_WhenSessionData_IsNotModified()
        {
            var clock   = new TestClock();
            var builder = new WebHostBuilder()
                          .Configure(app =>
            {
                app.UseSession();
                app.Run(context =>
                {
                    string responseData = string.Empty;
                    if (context.Request.Path == new PathString("/AddDataToSession"))
                    {
                        context.Session.SetInt32("Key", 10);
                        responseData = "added data to session";
                    }
                    else if (context.Request.Path == new PathString("/AccessSessionData"))
                    {
                        var value    = context.Session.GetInt32("Key");
                        responseData = (value == null) ? "No value found in session." : value.ToString();
                    }
                    else if (context.Request.Path == new PathString("/DoNotAccessSessionData"))
                    {
                        responseData = "did not access session data";
                    }

                    return(context.Response.WriteAsync(responseData));
                });
            })
                          .ConfigureServices(services =>
            {
                services.AddSingleton(typeof(ILoggerFactory), NullLoggerFactory.Instance);
                services.AddDistributedMemoryCache();
                services.AddSession(o => o.IdleTimeout = TimeSpan.FromMinutes(20));
                services.Configure <MemoryCacheOptions>(o => o.Clock = clock);
            });

            using (var server = new TestServer(builder))
            {
                var client   = server.CreateClient();
                var response = await client.GetAsync("AddDataToSession");

                response.EnsureSuccessStatusCode();

                client = server.CreateClient();
                var cookie = SetCookieHeaderValue.ParseList(response.Headers.GetValues("Set-Cookie").ToList()).First();
                client.DefaultRequestHeaders.Add(
                    "Cookie", new CookieHeaderValue(cookie.Name, cookie.Value).ToString());

                for (var i = 0; i < 5; i++)
                {
                    clock.Add(TimeSpan.FromMinutes(10));
                    await client.GetStringAsync("/DoNotAccessSessionData");
                }

                var data = await client.GetStringAsync("/AccessSessionData");

                Assert.Equal("10", data);
            }
        }
 /// <summary>
 /// Gets cookies from the HTTP response.
 /// </summary>
 /// <param name="response">HTTP response from which the cookies are retrieved.</param>
 /// <returns>
 /// List of <see cref="SetCookieHeaderValue"/> objects. If the response does not have any cookies, empty list is returned.
 /// </returns>
 /// <remarks><para>This method is available only in .NET Core version of the library.</para></remarks>
 public static IList <SetCookieHeaderValue> GetCookies(this HttpResponseMessage response)
 {
     if (response.Headers.TryGetValues(HeaderNames.SetCookie, out IEnumerable <string> values))
     {
         return(SetCookieHeaderValue.ParseList(values.ToList()));
     }
     return(new List <SetCookieHeaderValue>());
 }
예제 #9
0
    public async Task RemovedItemCannotBeAccessedAgain()
    {
        using var host = new HostBuilder()
                         .ConfigureWebHost(webHostBuilder =>
        {
            webHostBuilder
            .UseTestServer()
            .Configure(app =>
            {
                app.UseSession();
                app.Run(context =>
                {
                    int?value = context.Session.GetInt32("Key");
                    if (context.Request.Path == new PathString("/first"))
                    {
                        Assert.False(value.HasValue);
                        value = 0;
                        context.Session.SetInt32("Key", 1);
                    }
                    else if (context.Request.Path == new PathString("/second"))
                    {
                        Assert.True(value.HasValue);
                        Assert.Equal(1, value);
                        context.Session.Remove("Key");
                    }
                    else if (context.Request.Path == new PathString("/third"))
                    {
                        Assert.False(value.HasValue);
                        value = 2;
                    }
                    return(context.Response.WriteAsync(value.Value.ToString(CultureInfo.InvariantCulture)));
                });
            })
            .ConfigureServices(
                services =>
            {
                services.AddDistributedMemoryCache();
                services.AddSession();
            });
        }).Build();

        await host.StartAsync();

        using (var server = host.GetTestServer())
        {
            var client   = server.CreateClient();
            var response = await client.GetAsync("first");

            response.EnsureSuccessStatusCode();
            Assert.Equal("0", await response.Content.ReadAsStringAsync());

            client = server.CreateClient();
            var cookie = SetCookieHeaderValue.ParseList(response.Headers.GetValues("Set-Cookie").ToList()).First();
            client.DefaultRequestHeaders.Add("Cookie", new CookieHeaderValue(cookie.Name, cookie.Value).ToString());
            Assert.Equal("1", await client.GetStringAsync("/second"));
            Assert.Equal("2", await client.GetStringAsync("/third"));
        }
    }
예제 #10
0
        public async Task AspNetCoreWithLargeInteropCookieContainsIdentity()
        {
            var identity = new ClaimsIdentity("Cookies");

            identity.AddClaim(new Claim(ClaimTypes.Name, new string('a', 1024 * 5)));

            var dataProtection = DataProtectionProvider.Create(new DirectoryInfo("..\\..\\artifacts"));
            var dataProtector  = dataProtection.CreateProtector(
                "Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", // full name of the ASP.NET Core type
                CookieAuthenticationDefaults.AuthenticationType, "v2");

            var interopServer = TestServer.Create(app =>
            {
                app.Properties["host.AppName"] = "Microsoft.Owin.Security.Tests";

                app.UseCookieAuthentication(new Cookies.CookieAuthenticationOptions
                {
                    TicketDataFormat = new AspNetTicketDataFormat(new DataProtectorShim(dataProtector)),
                    CookieName       = AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.CookiePrefix
                                       + AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme,
                    CookieManager = new ChunkingCookieManager(),
                });

                app.Run(context =>
                {
                    context.Authentication.SignIn(identity);
                    return(Task.FromResult(0));
                });
            });

            var transaction = await SendAsync(interopServer, "http://example.com");

            var builder = new WebHostBuilder()
                          .Configure(app =>
            {
                app.UseCookieAuthentication(new AspNetCore.Builder.CookieAuthenticationOptions
                {
                    DataProtectionProvider = dataProtection
                });
                app.Run(async context =>
                {
                    var result = await context.Authentication.AuthenticateAsync("Cookies");
                    await context.Response.WriteAsync(result.Identity.Name);
                });
            })
                          .ConfigureServices(services => services.AddAuthentication());
            var newServer = new AspNetCore.TestHost.TestServer(builder);

            var request = new HttpRequestMessage(HttpMethod.Get, "http://example.com/login");

            foreach (var cookie in SetCookieHeaderValue.ParseList(transaction.SetCookie))
            {
                request.Headers.Add("Cookie", cookie.Name + "=" + cookie.Value);
            }
            var response = await newServer.CreateClient().SendAsync(request);

            Assert.Equal(1024 * 5, (await response.Content.ReadAsStringAsync()).Length);
        }
예제 #11
0
        public static IDictionary <string, string> ExtractCookiesFromResponse(WebResponse httpResponseSource)
        {
            IDictionary <string, string> result = new Dictionary <string, string>();

            SetCookieHeaderValue.ParseList(httpResponseSource.Headers.GetValues("Set-Cookie")).ToList().ForEach(cookie =>
            {
                result.Add(cookie.Name.ToString(), cookie.Value.ToString());
            });
            return(result);
        }
예제 #12
0
 private void GetCookiesFromHeader(HttpResponseMessage response)
 {
     if (response.Headers.TryGetValues("Set-Cookie", out var newCookies))
     {
         foreach (var item in SetCookieHeaderValue.ParseList(newCookies.ToList()))
         {
             _cookies.Add(response.RequestMessage.RequestUri, new Cookie(item.Name.Value, item.Value.Value, item.Path.Value));
         }
     }
 }
예제 #13
0
    public async Task CreateConsentCookieAppliesPolicy()
    {
        var httpContext = await RunTestAsync(options =>
        {
            options.CheckConsentNeeded    = context => true;
            options.MinimumSameSitePolicy = Http.SameSiteMode.Strict;
            options.OnAppendCookie        = context =>
            {
                Assert.Equal(".AspNet.Consent", context.CookieName);
                Assert.Equal("yes", context.CookieValue);
                Assert.Equal(Http.SameSiteMode.Strict, context.CookieOptions.SameSite);
                context.CookieName  += "1";
                context.CookieValue += "1";
            };
        },
                                             requestContext => { },
                                             context =>
        {
            var feature = context.Features.Get <ITrackingConsentFeature>();
            Assert.True(feature.IsConsentNeeded);
            Assert.False(feature.HasConsent);
            Assert.False(feature.CanTrack);

            feature.GrantConsent();

            Assert.True(feature.IsConsentNeeded);
            Assert.True(feature.HasConsent);
            Assert.True(feature.CanTrack);

            var cookie = feature.CreateConsentCookie();
            context.Response.Headers["ManualCookie"] = cookie;

            return(Task.CompletedTask);
        });

        var cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers.SetCookie);

        Assert.Equal(1, cookies.Count);
        var consentCookie = cookies[0];

        Assert.Equal(".AspNet.Consent1", consentCookie.Name);
        Assert.Equal("yes1", consentCookie.Value);
        Assert.Equal(Net.Http.Headers.SameSiteMode.Strict, consentCookie.SameSite);
        Assert.NotNull(consentCookie.Expires);

        cookies = SetCookieHeaderValue.ParseList(httpContext.Response.Headers["ManualCookie"]);
        Assert.Equal(1, cookies.Count);
        var manualCookie = cookies[0];

        Assert.Equal(consentCookie.Name, manualCookie.Name);
        Assert.Equal(consentCookie.Value, manualCookie.Value);
        Assert.Equal(consentCookie.SameSite, manualCookie.SameSite);
        Assert.NotNull(manualCookie.Expires); // Expires may not exactly match to the second.
    }
예제 #14
0
        public static SetCookieHeaderValue GetAntiForgeryCookie(this HttpResponseMessage response)
        {
            if (response.Headers.TryGetValues("Set-Cookie", out var values))
            {
                var setCookieHeaderValues = SetCookieHeaderValue.ParseList(values.ToList());
                return(setCookieHeaderValues.SingleOrDefault(c =>
                                                             c.Name.StartsWith(".AspNetCore.AntiForgery.", StringComparison.InvariantCultureIgnoreCase)));
            }

            return(null);
        }
예제 #15
0
        private void SetAuthenticationCookieHeaderForClient(HttpResponseMessage loginResponse)
        {
            var cookieHeaders = loginResponse.Headers
                                .Where(h => h.Key == "Set-Cookie")
                                .SelectMany(h => h.Value)
                                .ToList();
            var authCookie = SetCookieHeaderValue.ParseList(cookieHeaders)
                             .Single(c => c.Name == ".AspNetCore.Identity.Application");

            _client.DefaultRequestHeaders.Add("cookie", authCookie.ToString());
        }
        protected HttpRequestMessage GetRequest(string path, HttpResponseMessage response)
        {
            var request = new HttpRequestMessage(HttpMethod.Get, path);

            if (response.Headers.TryGetValues("Set-Cookie", out var values))
            {
                var cookie = SetCookieHeaderValue.ParseList(values.ToList()).First();
                request.Headers.Add("Cookie", new CookieHeaderValue(cookie.Name, cookie.Value).ToString());
            }

            return(request);
        }
예제 #17
0
        private void CopyCookies(HttpResponseMessage response, HttpRequestMessage request)
        {
            var cookies = SetCookieHeaderValue.ParseList(response.Headers.GetValues(HeaderNames.SetCookie).ToList());

            foreach (var cookie in cookies)
            {
                if (cookie.Value.HasValue)
                {
                    request.Headers.Add(HeaderNames.Cookie, new CookieHeaderValue(cookie.Name, cookie.Value).ToString());
                }
            }
        }
예제 #18
0
        private static HttpRequestMessage CreateRequestWithCookie(HttpMethod httpMethod, string path, HttpResponseMessage response)
        {
            var request = new HttpRequestMessage(httpMethod, path);

            if (response.Headers.TryGetValues("Set-Cookie", out IEnumerable <string> values))
            {
                SetCookieHeaderValue cookie = SetCookieHeaderValue.ParseList(values.ToList()).First();
                request.Headers.Add("Cookie", new CookieHeaderValue(cookie.Name, cookie.Value).ToString());
            }

            return(request);
        }
        public static IEnumerable <SetCookieHeaderValue> GetSetCookieHeaderValues(this HttpResponseMessage subject)
        {
            subject = subject ?? throw new ArgumentNullException(nameof(subject));

            IEnumerable <string> values;

            if (!subject.Headers.TryGetValues("Set-Cookie", out values))
            {
                return(Enumerable.Empty <SetCookieHeaderValue>());
            }

            return(SetCookieHeaderValue.ParseList(values.ToList()).ToList());
        }
예제 #20
0
        private static SetCookieHeaderValue TryGetAntiForgeryCookie(HttpResponseMessage response)
        {
            if (response.Headers.TryGetValues("Set-Cookie", out IEnumerable <string> values))
            {
                return(SetCookieHeaderValue.ParseList(values.ToList())
                       .SingleOrDefault(
                           c => c.Name.StartsWith(
                               ".AspNetCore.AntiForgery.",
                               StringComparison.InvariantCultureIgnoreCase)));
            }

            return(null);
        }
예제 #21
0
        public HttpClient CreateAuthenticatedClient(User user)
        {
            var client    = base.CreateClient();
            var viewModel = UserFactory.SigninViewModel(user);
            var response  = client.PostAsJsonAsync("signin", viewModel).Result;
            var header    = response.Headers.GetValues("Set-Cookie");
            var cookies   = SetCookieHeaderValue.ParseList(header.ToList());
            var cookie    = cookies.Single();

            client.DefaultRequestHeaders.Add("Cookie", cookie.ToString());

            return(client);
        }
예제 #22
0
    // <summary>
    // extract cookies from response and set them to request message
    // </summary>
    public static HttpRequestMessage SetCookiesFromResponse(this HttpRequestMessage request, HttpResponseMessage response)
    {
        IEnumerable <string> values;

        if (response.Headers.TryGetValues("Set-Cookie", out values))
        {
            var setCookieHeaderValues = SetCookieHeaderValue.ParseList(values.ToList());
            var cookiesValues         = setCookieHeaderValues.Select(c => new CookieHeaderValue(c.Name, c.Value).ToString());
            var cookieHeaderValue     = string.Join("; ", cookiesValues);
            request.Headers.Add("Cookie", cookieHeaderValue);
        }
        return(request);
    }
예제 #23
0
        /// <summary>
        /// Login and return authentication cookie. This cookie must be passed with subsequent requests
        /// </summary>
        /// <param name="Client"></param>
        /// <returns></returns>
        public static async Task <SetCookieHeaderValue> Login(this HttpClient Client)
        {
            //pw for in-memory account, created in Startup.cs
            string pw = "QWErty!@#$%^12345";

            var result = await Client.GetAsync("/Account/Login");

            IEnumerable <string> values;

            result.Headers.TryGetValues("Set-Cookie", out values);

            Assert.NotNull(values);
            Assert.NotEmpty(values);
            //find the validation token
            //< input name = "__RequestVerificationToken" type = "hidden" value = "CfDJ8BQFQUk1PV9Fusy3dPMxl5Uu-rriBM3Ad5zCQGNf6fv_bkRBpTo7gfQAlYLPGyROR15d4NpLJ_AZN7mWKXKBqvOw-MAyMMEeLSeAeNadgxG_8sGgvJBYKGdtLn5PO9YO3jSNz_zQRuuTLjEmyTiPDCc" >
            string tokenPattern = "<input name=\\\"__RequestVerificationToken\\\" type=\\\"hidden\\\" value=\\\"([\\w\\W\\d\\D]*)\\\">";

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

            var match = Regex.Match(body, tokenPattern);

            Assert.NotEmpty(match.Groups[1].Value);
            //get request token to pass back to login
            var token = match.Groups[1].Value;

            var post = new
            {
                Password = pw,
                Email    = "*****@*****.**",
                __RequestVerificationToken = token
            };

            HttpRequestMessage message = new HttpRequestMessage();


            result = await Client.GetResponseFromFormEncodedPost("/Account/Login", post, null, null, false);

            body = await result.Content.ReadAsStringAsync();

            Assert.Equal(HttpStatusCode.Redirect, result.StatusCode);

            //get the cookies sent in response from the login
            Assert.True(result.Headers.TryGetValues("Set-Cookie", out values));
            Assert.NotNull(values);
            var cookies = SetCookieHeaderValue.ParseList(values.ToList());

            Assert.Equal(1, cookies.Count);


            return(cookies.FirstOrDefault());
        }
        // Inspired from:
        // https://github.com/aspnet/Mvc/blob/538cd9c19121f8d3171cbfddd5d842cbb756df3e/test/Microsoft.AspNet.Mvc.FunctionalTests/TempDataTest.cs#L201-L202

        public static IDictionary <string, string> ExtractCookiesFromResponse(HttpResponseMessage response)
        {
            var result = new Dictionary <string, string>();
            IEnumerable <string> values;

            if (response.Headers.TryGetValues("Set-Cookie", out values))
            {
                SetCookieHeaderValue.ParseList(values.ToList()).ToList().ForEach(cookie =>
                {
                    result.Add(cookie.Name, cookie.Value);
                });
            }
            return(result);
        }
예제 #25
0
        private HttpRequestMessage GetRequest(string path, HttpResponseMessage response)
        {
            var request = new HttpRequestMessage(HttpMethod.Get, path);
            IEnumerable <string> values;

            if (response.Headers.TryGetValues("Set-Cookie", out values))
            {
                var setCookieHeaderValues = SetCookieHeaderValue.ParseList(values.ToList());
                var cookiesValues         = setCookieHeaderValues.Select(c => new CookieHeaderValue(c.Name, c.Value).ToString());
                var cookieHeaderValue     = string.Join("; ", cookiesValues);
                request.Headers.Add("Cookie", cookieHeaderValue);
            }
            return(request);
        }
예제 #26
0
        public async Task ClearedItemsCannotBeAccessedAgain()
        {
            var builder = new WebHostBuilder()
                          .Configure(app =>
            {
                app.UseSession();
                app.Run(context =>
                {
                    int?value = context.Session.GetInt32("Key");
                    if (context.Request.Path == new PathString("/first"))
                    {
                        Assert.False(value.HasValue);
                        value = 0;
                        context.Session.SetInt32("Key", 1);
                    }
                    else if (context.Request.Path == new PathString("/second"))
                    {
                        Assert.True(value.HasValue);
                        Assert.Equal(1, value);
                        context.Session.Clear();
                    }
                    else if (context.Request.Path == new PathString("/third"))
                    {
                        Assert.False(value.HasValue);
                        value = 2;
                    }
                    return(context.Response.WriteAsync(value.Value.ToString()));
                });
            })
                          .ConfigureServices(services =>
            {
                services.AddSingleton <IDistributedCache>(new FauxCouchbaseCache());
                services.AddCouchbaseSession();
            });

            using (var server = new TestServer(builder))
            {
                var client   = server.CreateClient();
                var response = await client.GetAsync("first");

                response.EnsureSuccessStatusCode();
                Assert.Equal("0", await response.Content.ReadAsStringAsync());

                client = server.CreateClient();
                var cookie = SetCookieHeaderValue.ParseList(response.Headers.GetValues("Set-Cookie").ToList()).First();
                client.DefaultRequestHeaders.Add("Cookie", new CookieHeaderValue(cookie.Name, cookie.Value).ToString());
                Assert.Equal("1", await client.GetStringAsync("/second"));
                Assert.Equal("2", await client.GetStringAsync("/third"));
            }
        }
예제 #27
0
    private static async Task TestSyncWithTestServer()
    {
        var builder = new WebHostBuilder()
                      .UseKestrel()
                      .UseUrls("http://127.0.0.1:0/")
                      .Configure(app =>
        {
            app.UseSession();

            app.Run(context =>
            {
                int?value = context.Session.GetInt32("Key");
                if (context.Request.Path == new PathString("/first"))
                {
                    Console.WriteLine("value.HasValue : " + value.HasValue);
                    value = 0;
                }
                Console.WriteLine("value.HasValue " + value.HasValue);
                context.Session.SetInt32("Key", value.Value + 1);
                return(context.Response.WriteAsync(value.Value.ToString()));
            });
        })
                      .ConfigureServices(services =>
        {
            services.AddDistributedMemoryCache();
            services.AddSession();
        });

        using (var server = new TestServer(builder))
        {
            var client = server.CreateClient();

            // Nothing here seems to work
            // client.BaseAddress = new Uri("http://localhost.fiddler/");

            var response = await client.GetAsync("first");

            response.EnsureSuccessStatusCode();
            Console.WriteLine("Server result : " + await response.Content.ReadAsStringAsync());

            client = server.CreateClient();
            var cookie = SetCookieHeaderValue.ParseList(response.Headers.GetValues("Set-Cookie").ToList()).First();
            client.DefaultRequestHeaders.Add("Cookie", new CookieHeaderValue(cookie.Name, cookie.Value).ToString());

            Console.WriteLine("Server result : " + await client.GetStringAsync("/"));
            Console.WriteLine("Server result : " + await client.GetStringAsync("/"));
            Console.WriteLine("Server result : " + await client.GetStringAsync("/"));
        }
    }
예제 #28
0
        public TestHttpRequestBuilder WithCookieFrom(HttpResponseMessage prevResponse)
        {
            if (!prevResponse.Headers.TryGetValues(HeaderNames.SetCookie, out var cookies))
            {
                return(this);
            }

            var responseCookieHeaders = SetCookieHeaderValue.ParseList(cookies.ToList());

            foreach (var cookie in responseCookieHeaders)
            {
                WithCookie(cookie.Name.ToString(), cookie.Value.ToString());
            }
            return(this);
        }
예제 #29
0
        private void SetCookieHeaders(HttpRequestMessage request, HttpResponseMessage response)
        {
            IEnumerable <string> values;

            if (response.Headers.TryGetValues("Set-Cookie", out values))
            {
                foreach (var cookie in SetCookieHeaderValue.ParseList(values.ToList()))
                {
                    if (cookie.Expires == null || cookie.Expires >= DateTimeOffset.UtcNow)
                    {
                        request.Headers.Add("Cookie", new CookieHeaderValue(cookie.Name, cookie.Value).ToString());
                    }
                }
            }
        }
예제 #30
0
        public static RequestBuilder WithCookiesFrom(this RequestBuilder request, HttpResponseMessage response)
        {
            if (!response.Headers.TryGetValues(HeaderNames.SetCookie, out var cookies))
            {
                return(request);
            }

            var responseCookieHeaders = SetCookieHeaderValue.ParseList(cookies.ToList());

            foreach (var cookie in responseCookieHeaders)
            {
                request.WithCookie(cookie.Name.ToString(), cookie.Value.ToString());
            }
            return(request);
        }