Exemplo n.º 1
0
        private void CheckOutCartItems()
        {
            _logger.LogInformation("Checking out the cart contents...");
            var response = _httpClient.GetAsync("Checkout/AddressAndPayment").Result;

            ThrowIfResponseStatusNotOk(response);
            var responseContent = response.Content.ReadAsStringAsync().Result;

            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Checkout/AddressAndPayment")),
                new KeyValuePair <string, string>("FirstName", "FirstNameValue"),
                new KeyValuePair <string, string>("LastName", "LastNameValue"),
                new KeyValuePair <string, string>("Address", "AddressValue"),
                new KeyValuePair <string, string>("City", "Redmond"),
                new KeyValuePair <string, string>("State", "WA"),
                new KeyValuePair <string, string>("PostalCode", "98052"),
                new KeyValuePair <string, string>("Country", "USA"),
                new KeyValuePair <string, string>("Phone", "PhoneValue"),
                new KeyValuePair <string, string>("Email", "*****@*****.**"),
                new KeyValuePair <string, string>("PromoCode", "FREE"),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response        = _httpClient.PostAsync("Checkout/AddressAndPayment", content).Result;
            responseContent = response.Content.ReadAsStringAsync().Result;
            Assert.Contains("<h2>Checkout Complete</h2>", responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.StartsWith(_applicationBaseUrl + "Checkout/Complete/", response.RequestMessage.RequestUri.AbsoluteUri, StringComparison.OrdinalIgnoreCase);
        }
Exemplo n.º 2
0
        public async Task SignInWithUser(string email, string password)
        {
            var response = await DoGetAsync("Account/Login");

            await ThrowIfResponseStatusNotOk(response);

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

            _logger.LogInformation("Signing in with user '{email}'", email);
            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Email", email),
                new KeyValuePair <string, string>("Password", password),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/Login")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response = await DoPostAsync("Account/Login", content);

            responseContent = await response.Content.ReadAsStringAsync();

            Assert.Contains(string.Format(CultureInfo.InvariantCulture, "Hello {0}!", email), responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("Log off", responseContent, StringComparison.OrdinalIgnoreCase);
            //Verify cookie sent
            Assert.Contains(IdentityCookieName, GetCookieNames());
            _logger.LogInformation("Successfully signed in with user '{email}'", email);
        }
Exemplo n.º 3
0
        public async Task RegisterExistingUser(string email)
        {
            _logger.LogInformation("Trying to register a user with name '{email}' again", email);
            var response = await DoGetAsync("Account/Register");

            await ThrowIfResponseStatusNotOk(response);

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

            _logger.LogInformation("Creating a new user with name '{email}'", email);
            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Email", email),
                new KeyValuePair <string, string>("Password", "Password~1"),
                new KeyValuePair <string, string>("ConfirmPassword", "Password~1"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/Register")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response = await DoPostAsync("Account/Register", content);

            responseContent = await response.Content.ReadAsStringAsync();

            Assert.Contains(string.Format(CultureInfo.InvariantCulture, "User name &#x27;{0}&#x27; is already taken.", email), responseContent, StringComparison.OrdinalIgnoreCase);
            _logger.LogInformation("Identity threw a valid exception that user '{email}' already exists in the system", email);
        }
Exemplo n.º 4
0
        public async Task <string> CreateAlbum()
        {
            var albumName = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 12);

            _logger.LogInformation("Trying to create an album with name '{album}'", albumName);
            var response = await DoGetAsync("Admin/StoreManager/create");

            await ThrowIfResponseStatusNotOk(response);

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

            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Admin/StoreManager/create")),
                new KeyValuePair <string, string>("GenreId", "1"),
                new KeyValuePair <string, string>("ArtistId", "1"),
                new KeyValuePair <string, string>("Title", albumName),
                new KeyValuePair <string, string>("Price", "9.99"),
                new KeyValuePair <string, string>("AlbumArtUrl", "http://myapp/testurl"),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response = await DoPostAsync("Admin/StoreManager/create", content);

            responseContent = await response.Content.ReadAsStringAsync();

            Assert.Equal(_deploymentResult.ApplicationBaseUri + "Admin/StoreManager", response.RequestMessage.RequestUri.AbsoluteUri);
            Assert.Contains(albumName, responseContent);
            _logger.LogInformation("Successfully created an album with name '{album}' in the store", albumName);
            return(albumName);
        }
Exemplo n.º 5
0
        public async Task SignInWithInvalidPassword(string email, string invalidPassword)
        {
            var response = await DoGetAsync("Account/Login");

            await ThrowIfResponseStatusNotOk(response);

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

            _logger.LogInformation("Signing in with user '{email}'", email);
            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Email", email),
                new KeyValuePair <string, string>("Password", invalidPassword),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/Login")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response = await DoPostAsync("Account/Login", content);

            responseContent = await response.Content.ReadAsStringAsync();

            Assert.Contains("<div class=\"text-danger validation-summary-errors\" data-valmsg-summary=\"true\"><ul><li>Invalid login attempt.</li>", responseContent, StringComparison.OrdinalIgnoreCase);
            //Verify cookie not sent
            Assert.DoesNotContain(IdentityCookieName, GetCookieNames());
            _logger.LogInformation("Identity successfully prevented an invalid user login.");
        }
Exemplo n.º 6
0
        private void SignInWithUser(string email, string password)
        {
            var response = _httpClient.GetAsync("Account/Login").Result;

            ThrowIfResponseStatusNotOk(response);
            var responseContent = response.Content.ReadAsStringAsync().Result;

            _logger.LogInformation("Signing in with user '{email}'", email);
            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Email", email),
                new KeyValuePair <string, string>("Password", password),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/Login")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response        = _httpClient.PostAsync("Account/Login", content).Result;
            responseContent = response.Content.ReadAsStringAsync().Result;
            Assert.Contains(string.Format("Hello {0}!", email), responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("Log off", responseContent, StringComparison.OrdinalIgnoreCase);
            //Verify cookie sent
            Assert.NotNull(_httpClientHandler.CookieContainer.GetCookies(new Uri(_applicationBaseUrl)).GetCookieWithName(".AspNet.Microsoft.AspNet.Identity.Application"));
            _logger.LogInformation("Successfully signed in with user '{email}'", email);
        }
Exemplo n.º 7
0
        private void RegisterUserWithNonMatchingPasswords()
        {
            _logger.LogInformation("Trying to create user with not matching password and confirm password");
            var response = _httpClient.GetAsync("Account/Register").Result;

            ThrowIfResponseStatusNotOk(response);
            var responseContent = response.Content.ReadAsStringAsync().Result;

            ValidateLayoutPage(responseContent);

            var generatedEmail = Guid.NewGuid().ToString().Replace("-", string.Empty) + "@test.com";

            _logger.LogInformation("Creating a new user with name '{email}'", generatedEmail);
            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Email", generatedEmail),
                new KeyValuePair <string, string>("Password", "Password~1"),
                new KeyValuePair <string, string>("ConfirmPassword", "Password~2"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/Register")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response        = _httpClient.PostAsync("Account/Register", content).Result;
            responseContent = response.Content.ReadAsStringAsync().Result;
            Assert.Null(_httpClientHandler.CookieContainer.GetCookies(new Uri(_applicationBaseUrl)).GetCookieWithName(".AspNet.Microsoft.AspNet.Identity.Application"));
            Assert.Contains("<div class=\"validation-summary-errors text-danger\" data-valmsg-summary=\"true\"><ul><li>The password and confirmation password do not match.</li>", responseContent, StringComparison.OrdinalIgnoreCase);
            _logger.LogInformation("Server side model validator rejected the user '{email}''s registration as passwords do not match.", generatedEmail);
        }
Exemplo n.º 8
0
        public async Task ChangePassword(string email)
        {
            var response = await DoGetAsync("Manage/ChangePassword");

            await ThrowIfResponseStatusNotOk(response);

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

            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("OldPassword", "Password~1"),
                new KeyValuePair <string, string>("NewPassword", "Password~2"),
                new KeyValuePair <string, string>("ConfirmPassword", "Password~2"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Manage/ChangePassword")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response = await DoPostAsync("Manage/ChangePassword", content);

            responseContent = await response.Content.ReadAsStringAsync();

            Assert.Contains("Your password has been changed.", responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains(IdentityCookieName, GetCookieNames());
            _logger.LogInformation("Successfully changed the password for user '{email}'", email);
        }
Exemplo n.º 9
0
        private string CreateAlbum()
        {
            var albumName = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 12);

            Console.WriteLine("Trying to create an album with name '{0}'", albumName);
            var response = httpClient.GetAsync("/StoreManager/create").Result;

            ThrowIfResponseStatusNotOk(response);
            var responseContent = response.Content.ReadAsStringAsync().Result;
            var formParameters  = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/StoreManager/create")),
                new KeyValuePair <string, string>("GenreId", "1"),
                new KeyValuePair <string, string>("ArtistId", "1"),
                new KeyValuePair <string, string>("Title", albumName),
                new KeyValuePair <string, string>("Price", "9.99"),
                new KeyValuePair <string, string>("AlbumArtUrl", "http://myapp/testurl"),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response        = httpClient.PostAsync("/StoreManager/create", content).Result;
            responseContent = response.Content.ReadAsStringAsync().Result;
            Assert.Equal <string>(ApplicationBaseUrl + "StoreManager", response.RequestMessage.RequestUri.AbsoluteUri);
            Assert.Contains(albumName, responseContent);
            Console.WriteLine("Successfully created an album with name '{0}' in the store", albumName);
            return(albumName);
        }
Exemplo n.º 10
0
        public async Task ChangePassword(string email)
        {
            var response = await _httpClient.GetAsync("Manage/ChangePassword");

            await ThrowIfResponseStatusNotOk(response);

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

            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("OldPassword", "Password~1"),
                new KeyValuePair <string, string>("NewPassword", "Password~2"),
                new KeyValuePair <string, string>("ConfirmPassword", "Password~2"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Manage/ChangePassword")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response = await _httpClient.PostAsync("Manage/ChangePassword", content);

            responseContent = await response.Content.ReadAsStringAsync();

            Assert.Contains("Your password has been changed.", responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.NotNull(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(".AspNet.Microsoft.AspNet.Identity.Application"));
            _logger.LogInformation("Successfully changed the password for user '{email}'", email);
        }
Exemplo n.º 11
0
        private void SignOutUser(string userName)
        {
            Console.WriteLine("Signing out from '{0}''s session", userName);
            var response = httpClient.GetAsync(string.Empty).Result;

            ThrowIfResponseStatusNotOk(response);
            var responseContent = response.Content.ReadAsStringAsync().Result;

            ValidateLayoutPage(responseContent);
            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/LogOff")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response        = httpClient.PostAsync("/Account/LogOff", content).Result;
            responseContent = response.Content.ReadAsStringAsync().Result;
            Assert.Contains("ASP.NET MVC Music Store", responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("Register", responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("Login", responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("mvcmusicstore.codeplex.com", responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("/Images/home-showcase.png", responseContent, StringComparison.OrdinalIgnoreCase);
            //Verify cookie cleared on logout
            Assert.Null(httpClientHandler.CookieContainer.GetCookies(new Uri(ApplicationBaseUrl)).GetCookieWithName(".AspNet.Microsoft.AspNet.Identity.Application"));
            Console.WriteLine("Successfully signed out of '{0}''s session", userName);
        }
Exemplo n.º 12
0
        private string RegisterValidUser()
        {
            var response = httpClient.GetAsync("/Account/Register").Result;

            ThrowIfResponseStatusNotOk(response);
            var responseContent = response.Content.ReadAsStringAsync().Result;

            ValidateLayoutPage(responseContent);

            var generatedUserName = Guid.NewGuid().ToString().Replace("-", string.Empty);

            Console.WriteLine("Creating a new user with name '{0}'", generatedUserName);
            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("UserName", generatedUserName),
                new KeyValuePair <string, string>("Password", "Password~1"),
                new KeyValuePair <string, string>("ConfirmPassword", "Password~1"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/Register")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response        = httpClient.PostAsync("/Account/Register", content).Result;
            responseContent = response.Content.ReadAsStringAsync().Result;
            Assert.Contains(string.Format("Hello {0}!", generatedUserName), responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("Log off", responseContent, StringComparison.OrdinalIgnoreCase);
            //Verify cookie sent
            Assert.NotNull(httpClientHandler.CookieContainer.GetCookies(new Uri(ApplicationBaseUrl)).GetCookieWithName(".AspNet.Microsoft.AspNet.Identity.Application"));
            Console.WriteLine("Successfully registered user '{0}' and signed in", generatedUserName);
            return(generatedUserName);
        }
Exemplo n.º 13
0
        public async Task SignOutUser(string email)
        {
            _logger.LogInformation("Signing out from '{email}''s session", email);
            var response = await DoGetAsync(string.Empty);

            await ThrowIfResponseStatusNotOk(response);

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

            ValidateLayoutPage(responseContent);
            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/LogOff")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response = await DoPostAsync("Account/LogOff", content);

            responseContent = await response.Content.ReadAsStringAsync();

            Assert.Contains("ASP.NET MVC Music Store", responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("Register", responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("Login", responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("www.github.com/aspnet/MusicStore", responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("/Images/home-showcase.png", responseContent, StringComparison.OrdinalIgnoreCase);
            //Verify cookie cleared on logout
            Assert.DoesNotContain(IdentityCookieName, GetCookieNames());
            _logger.LogInformation("Successfully signed out of '{email}''s session", email);
        }
Exemplo n.º 14
0
        private string CreateAlbum()
        {
            var    albumName       = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 12);
            string dataFromHub     = null;
            var    OnReceivedEvent = new AutoResetEvent(false);
            var    hubConnection   = new HubConnection(ApplicationBaseUrl + "SignalR");

            hubConnection.Received += (data) =>
            {
                Console.WriteLine("Data received by SignalR client: {0}", data);
                dataFromHub = data;
                OnReceivedEvent.Set();
            };

            IHubProxy proxy = hubConnection.CreateHubProxy("Announcement");

            hubConnection.Start().Wait();

            Console.WriteLine("Trying to create an album with name '{0}'", albumName);
            var response = httpClient.GetAsync("Admin/StoreManager/create").Result;

            ThrowIfResponseStatusNotOk(response);
            var responseContent = response.Content.ReadAsStringAsync().Result;
            var formParameters  = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Admin/StoreManager/create")),
                new KeyValuePair <string, string>("GenreId", "1"),
                new KeyValuePair <string, string>("ArtistId", "1"),
                new KeyValuePair <string, string>("Title", albumName),
                new KeyValuePair <string, string>("Price", "9.99"),
                new KeyValuePair <string, string>("AlbumArtUrl", "http://myapp/testurl"),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response        = httpClient.PostAsync("Admin/StoreManager/create", content).Result;
            responseContent = response.Content.ReadAsStringAsync().Result;

            if (!Helpers.RunningOnMono)
            {
                //Bug in mono Httpclient - RequestMessage not automatically changed on 302
                Assert.Equal <string>(ApplicationBaseUrl + "Admin/StoreManager", response.RequestMessage.RequestUri.AbsoluteUri);
            }

            Assert.Contains(albumName, responseContent);
            Console.WriteLine("Waiting for the SignalR client to receive album created announcement");
            OnReceivedEvent.WaitOne(TimeSpan.FromSeconds(10));
            dataFromHub = dataFromHub ?? "No relevant data received from Hub";
            Assert.Contains(albumName, dataFromHub);
            Console.WriteLine("Successfully created an album with name '{0}' in the store", albumName);
            return(albumName);
        }
Exemplo n.º 15
0
        public async Task <string> CreateAlbum()
        {
            var albumName = Guid.NewGuid().ToString().Replace("-", string.Empty).Substring(0, 12);

#if DNX451
            string dataFromHub     = null;
            var    OnReceivedEvent = new AutoResetEvent(false);
            var    hubConnection   = new HubConnection(_deploymentResult.ApplicationBaseUri + "SignalR");
            hubConnection.Received += (data) =>
            {
                _logger.LogVerbose("Data received by SignalR client: {receivedData}", data);
                dataFromHub = data;
                OnReceivedEvent.Set();
            };

            IHubProxy proxy = hubConnection.CreateHubProxy("Announcement");
            await hubConnection.Start();
#endif
            _logger.LogInformation("Trying to create an album with name '{album}'", albumName);
            var response = await _httpClient.GetAsync("Admin/StoreManager/create");
            await ThrowIfResponseStatusNotOk(response);

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

            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Admin/StoreManager/create")),
                new KeyValuePair <string, string>("GenreId", "1"),
                new KeyValuePair <string, string>("ArtistId", "1"),
                new KeyValuePair <string, string>("Title", albumName),
                new KeyValuePair <string, string>("Price", "9.99"),
                new KeyValuePair <string, string>("AlbumArtUrl", "http://myapp/testurl"),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());
            response = await _httpClient.PostAsync("Admin/StoreManager/create", content);

            responseContent = await response.Content.ReadAsStringAsync();

            Assert.Equal <string>(_deploymentResult.ApplicationBaseUri + "Admin/StoreManager", response.RequestMessage.RequestUri.AbsoluteUri);
            Assert.Contains(albumName, responseContent);
#if DNX451
            _logger.LogInformation("Waiting for the SignalR client to receive album created announcement");
            OnReceivedEvent.WaitOne(TimeSpan.FromSeconds(10));
            dataFromHub = dataFromHub ?? "No relevant data received from Hub";
            Assert.Contains(albumName, dataFromHub);
#endif
            _logger.LogInformation("Successfully created an album with name '{album}' in the store", albumName);
            return(albumName);
        }
Exemplo n.º 16
0
        public async Task <string> RegisterValidUser()
        {
            var response = await DoGetAsync("Account/Register");

            await ThrowIfResponseStatusNotOk(response);

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

            ValidateLayoutPage(responseContent);

            var generatedEmail = Guid.NewGuid().ToString().Replace("-", string.Empty) + "@test.com";

            _logger.LogInformation("Creating a new user with name '{email}'", generatedEmail);
            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Email", generatedEmail),
                new KeyValuePair <string, string>("Password", "Password~1"),
                new KeyValuePair <string, string>("ConfirmPassword", "Password~1"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/Register")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response = await DoPostAsync("Account/Register", content);

            responseContent = await response.Content.ReadAsStringAsync();

            //Account verification
            Assert.Equal(_deploymentResult.ApplicationBaseUri + "Account/Register", response.RequestMessage.RequestUri.AbsoluteUri);
            Assert.Contains("For DEMO only: You can click this link to confirm the email:", responseContent, StringComparison.OrdinalIgnoreCase);
            var startIndex = responseContent.IndexOf("[[<a href=\"", 0, StringComparison.Ordinal) + "[[<a href=\"".Length;
            var endIndex   = responseContent.IndexOf("\">link</a>]]", startIndex, StringComparison.Ordinal);
            var confirmUrl = responseContent.Substring(startIndex, endIndex - startIndex);

            confirmUrl = WebUtility.HtmlDecode(confirmUrl);
            response   = await DoGetAsync(confirmUrl);
            await ThrowIfResponseStatusNotOk(response);

            responseContent = await response.Content.ReadAsStringAsync();

            Assert.Contains("Thank you for confirming your email.", responseContent, StringComparison.OrdinalIgnoreCase);
            return(generatedEmail);
        }
Exemplo n.º 17
0
        public async Task SignOutUser(string email)
        {
            _logger.LogInformation("Signing out from '{email}''s session", email);
            var response = await DoGetAsync(string.Empty);

            await ThrowIfResponseStatusNotOk(response);

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

            ValidateLayoutPage(responseContent);
            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/LogOff")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response = await DoPostAsync("Account/LogOff", content);

            responseContent = await response.Content.ReadAsStringAsync();

            if (!Helpers.RunningOnMono)
            {
                Assert.Contains("ASP.NET MVC Music Store", responseContent, StringComparison.OrdinalIgnoreCase);
                Assert.Contains("Register", responseContent, StringComparison.OrdinalIgnoreCase);
                Assert.Contains("Login", responseContent, StringComparison.OrdinalIgnoreCase);
                Assert.Contains("www.github.com/aspnet/MusicStore", responseContent, StringComparison.OrdinalIgnoreCase);
                Assert.Contains("/Images/home-showcase.png", responseContent, StringComparison.OrdinalIgnoreCase);
                //Verify cookie cleared on logout
                Assert.Null(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(IdentityCookieName));
                _logger.LogInformation("Successfully signed out of '{email}''s session", email);
            }
            else
            {
                //Bug in Mono - on logout the cookie is not cleared in the cookie container and not redirected. Work around by reinstantiating the httpClient.
                _httpClientHandler = new HttpClientHandler();
                _httpClient        = new HttpClient(_httpClientHandler)
                {
                    BaseAddress = new Uri(_deploymentResult.ApplicationBaseUri)
                };
            }
        }
Exemplo n.º 18
0
        private void ChangePassword(string userName)
        {
            var response        = httpClient.GetAsync("/Account/Manage").Result;
            var responseContent = response.Content.ReadAsStringAsync().Result;
            var formParameters  = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("OldPassword", "Password~1"),
                new KeyValuePair <string, string>("NewPassword", "Password~2"),
                new KeyValuePair <string, string>("ConfirmPassword", "Password~2"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/Manage")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response        = httpClient.PostAsync("/Account/Manage", content).Result;
            responseContent = response.Content.ReadAsStringAsync().Result;
            Assert.Contains("Your password has been changed.", responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.NotNull(httpClientHandler.CookieContainer.GetCookies(new Uri(ApplicationBaseUrl)).GetCookieWithName(".AspNet.Microsoft.AspNet.Identity.Application"));
            Console.WriteLine("Successfully changed the password for user '{0}'", userName);
        }
Exemplo n.º 19
0
        private void SignInWithInvalidPassword(string userName, string invalidPassword)
        {
            var response        = httpClient.GetAsync("/Account/Login").Result;
            var responseContent = response.Content.ReadAsStringAsync().Result;

            Console.WriteLine("Signing in with user '{0}'", userName);
            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("UserName", userName),
                new KeyValuePair <string, string>("Password", invalidPassword),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/Login")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response        = httpClient.PostAsync("/Account/Login", content).Result;
            responseContent = response.Content.ReadAsStringAsync().Result;
            Assert.Contains("<div class=\"validation-summary-errors\"><ul><li>Invalid username or password.</li>", responseContent, StringComparison.OrdinalIgnoreCase);
            //Verify cookie not sent
            Assert.Null(httpClientHandler.CookieContainer.GetCookies(new Uri(ApplicationBaseUrl)).GetCookieWithName(".AspNet.Microsoft.AspNet.Identity.Application"));
            Console.WriteLine("Identity successfully prevented an invalid user login.");
        }
Exemplo n.º 20
0
        private void RegisterExistingUser(string userName)
        {
            Console.WriteLine("Trying to register a user with name '{0}' again", userName);
            var response        = httpClient.GetAsync("/Account/Register").Result;
            var responseContent = response.Content.ReadAsStringAsync().Result;

            Console.WriteLine("Creating a new user with name '{0}'", userName);
            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("UserName", userName),
                new KeyValuePair <string, string>("Password", "Password~1"),
                new KeyValuePair <string, string>("ConfirmPassword", "Password~1"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/Register")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response        = httpClient.PostAsync("/Account/Register", content).Result;
            responseContent = response.Content.ReadAsStringAsync().Result;
            Assert.Contains(string.Format("Name {0} is already taken.", userName), responseContent, StringComparison.OrdinalIgnoreCase);
            Console.WriteLine("Identity threw a valid exception that user '{0}' already exists in the system", userName);
        }
Exemplo n.º 21
0
        private void SignInWithInvalidPassword(string email, string invalidPassword)
        {
            var response = _httpClient.GetAsync("Account/Login").Result;

            ThrowIfResponseStatusNotOk(response);
            var responseContent = response.Content.ReadAsStringAsync().Result;

            _logger.LogInformation("Signing in with user '{email}'", email);
            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Email", email),
                new KeyValuePair <string, string>("Password", invalidPassword),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/Login")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response        = _httpClient.PostAsync("Account/Login", content).Result;
            responseContent = response.Content.ReadAsStringAsync().Result;
            Assert.Contains("<div class=\"validation-summary-errors text-danger\"><ul><li>Invalid login attempt.</li>", responseContent, StringComparison.OrdinalIgnoreCase);
            //Verify cookie not sent
            Assert.Null(_httpClientHandler.CookieContainer.GetCookies(new Uri(_applicationBaseUrl)).GetCookieWithName(".AspNet.Microsoft.AspNet.Identity.Application"));
            _logger.LogInformation("Identity successfully prevented an invalid user login.");
        }
Exemplo n.º 22
0
        public async Task RegisterUserWithNonMatchingPasswords()
        {
            _logger.LogInformation("Trying to create user with not matching password and confirm password");
            var response = await DoGetAsync("Account/Register");

            await ThrowIfResponseStatusNotOk(response);

            LogHeaders(response, LogLevel.Trace);

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

            ValidateLayoutPage(responseContent);


            var generatedEmail = Guid.NewGuid().ToString().Replace("-", string.Empty) + "@test.com";

            _logger.LogInformation("Creating a new user with name '{email}'", generatedEmail);
            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Email", generatedEmail),
                new KeyValuePair <string, string>("Password", "Password~1"),
                new KeyValuePair <string, string>("ConfirmPassword", "Password~2"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/Register")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response = await DoPostAsync("Account/Register", content);
            await ThrowIfResponseStatusNotOk(response);

            responseContent = await response.Content.ReadAsStringAsync();

            Assert.DoesNotContain(IdentityCookieName, GetCookieNames());
            Assert.Contains("<div class=\"text-danger validation-summary-errors\" data-valmsg-summary=\"true\"><ul><li>The password and confirmation password do not match.</li>", responseContent, StringComparison.OrdinalIgnoreCase);
            _logger.LogInformation("Server side model validator rejected the user '{email}''s registration as passwords do not match.", generatedEmail);
        }
Exemplo n.º 23
0
        private void LoginWithTwitter()
        {
            _httpClientHandler = new HttpClientHandler()
            {
                AllowAutoRedirect = false
            };
            _httpClient = new HttpClient(_httpClientHandler)
            {
                BaseAddress = new Uri(_applicationBaseUrl)
            };

            var response = _httpClient.GetAsync("Account/Login").Result;

            ThrowIfResponseStatusNotOk(response);
            var responseContent = response.Content.ReadAsStringAsync().Result;

            _logger.WriteInformation("Signing in with Twitter account");
            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("provider", "Twitter"),
                new KeyValuePair <string, string>("returnUrl", "/"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLogin")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response = _httpClient.PostAsync("Account/ExternalLogin", content).Result;
            Assert.Equal <string>("https://twitter.com/oauth/authenticate", response.Headers.Location.AbsoluteUri.Replace(response.Headers.Location.Query, string.Empty));
            var queryItems = new ReadableStringCollection(QueryHelpers.ParseQuery(response.Headers.Location.Query));

            Assert.Equal <string>("custom", queryItems["custom_redirect_uri"]);
            Assert.Equal <string>("valid_oauth_token", queryItems["oauth_token"]);
            //Check for the correlation cookie
            Assert.NotNull(_httpClientHandler.CookieContainer.GetCookies(new Uri(_applicationBaseUrl))["__TwitterState"]);

            //This is just to generate a correlation cookie. Previous step would generate this cookie, but we have reset the handler now.
            _httpClientHandler = new HttpClientHandler()
            {
                AllowAutoRedirect = true
            };
            _httpClient = new HttpClient(_httpClientHandler)
            {
                BaseAddress = new Uri(_applicationBaseUrl)
            };

            response        = _httpClient.GetAsync("Account/Login").Result;
            responseContent = response.Content.ReadAsStringAsync().Result;
            formParameters  = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("provider", "Twitter"),
                new KeyValuePair <string, string>("returnUrl", "/"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLogin")),
            };

            content  = new FormUrlEncodedContent(formParameters.ToArray());
            response = _httpClient.PostAsync("Account/ExternalLogin", content).Result;

            //Post a message to the Facebook middleware
            response = _httpClient.GetAsync("signin-twitter?oauth_token=valid_oauth_token&oauth_verifier=valid_oauth_verifier").Result;
            ThrowIfResponseStatusNotOk(response);
            responseContent = response.Content.ReadAsStringAsync().Result;

            //Check correlation cookie not getting cleared after successful signin
            if (!Helpers.RunningOnMono)
            {
                Assert.Null(_httpClientHandler.CookieContainer.GetCookies(new Uri(_applicationBaseUrl))["__TwitterState"]);
            }
            Assert.Equal(_applicationBaseUrl + "Account/ExternalLoginCallback?ReturnUrl=%2F", response.RequestMessage.RequestUri.AbsoluteUri);
            //Twitter does not give back the email claim for some reason.
            //Assert.Contains("*****@*****.**", responseContent, StringComparison.OrdinalIgnoreCase);

            formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Email", "*****@*****.**"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLoginConfirmation?ReturnUrl=%2F")),
            };

            content  = new FormUrlEncodedContent(formParameters.ToArray());
            response = _httpClient.PostAsync("Account/ExternalLoginConfirmation", content).Result;
            ThrowIfResponseStatusNotOk(response);
            responseContent = response.Content.ReadAsStringAsync().Result;

            Assert.Contains(string.Format("Hello {0}!", "*****@*****.**"), responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("Log off", responseContent, StringComparison.OrdinalIgnoreCase);
            //Verify cookie sent
            Assert.NotNull(_httpClientHandler.CookieContainer.GetCookies(new Uri(_applicationBaseUrl)).GetCookieWithName(".AspNet.Microsoft.AspNet.Identity.Application"));
            Assert.Null(_httpClientHandler.CookieContainer.GetCookies(new Uri(_applicationBaseUrl)).GetCookieWithName(".AspNet.Microsoft.AspNet.Identity.ExternalLogin"));
            _logger.WriteInformation("Successfully signed in with user '{0}'", "*****@*****.**");

            _logger.WriteInformation("Verifying if the middleware notifications were fired");
            //Check for a non existing item
            response = _httpClient.GetAsync(string.Format("Admin/StoreManager/GetAlbumIdFromName?albumName={0}", "123")).Result;
            //This action requires admin permissions. If notifications are fired this permission is granted
            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
            _logger.WriteInformation("Middleware notifications were fired successfully");
        }
Exemplo n.º 24
0
        private void LoginWithMicrosoftAccount()
        {
            httpClientHandler = new HttpClientHandler()
            {
                AllowAutoRedirect = false
            };
            httpClient = new HttpClient(httpClientHandler)
            {
                BaseAddress = new Uri(ApplicationBaseUrl)
            };

            var response = httpClient.GetAsync("Account/Login").Result;

            ThrowIfResponseStatusNotOk(response);
            var responseContent = response.Content.ReadAsStringAsync().Result;

            Console.WriteLine("Signing in with Microsoft account");
            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("provider", "Microsoft"),
                new KeyValuePair <string, string>("returnUrl", "/"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLogin")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response = httpClient.PostAsync("Account/ExternalLogin", content).Result;
            Assert.Equal <string>("https://login.live.com/oauth20_authorize.srf", response.Headers.Location.AbsoluteUri.Replace(response.Headers.Location.Query, string.Empty));
            var queryItems = QueryHelpers.ParseQuery(response.Headers.Location.Query);

            Assert.Equal <string>("code", queryItems["response_type"]);
            Assert.Equal <string>("[ClientId]", queryItems["client_id"]);
            Assert.Equal <string>(ApplicationBaseUrl + "signin-microsoft", queryItems["redirect_uri"]);
            Assert.Equal <string>("wl.basic wl.signin", queryItems["scope"]);
            Assert.Equal <string>("ValidStateData", queryItems["state"]);
            Assert.Equal <string>("custom", queryItems["custom_redirect_uri"]);

            //Check for the correlation cookie
            Assert.NotNull(httpClientHandler.CookieContainer.GetCookies(new Uri(ApplicationBaseUrl)).GetCookieWithName(".AspNet.Correlation.Microsoft"));

            //This is just to generate a correlation cookie. Previous step would generate this cookie, but we have reset the handler now.
            httpClientHandler = new HttpClientHandler()
            {
                AllowAutoRedirect = true
            };
            httpClient = new HttpClient(httpClientHandler)
            {
                BaseAddress = new Uri(ApplicationBaseUrl)
            };

            response        = httpClient.GetAsync("Account/Login").Result;
            responseContent = response.Content.ReadAsStringAsync().Result;
            formParameters  = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("provider", "Microsoft"),
                new KeyValuePair <string, string>("returnUrl", "/"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLogin")),
            };

            content  = new FormUrlEncodedContent(formParameters.ToArray());
            response = httpClient.PostAsync("Account/ExternalLogin", content).Result;

            //Post a message to the MicrosoftAccount middleware
            response = httpClient.GetAsync("signin-microsoft?code=ValidCode&state=ValidStateData").Result;
            ThrowIfResponseStatusNotOk(response);
            responseContent = response.Content.ReadAsStringAsync().Result;

            //Correlation cookie not getting cleared after successful signin?
            if (!Helpers.RunningOnMono)
            {
                Assert.Null(httpClientHandler.CookieContainer.GetCookies(new Uri(ApplicationBaseUrl)).GetCookieWithName(".AspNet.Correlation.Microsoft"));
            }
            Assert.Equal(ApplicationBaseUrl + "Account/ExternalLoginCallback?ReturnUrl=%2F", response.RequestMessage.RequestUri.AbsoluteUri);

            formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Email", "*****@*****.**"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLoginConfirmation?ReturnUrl=%2F")),
            };

            content  = new FormUrlEncodedContent(formParameters.ToArray());
            response = httpClient.PostAsync("Account/ExternalLoginConfirmation", content).Result;
            ThrowIfResponseStatusNotOk(response);
            responseContent = response.Content.ReadAsStringAsync().Result;

            Assert.Contains(string.Format("Hello {0}!", "*****@*****.**"), responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("Log off", responseContent, StringComparison.OrdinalIgnoreCase);
            //Verify cookie sent
            Assert.NotNull(httpClientHandler.CookieContainer.GetCookies(new Uri(ApplicationBaseUrl)).GetCookieWithName(".AspNet.Microsoft.AspNet.Identity.Application"));
            Assert.Null(httpClientHandler.CookieContainer.GetCookies(new Uri(ApplicationBaseUrl)).GetCookieWithName(".AspNet.Microsoft.AspNet.Identity.ExternalLogin"));
            Console.WriteLine("Successfully signed in with user '{0}'", "*****@*****.**");

            Console.WriteLine("Verifying if the middleware notifications were fired");
            //Check for a non existing item
            response = httpClient.GetAsync(string.Format("Admin/StoreManager/GetAlbumIdFromName?albumName={0}", "123")).Result;
            //This action requires admin permissions. If notifications are fired this permission is granted
            Console.WriteLine(response.Content.ReadAsStringAsync().Result);
            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
            Console.WriteLine("Middleware notifications were fired successfully");
        }
Exemplo n.º 25
0
        private void LoginWithFacebook()
        {
            httpClientHandler = new HttpClientHandler()
            {
                AllowAutoRedirect = false
            };
            httpClient = new HttpClient(httpClientHandler)
            {
                BaseAddress = new Uri(ApplicationBaseUrl)
            };

            var response = httpClient.GetAsync("Account/Login").Result;

            ThrowIfResponseStatusNotOk(response);
            var responseContent = response.Content.ReadAsStringAsync().Result;

            Console.WriteLine("Signing in with Facebook account");
            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("provider", "Facebook"),
                new KeyValuePair <string, string>("returnUrl", "/"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLogin")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response = httpClient.PostAsync("Account/ExternalLogin", content).Result;
            Assert.Equal <string>("https://www.facebook.com/dialog/oauth", response.Headers.Location.AbsoluteUri.Replace(response.Headers.Location.Query, string.Empty));
            var queryItems = response.Headers.Location.ParseQueryString();

            Assert.Equal <string>("code", queryItems["response_type"]);
            Assert.Equal <string>("[AppId]", queryItems["client_id"]);
            Assert.Equal <string>(ApplicationBaseUrl + "signin-facebook", queryItems["redirect_uri"]);
            Assert.Equal <string>("email,read_friendlists,user_checkins", queryItems["scope"]);
            Assert.Equal <string>("ValidStateData", queryItems["state"]);
            Assert.Equal <string>("custom", queryItems["custom_redirect_uri"]);
            //Check for the correlation cookie
            Assert.NotNull(httpClientHandler.CookieContainer.GetCookies(new Uri(ApplicationBaseUrl)).GetCookieWithName(".AspNet.Correlation.Facebook"));

            //This is just to generate a correlation cookie. Previous step would generate this cookie, but we have reset the handler now.
            httpClientHandler = new HttpClientHandler()
            {
                AllowAutoRedirect = true
            };
            httpClient = new HttpClient(httpClientHandler)
            {
                BaseAddress = new Uri(ApplicationBaseUrl)
            };

            response        = httpClient.GetAsync("Account/Login").Result;
            responseContent = response.Content.ReadAsStringAsync().Result;
            formParameters  = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("provider", "Facebook"),
                new KeyValuePair <string, string>("returnUrl", "/"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLogin")),
            };

            content  = new FormUrlEncodedContent(formParameters.ToArray());
            response = httpClient.PostAsync("Account/ExternalLogin", content).Result;

            //Post a message to the Facebook middleware
            response = httpClient.GetAsync("signin-facebook?code=ValidCode&state=ValidStateData").Result;
            //This should land us in ExternalLoginCallBack - this action is not implemented yet. We need to wait to complete automation.

            //Correlation cookie not getting cleared after successful signin?
            //Assert.Null(httpClientHandler.CookieContainer.GetCookies(new Uri(ApplicationBaseUrl)).GetCookieWithName(".AspNet.Correlation.Facebook"));
        }
Exemplo n.º 26
0
        public async Task LoginWithOpenIdConnect()
        {
            _httpClientHandler = new HttpClientHandler()
            {
                AllowAutoRedirect = false
            };
            _httpClient = new HttpClient(_httpClientHandler)
            {
                BaseAddress = new Uri(_deploymentResult.ApplicationBaseUri)
            };

            var response = await _httpClient.GetAsync("Account/Login");

            await ThrowIfResponseStatusNotOk(response);

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

            _logger.LogInformation("Signing in with OpenIdConnect account");
            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("provider", "OpenIdConnect"),
                new KeyValuePair <string, string>("returnUrl", "/"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLogin")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response = await _httpClient.PostAsync("Account/ExternalLogin", content);

            Assert.Equal <string>("https://login.windows.net/4afbc689-805b-48cf-a24c-d4aa3248a248/oauth2/authorize", response.Headers.Location.AbsoluteUri.Replace(response.Headers.Location.Query, string.Empty));
            var queryItems = new ReadableStringCollection(QueryHelpers.ParseQuery(response.Headers.Location.Query));

            Assert.Equal <string>("c99497aa-3ee2-4707-b8a8-c33f51323fef", queryItems["client_id"]);
            Assert.Equal <string>("form_post", queryItems["response_mode"]);
            Assert.Equal <string>("code id_token", queryItems["response_type"]);
            Assert.Equal <string>("openid profile", queryItems["scope"]);
            Assert.Equal <string>("OpenIdConnect.AuthenticationProperties=ValidStateData", queryItems["state"]);
            Assert.NotNull(queryItems["nonce"]);
            Assert.NotNull(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(".AspNet.OpenIdConnect.Nonce.protectedString"));

            // This is just enable the auto-redirect.
            _httpClientHandler = new HttpClientHandler()
            {
                AllowAutoRedirect = true
            };
            _httpClient = new HttpClient(_httpClientHandler)
            {
                BaseAddress = new Uri(_deploymentResult.ApplicationBaseUri)
            };
            _httpClientHandler.CookieContainer.Add(new Uri(_deploymentResult.ApplicationBaseUri), new Cookie(".AspNet.OpenIdConnect.Nonce.protectedString", "N"));

            //Post a message to the OpenIdConnect middleware
            var token = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("code", "AAABAAAAvPM1KaPlrEqdFSBzjqfTGGBtrTYVn589oKw4lLgJ6Svz0AhPVOJr0J2-Uu_KffGlqIbYlRAyxmt-vZ7VlSVdrWvOkNhK9OaAMaSD7LDoPbBTVMEkB0MdAgBTV34l2el-s8ZI02_9PvgQaORZs7n8eGaGbcoKAoxiDn2OcKuJVplXYgrGUwU4VpRaqe6RaNzuseM7qBFbLIv4Wps8CndE6W8ccmuu6EvGC6-H4uF9EZL7gU4nEcTcvkE4Qyt8do6VhTVfM1ygRNQgmV1BCig5t_5xfhL6-xWQdy15Uzn_Df8VSsyDXe8s9cxyKlqc_AIyLFy_NEiMQFUqjZWKd_rR3A8ugug15SEEGuo1kF3jMc7dVMdE6OF9UBd-Ax5ILWT7V4clnRQb6-CXB538DlolREfE-PowXYruFBA-ARD6rwAVtuVfCSbS0Zr4ZqfNjt6x8yQdK-OkdQRZ1thiZcZlm1lyb2EquGZ8Deh2iWBoY1uNcyjzhG-L43EivxtHAp6Y8cErhbo41iacgqOycgyJWxiB5J0HHkxD0nQ2RVVuY8Ybc9sdgyfKkkK2wZ3idGaRCdZN8Q9VBhWRXPDMqHWG8t3aZRtvJ_Xd3WhjNPJC0GpepUGNNQtXiEoIECC363o1z6PZC5-E7U3l9xK06BZkcfTOnggUiSWNCrxUKS44dNqaozdYlO5E028UgAEhJ4eDtcP3PZty-0j4j5Mw0F2FmyAA"),
                new KeyValuePair <string, string>("id_token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsIng1dCI6ImtyaU1QZG1Cdng2OHNrVDgtbVBBQjNCc2VlQSJ9.eyJhdWQiOiJjOTk0OTdhYS0zZWUyLTQ3MDctYjhhOC1jMzNmNTEzMjNmZWYiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC80YWZiYzY4OS04MDViLTQ4Y2YtYTI0Yy1kNGFhMzI0OGEyNDgvIiwiaWF0IjoxNDIyMzk1NzYzLCJuYmYiOjE0MjIzOTU3NjMsImV4cCI6MTQyMjM5OTY2MywidmVyIjoiMS4wIiwidGlkIjoiNGFmYmM2ODktODA1Yi00OGNmLWEyNGMtZDRhYTMyNDhhMjQ4IiwiYW1yIjpbInB3ZCJdLCJvaWQiOiJmODc2YWJlYi1kNmI1LTQ0ZTQtOTcxNi02MjY2YWMwMTgxYTgiLCJ1cG4iOiJ1c2VyM0BwcmFidXJhamdtYWlsLm9ubWljcm9zb2Z0LmNvbSIsInN1YiI6IlBVZGhjbFA1UGdJalNVOVAxUy1IZWxEYVNGU2YtbVhWMVk2MC1LMnZXcXciLCJnaXZlbl9uYW1lIjoiVXNlcjMiLCJmYW1pbHlfbmFtZSI6IlVzZXIzIiwibmFtZSI6IlVzZXIzIiwidW5pcXVlX25hbWUiOiJ1c2VyM0BwcmFidXJhamdtYWlsLm9ubWljcm9zb2Z0LmNvbSIsIm5vbmNlIjoiNjM1NTc5OTI4NjM5NTE3NzE1Lk9UUmpPVFZrTTJFdE1EUm1ZUzAwWkRFM0xUaGhaR1V0WldabVpHTTRPRGt6Wkdaa01EUmxORGhrTjJNdE9XSXdNQzAwWm1Wa0xXSTVNVEl0TVRVd1ltUTRNemRtT1dJMCIsImNfaGFzaCI6IkZHdDN3Y1FBRGUwUFkxUXg3TzFyNmciLCJwd2RfZXhwIjoiNjY5MzI4MCIsInB3ZF91cmwiOiJodHRwczovL3BvcnRhbC5taWNyb3NvZnRvbmxpbmUuY29tL0NoYW5nZVBhc3N3b3JkLmFzcHgifQ.coAdCkdMgnslMHagdU8IBgH7Z0dilRdMfKytyqPJuTr6sbmbhrAoAj-KeGwbKgzrd-BeDk_rW47dntWuuAqGrAOGzxXvS2dcSWgoEKoXuDccIL5b4rIomRpfJpaeE-YwiU3usyRvoQCpHmtOa0g7xVilIj3_1-9ylMgRDY5qcrtQ_hEZlGuYyiCPR0dw8WmNU7r6PKObG-o3Yk_RbEBHjnaWxKoJwrVUEZUQOJDAvlr6ZYEmGTlD_BM0Rc_0fJZPU7A3uN9PHLw1atm-chN06IDXf23R33JI_xFuEZnj9HZQ_eIzNCl7GFmUryK3FFgYJpIbsI0BIFuksSikXz33IA"),
                new KeyValuePair <string, string>("state", "OpenIdConnect.AuthenticationProperties=ValidStateData"),
                new KeyValuePair <string, string>("session_state", "d0b59ffa-2df9-4d8c-b43a-2c410987f4ae")
            };

            response = await _httpClient.PostAsync(string.Empty, new FormUrlEncodedContent(token.ToArray()));
            await ThrowIfResponseStatusNotOk(response);

            responseContent = await response.Content.ReadAsStringAsync();

            Assert.Equal(_deploymentResult.ApplicationBaseUri + "Account/ExternalLoginCallback?ReturnUrl=%2F", response.RequestMessage.RequestUri.AbsoluteUri);

            formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Email", "*****@*****.**"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLoginConfirmation?ReturnUrl=%2F")),
            };

            content  = new FormUrlEncodedContent(formParameters.ToArray());
            response = await _httpClient.PostAsync("Account/ExternalLoginConfirmation", content);
            await ThrowIfResponseStatusNotOk(response);

            responseContent = await response.Content.ReadAsStringAsync();

            Assert.Contains(string.Format("Hello {0}!", "*****@*****.**"), responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("Log off", responseContent, StringComparison.OrdinalIgnoreCase);
            //Verify cookie sent
            Assert.NotNull(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(".AspNet.Microsoft.AspNet.Identity.Application"));
            Assert.Null(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(".AspNet.Microsoft.AspNet.Identity.ExternalLogin"));
            _logger.LogInformation("Successfully signed in with user '{email}'", "*****@*****.**");

            _logger.LogInformation("Verifying if the middleware events were fired");
            //Check for a non existing item
            response = await _httpClient.GetAsync(string.Format("Admin/StoreManager/GetAlbumIdFromName?albumName={0}", "123"));

            //This action requires admin permissions. If events are fired this permission is granted
            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
            _logger.LogInformation("Middleware events were fired successfully");

            _logger.LogInformation("Verifying the OpenIdConnect logout flow..");
            response = await _httpClient.GetAsync(string.Empty);
            await ThrowIfResponseStatusNotOk(response);

            responseContent = await response.Content.ReadAsStringAsync();

            ValidateLayoutPage(responseContent);
            formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/LogOff")),
            };

            content = new FormUrlEncodedContent(formParameters.ToArray());
            // Need a non-redirecting handler
            var handler = new HttpClientHandler()
            {
                AllowAutoRedirect = false
            };

            handler.CookieContainer.Add(new Uri(_deploymentResult.ApplicationBaseUri), _httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)));
            _httpClient = new HttpClient(handler)
            {
                BaseAddress = new Uri(_deploymentResult.ApplicationBaseUri)
            };

            response = await _httpClient.PostAsync("Account/LogOff", content);

            Assert.Null(handler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(".AspNet.Microsoft.AspNet.Identity.Application"));
            Assert.Equal <string>(
                "https://login.windows.net/4afbc689-805b-48cf-a24c-d4aa3248a248/oauth2/logout",
                response.Headers.Location.AbsoluteUri.Replace(response.Headers.Location.Query, string.Empty));
            queryItems = new ReadableStringCollection(QueryHelpers.ParseQuery(response.Headers.Location.Query));
            Assert.Equal <string>(_deploymentResult.ApplicationBaseUri + "Account/Login", queryItems["post_logout_redirect_uri"]);
        }
        public async Task LoginWithMicrosoftAccount()
        {
            _httpClientHandler = new HttpClientHandler()
            {
                AllowAutoRedirect = false
            };
            _httpClient = new HttpClient(_httpClientHandler)
            {
                BaseAddress = new Uri(_deploymentResult.ApplicationBaseUri)
            };

            var response = await DoGetAsync("Account/Login");

            await ThrowIfResponseStatusNotOk(response);

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

            _logger.LogInformation("Signing in with Microsoft account");
            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("provider", "Microsoft"),
                new KeyValuePair <string, string>("returnUrl", "/"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLogin")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response = await DoPostAsync("Account/ExternalLogin", content);

            Assert.StartsWith("https://login.microsoftonline.com/common/oauth2/v2.0/authorize", response.Headers.Location.ToString());
            var queryItems = new QueryCollection(QueryHelpers.ParseQuery(response.Headers.Location.Query));

            Assert.Equal <string>("code", queryItems["response_type"]);
            Assert.Equal <string>("[ClientId]", queryItems["client_id"]);
            Assert.Equal <string>(_deploymentResult.ApplicationBaseUri + "signin-microsoft", queryItems["redirect_uri"]);
            Assert.Equal <string>("https://graph.microsoft.com/user.read wl.basic wl.signin", queryItems["scope"]);
            Assert.Equal <string>("ValidStateData", queryItems["state"]);
            Assert.Equal <string>("custom", queryItems["custom_redirect_uri"]);

            //Check for the correlation cookie
            //Assert.NotNull(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(".AspNetCore.Correlation.Microsoft"));

            //This is just to generate a correlation cookie. Previous step would generate this cookie, but we have reset the handler now.
            _httpClientHandler = new HttpClientHandler();
            _httpClient        = new HttpClient(_httpClientHandler)
            {
                BaseAddress = new Uri(_deploymentResult.ApplicationBaseUri)
            };

            response = await DoGetAsync("Account/Login");

            responseContent = await response.Content.ReadAsStringAsync();

            formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("provider", "Microsoft"),
                new KeyValuePair <string, string>("returnUrl", "/"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLogin")),
            };

            content  = new FormUrlEncodedContent(formParameters.ToArray());
            response = await DoPostAsync("Account/ExternalLogin", content);

            //Post a message to the MicrosoftAccount middleware
            response = await DoGetAsync("signin-microsoft?code=ValidCode&state=ValidStateData");
            await ThrowIfResponseStatusNotOk(response);

            responseContent = await response.Content.ReadAsStringAsync();

            //Correlation cookie not getting cleared after successful signin?
            if (!Helpers.RunningOnMono)
            {
                Assert.Null(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(".AspNetCore.Correlation.Microsoft"));
            }
            Assert.Equal(_deploymentResult.ApplicationBaseUri + "Account/ExternalLoginCallback?ReturnUrl=%2F", response.RequestMessage.RequestUri.AbsoluteUri);

            formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Email", "*****@*****.**"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLoginConfirmation?ReturnUrl=%2F")),
            };

            content  = new FormUrlEncodedContent(formParameters.ToArray());
            response = await DoPostAsync("Account/ExternalLoginConfirmation", content);
            await ThrowIfResponseStatusNotOk(response);

            responseContent = await response.Content.ReadAsStringAsync();

            Assert.Contains(string.Format("Hello {0}!", "*****@*****.**"), responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("Log off", responseContent, StringComparison.OrdinalIgnoreCase);
            //Verify cookie sent
            Assert.NotNull(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(IdentityCookieName));
            Assert.Null(_httpClientHandler.CookieContainer.GetCookies(new Uri(_deploymentResult.ApplicationBaseUri)).GetCookieWithName(ExternalLoginCookieName));
            _logger.LogInformation("Successfully signed in with user '{email}'", "*****@*****.**");

            _logger.LogInformation("Verifying if the middleware events were fired");
            //Check for a non existing item
            response = await DoGetAsync(string.Format("Admin/StoreManager/GetAlbumIdFromName?albumName={0}", "123"));

            //This action requires admin permissions. If events are fired this permission is granted
            _logger.LogInformation(await response.Content.ReadAsStringAsync());
            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
            _logger.LogInformation("Middleware events were fired successfully");
        }
Exemplo n.º 28
0
        public async Task LoginWithFacebook()
        {
            _httpClientHandler = new HttpClientHandler()
            {
                AllowAutoRedirect = false
            };
            _httpClient = new HttpClient(_httpClientHandler)
            {
                BaseAddress = new Uri(_deploymentResult.ApplicationBaseUri)
            };

            var response = await DoGetAsync("Account/Login");

            await ThrowIfResponseStatusNotOk(response);

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

            _logger.LogInformation("Signing in with Facebook account");
            var formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("provider", "Facebook"),
                new KeyValuePair <string, string>("returnUrl", "/"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLogin")),
            };

            var content = new FormUrlEncodedContent(formParameters.ToArray());

            response = await DoPostAsync("Account/ExternalLogin", content);

            Assert.StartsWith("https://www.facebook.com/v2.6/dialog/oauth", response.Headers.Location.ToString());
            var queryItems = new QueryCollection(QueryHelpers.ParseQuery(response.Headers.Location.Query));

            Assert.Equal <string>("code", queryItems["response_type"]);
            Assert.Equal <string>("[AppId]", queryItems["client_id"]);
            Assert.Equal <string>(_deploymentResult.ApplicationBaseUri + "signin-facebook", queryItems["redirect_uri"]);
            Assert.Equal <string>("public_profile,email,read_friendlists,user_checkins", queryItems["scope"]);
            Assert.Equal <string>("ValidStateData", queryItems["state"]);
            Assert.Equal <string>("custom", queryItems["custom_redirect_uri"]);
            //Check for the correlation cookie
            // Workaround for https://github.com/dotnet/corefx/issues/21250
            Assert.True(response.Headers.TryGetValues("Set-Cookie", out var setCookieValues));
            var setCookie = SetCookieHeaderValue.ParseList(setCookieValues.ToList());

            Assert.Contains(setCookie, c => c.Name.StartsWith(".AspNetCore.Correlation.Facebook", StringComparison.OrdinalIgnoreCase));

            // This is just enable the auto-redirect.
            _httpClientHandler = new HttpClientHandler();
            _httpClient        = new HttpClient(_httpClientHandler)
            {
                BaseAddress = new Uri(_deploymentResult.ApplicationBaseUri)
            };
            foreach (var header in SetCookieHeaderValue.ParseList(response.Headers.GetValues("Set-Cookie").ToList()))
            {
                // Workaround for https://github.com/dotnet/corefx/issues/21250
                // The path of the cookie must either match the URI or be a prefix of it due to the fact
                // that CookieContainer doesn't support the latest version of the standard for cookies.
                var uri = new Uri(new Uri(_deploymentResult.ApplicationBaseUri), header.Path.ToString());
                _httpClientHandler.CookieContainer.Add(uri, new Cookie(header.Name.ToString(), header.Value.ToString()));
            }

            //Post a message to the Facebook middleware
            response = await DoGetAsync("signin-facebook?code=ValidCode&state=ValidStateData");
            await ThrowIfResponseStatusNotOk(response);

            responseContent = await response.Content.ReadAsStringAsync();

            // Correlation cookie not getting cleared after successful signin?
            Assert.DoesNotContain(".AspNetCore.Correlation.Facebook", GetCookieNames(_deploymentResult.ApplicationBaseUri + "signin-facebook"));

            Assert.Equal(_deploymentResult.ApplicationBaseUri + "Account/ExternalLoginCallback?ReturnUrl=%2F", response.RequestMessage.RequestUri.AbsoluteUri);
            Assert.Contains("*****@*****.**", responseContent, StringComparison.OrdinalIgnoreCase);

            formParameters = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("Email", "*****@*****.**"),
                new KeyValuePair <string, string>("__RequestVerificationToken", HtmlDOMHelper.RetrieveAntiForgeryToken(responseContent, "/Account/ExternalLoginConfirmation?ReturnUrl=%2F")),
            };

            content  = new FormUrlEncodedContent(formParameters.ToArray());
            response = await DoPostAsync("Account/ExternalLoginConfirmation", content);
            await ThrowIfResponseStatusNotOk(response);

            responseContent = await response.Content.ReadAsStringAsync();

            Assert.Contains(string.Format("Hello {0}!", "*****@*****.**"), responseContent, StringComparison.OrdinalIgnoreCase);
            Assert.Contains("Log off", responseContent, StringComparison.OrdinalIgnoreCase);
            // Verify cookie sent
            Assert.Contains(IdentityCookieName, GetCookieNames());
            Assert.DoesNotContain(ExternalLoginCookieName, GetCookieNames());
            _logger.LogInformation("Successfully signed in with user '{email}'", "*****@*****.**");

            _logger.LogInformation("Verifying if the middleware events were fired");
            //Check for a non existing item
            response = await DoGetAsync(string.Format("Admin/StoreManager/GetAlbumIdFromName?albumName={0}", "123"));

            //This action requires admin permissions. If events are fired this permission is granted
            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
            _logger.LogInformation("Middleware events were fired successfully");
        }