Exemplo n.º 1
0
        protected async override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            var response        = new HttpResponseMessage();
            var queryParameters = new ReadableStringCollection(QueryHelpers.ParseQuery(request.RequestUri.Query));

            if (request.RequestUri.AbsoluteUri.StartsWith("https://graph.facebook.com/v2.2/oauth/access_token"))
            {
                if (queryParameters["grant_type"] == "authorization_code")
                {
                    if (queryParameters["code"] == "ValidCode")
                    {
                        Helpers.ThrowIfConditionFailed(() => ((string)queryParameters["redirect_uri"]).EndsWith("signin-facebook"), "Redirect URI is not ending with /signin-facebook");
                        Helpers.ThrowIfConditionFailed(() => queryParameters["client_id"] == "[AppId]", "Invalid client Id received");
                        Helpers.ThrowIfConditionFailed(() => queryParameters["client_secret"] == "[AppSecret]", "Invalid client secret received");
                        response.Content = new StringContent("access_token=ValidAccessToken&expires=100");
                    }
                }
            }
            else if (request.RequestUri.AbsoluteUri.StartsWith("https://graph.facebook.com/v2.2/me"))
            {
                Helpers.ThrowIfConditionFailed(() => queryParameters["appsecret_proof"] != null, "appsecret_proof is null");
                if (queryParameters["access_token"] == "ValidAccessToken")
                {
                    response.Content = new StringContent("{\"id\":\"Id\",\"name\":\"AspnetvnextTest AspnetvnextTest\",\"first_name\":\"AspnetvnextTest\",\"last_name\":\"AspnetvnextTest\",\"link\":\"https:\\/\\/www.facebook.com\\/myLink\",\"username\":\"AspnetvnextTest.AspnetvnextTest.7\",\"gender\":\"male\",\"email\":\"AspnetvnextTest\\u0040test.com\",\"timezone\":-7,\"locale\":\"en_US\",\"verified\":true,\"updated_time\":\"2013-08-06T20:38:48+0000\",\"CertValidatorInvoked\":\"ValidAccessToken\"}");
                }
                else
                {
                    response.Content = new StringContent("{\"error\":{\"message\":\"Invalid OAuth access token.\",\"type\":\"OAuthException\",\"code\":190}}");
                }
            }

            return(await Task.FromResult(response));
        }
        protected override IEnumerableValueProvider GetEnumerableValueProvider(
            BindingSource bindingSource,
            IDictionary <string, string[]> values,
            CultureInfo culture)
        {
            var backingStore = new ReadableStringCollection(values);

            return(new ReadableStringCollectionValueProvider(bindingSource, backingStore, culture));
        }
        public async Task ContainsPrefixAsync_WithEmptyCollection_ReturnsFalseForEmptyPrefix()
        {
            // Arrange
            var backingStore = new ReadableStringCollection(new Dictionary<string, string[]>());
            var valueProvider = new ReadableStringCollectionValueProvider(backingStore, null);

            // Act
            var result = await valueProvider.ContainsPrefixAsync("");

            // Assert
            Assert.False(result);
        }
Exemplo n.º 4
0
        public async Task ContainsPrefixAsync_WithEmptyCollection_ReturnsFalseForEmptyPrefix()
        {
            // Arrange
            var backingStore  = new ReadableStringCollection(new Dictionary <string, string[]>());
            var valueProvider = new ReadableStringCollectionValueProvider <TestValueProviderMetadata>(backingStore, null);

            // Act
            var result = await valueProvider.ContainsPrefixAsync("");

            // Assert
            Assert.False(result);
        }
        private static IValueProvider CreateEnumerableValueProvider(
            string keyFormat,
            IDictionary <string, string> dictionary)
        {
            // Convert to an IDictionary<string, StringValues> then wrap it up.
            var backingStore = dictionary.ToDictionary(
                kvp => string.Format(keyFormat, kvp.Key),
                kvp => (StringValues)kvp.Value);
            var stringCollection = new ReadableStringCollection(backingStore);

            return(new ReadableStringCollectionValueProvider(
                       BindingSource.Form,
                       stringCollection,
                       CultureInfo.InvariantCulture));
        }
Exemplo n.º 6
0
        public async Task GetValueAsync_NullMultipleValue()
        {
            // Arrange
            var backingStore = new ReadableStringCollection(
                new Dictionary <string, string[]>
            {
                { "key", new string[] { null, null, "value" } }
            });
            var culture       = new CultureInfo("fr-FR");
            var valueProvider = new ReadableStringCollectionValueProvider <TestValueProviderMetadata>(backingStore, culture);

            // Act
            var vpResult = await valueProvider.GetValueAsync("key");

            // Assert
            Assert.Equal(new[] { null, null, "value" }, vpResult.RawValue as IEnumerable <string>);
            Assert.Equal(",,value", vpResult.AttemptedValue);
        }
Exemplo n.º 7
0
        public async Task <User> GetUserAsync_ModelType_IncludeAll(int id)
        {
            var backingStore = new ReadableStringCollection(
                new Dictionary <string, StringValues>
            {
                { "Key", new[] { "123" } },
                { "RegisterationMonth", new[] { "March" } },
                { "UserName", new[] { "SomeName" } }
            });

            var user = GetUser(id);

            await TryUpdateModelAsync(user,
                                      typeof(User),
                                      prefix : string.Empty,
                                      valueProvider : new ReadableStringCollectionValueProvider(
                                          BindingSource.Query,
                                          backingStore,
                                          CultureInfo.CurrentCulture),
                                      predicate : (content, propertyName) => true);

            return(user);
        }
Exemplo n.º 8
0
        public async Task <Employee> GetEmployeeAsync_BindToBaseDeclaredType()
        {
            var backingStore = new ReadableStringCollection(
                new Dictionary <string, StringValues>
            {
                { "Parent.Name", new[] { "fatherName" } },
                { "Parent.Parent.Name", new[] { "grandFatherName" } },
                { "Department", new[] { "Sales" } }
            });

            Person employee = new Employee();

            await TryUpdateModelAsync(
                employee,
                employee.GetType(),
                prefix : string.Empty,
                valueProvider : new ReadableStringCollectionValueProvider(
                    BindingSource.Query,
                    backingStore,
                    CultureInfo.CurrentCulture),
                predicate : (content, propertyName) => true);

            return((Employee)employee);
        }
        public void ContainsPrefix_ReturnsTrue_IfQueryStringNameStartsWithPrefix(
            string expectedKey,
            string key)
        {
            // Arrange
            var bindingSource = BindingSource.Query;
            var culture       = new CultureInfo("en-US");

            var collection = new ReadableStringCollection(
                new Dictionary <string, StringValues>()
            {
                { expectedKey, new StringValues("value") }
            });

            // Act
            var valueProvider =
                new SnakeCaseQueryValueProvider(
                    bindingSource,
                    collection,
                    culture);

            // Assert
            Assert.True(valueProvider.ContainsPrefix(key));
        }
Exemplo n.º 10
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.º 11
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 _httpClient.GetAsync("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 _httpClient.PostAsync("Account/ExternalLogin", content);

            Assert.Equal <string>("https://login.live.com/oauth20_authorize.srf", response.Headers.Location.AbsoluteUri.Replace(response.Headers.Location.Query, string.Empty));
            var queryItems = new ReadableStringCollection(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>("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(".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(_deploymentResult.ApplicationBaseUri)
            };

            response = await _httpClient.GetAsync("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 _httpClient.PostAsync("Account/ExternalLogin", content);

            //Post a message to the MicrosoftAccount middleware
            response = await _httpClient.GetAsync("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(".AspNet.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 _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
            _logger.LogInformation(await response.Content.ReadAsStringAsync());
            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
            _logger.LogInformation("Middleware events were fired successfully");
        }
        public async Task GetValueAsync_NullMultipleValue()
        {
            // Arrange
            var backingStore = new ReadableStringCollection(
                new Dictionary<string, string[]>
                {
                    { "key", new string[] { null, null, "value" } }
                });
            var culture = new CultureInfo("fr-FR");
            var valueProvider = new ReadableStringCollectionValueProvider(backingStore, culture);

            // Act
            var vpResult = await valueProvider.GetValueAsync("key");

            // Assert
            Assert.Equal(new[] { null, null, "value" }, vpResult.RawValue as IEnumerable<string>);
            Assert.Equal(",,value", vpResult.AttemptedValue);
        }
Exemplo n.º 14
0
 public FormData(ReadableStringCollection form, IEnumerable <HttpFile> files)
 {
     Form  = form;
     Files = files;
 }
Exemplo n.º 15
0
        /// <summary>
        /// 解码字符串
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        #pragma warning disable 1998
        private async Task Decode()
        {
            if (_options.AllowArgumentEncrypt)
            {
                string[] values          = null;
                var      queryString     = _context.Request.QueryString.Value;
                var      queryCollection = _context.Request.Query;
                var      formCollection  = _context.Request.HasFormContentType ? _context.Request.Form : null;

                //解析查询字符串
                if (queryString.Length > 0)
                {
                    StringBuilder arguments = new StringBuilder();
                    queryString = queryString.Substring(1);
                    foreach (var item in queryString.Split('&'))
                    {
                        var key   = item.Split('=')[0];
                        var value = item.Split('=')[1];
                        value = Decrypt(value);

                        arguments.Append($"{key}={value}");
                        arguments.Append("&");
                    }
                    if (arguments.ToString().EndsWith("&"))
                    {
                        arguments.Remove(arguments.Length - 1, 1);
                    }
                    _context.Request.QueryString = new QueryString(queryString);
                }

                //解析查询字符串集合
                if (queryCollection != null && queryCollection.Count > 0)
                {
                    var queryDict = new Dictionary <string, StringValues>();
                    ReadableStringCollection query = new ReadableStringCollection(queryDict);
                    foreach (var item in queryCollection)
                    {
                        var key = item.Key;
                        values = new string[item.Value.Count];
                        for (var i = 0; i < values.Length; i++)
                        {
                            values[i] = Decrypt(item.Value[i]);
                        }

                        queryDict.Add(key, new StringValues(values));
                    }
                    _context.Request.Query = query;
                }

                //解析Form集合
                if (formCollection != null && formCollection.Count > 0)
                {
                    var            formDict = new Dictionary <string, StringValues>();
                    FormCollection form     = new FormCollection(formDict);
                    foreach (var item in formCollection)
                    {
                        var key = item.Key;
                        values = new string[item.Value.Count];
                        for (var i = 0; i < values.Length; i++)
                        {
                            values[i] = Decrypt(item.Value[i]);
                        }

                        formDict.Add(key, new StringValues(values));
                    }
                    _context.Request.Form = form;
                }
            }
        }