Пример #1
0
        public async Task Ctor_EmptySource_Succeed()
        {
            var    content = new FormUrlEncodedContent(new Dictionary <string, string>());
            Stream stream  = await content.ReadAsStreamAsync();

            Assert.Equal(0, stream.Length);
        }
Пример #2
0
        public async Task WriteForm(FormHttpBody form)
        {
            Response.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            var content = new FormUrlEncodedContent(form.Values);
            var data    = await content.ReadAsStreamAsync();

            await data.CopyToAsync(Response.OutputStream);
        }
Пример #3
0
        public async Task KentorAuthServicesAuthenticationMiddleware_UsesCommandResultLocation()
        {
            // For Owin middleware, the redirect uri is part of the
            // authentication properties, but we don't want to use it as it
            // is because it can be empty (e.g. on unsolicited responses
            // or until #182 is fixed). The redirect uri should be taken
            // from the commandresult location instead.

            var context = OwinTestHelpers.CreateOwinContext();

            context.Request.Method = "POST";

            var response =
                @"<saml2p:Response xmlns:saml2p=""urn:oasis:names:tc:SAML:2.0:protocol""
                xmlns:saml2=""urn:oasis:names:tc:SAML:2.0:assertion""
                ID = """ + MethodBase.GetCurrentMethod().Name + @""" Version=""2.0""
                IssueInstant=""2013-01-01T00:00:00Z"">
                <saml2:Issuer>
                    https://idp.example.com
                </saml2:Issuer>
                <saml2p:Status>
                    <saml2p:StatusCode Value=""urn:oasis:names:tc:SAML:2.0:status:Success"" />
                </saml2p:Status>
                <saml2:Assertion
                Version=""2.0"" ID=""" + MethodBase.GetCurrentMethod().Name + @"_Assertion1""
                IssueInstant=""2013-09-25T00:00:00Z"">
                    <saml2:Issuer>https://idp.example.com</saml2:Issuer>
                    <saml2:Subject>
                        <saml2:NameID>SomeUser</saml2:NameID>
                        <saml2:SubjectConfirmation Method=""urn:oasis:names:tc:SAML:2.0:cm:bearer"" />
                    </saml2:Subject>
                    <saml2:Conditions NotOnOrAfter=""2100-01-01T00:00:00Z"" />
                </saml2:Assertion>
            </saml2p:Response>";

            var bodyData = new KeyValuePair <string, string>[] {
                new KeyValuePair <string, string>("SAMLResponse",
                                                  Convert.ToBase64String(Encoding.UTF8.GetBytes(SignedXmlHelper.SignXml(response))))
            };

            var encodedBodyData = new FormUrlEncodedContent(bodyData);

            context.Request.Body        = encodedBodyData.ReadAsStreamAsync().Result;
            context.Request.ContentType = encodedBodyData.Headers.ContentType.ToString();
            context.Request.Host        = new HostString("localhost");
            context.Request.Path        = new PathString("/AuthServices/Acs");

            var middleware = new KentorAuthServicesAuthenticationMiddleware(null, CreateAppBuilder(),
                                                                            new KentorAuthServicesAuthenticationOptions(true)
            {
                SignInAsAuthenticationType = "AuthType"
            });

            await middleware.Invoke(context);

            context.Response.StatusCode.Should().Be(302);
            context.Response.Headers["Location"].Should().Be("http://localhost/LoggedIn");
        }
        private async Task<object> ParseToObject(Type type, IEnumerable<KeyValuePair<string, string>> pairs)
        {
            var content = new FormUrlEncodedContent(pairs);
            var formatter = new FormUrlEncodedMediaTypeFormatter();
            var stream = await content.ReadAsStreamAsync();
            var jtoken = await formatter.ReadFromStreamAsync(typeof(JToken), stream, content, this._logger) as JToken;

            return jtoken.ToObject(type);
        }
        public async Task Ctor_OneUnicodeEntry_Encoded()
        {
            var data = new Dictionary<string, string>();
            data.Add("key", "valueク");
            var content = new FormUrlEncodedContent(data);

            Stream stream = await content.ReadAsStreamAsync();
            Assert.Equal(18, stream.Length);
            string result = new StreamReader(stream).ReadToEnd();
            Assert.Equal("key=value%E3%82%AF", result);
        }
        public async Task Ctor_TwoEntries_SeparatedByAnd()
        {
            var data = new Dictionary<string, string>();
            data.Add("key1", "value1");
            data.Add("key2", "value2");
            var content = new FormUrlEncodedContent(data);

            Stream stream = await content.ReadAsStreamAsync();
            Assert.Equal(23, stream.Length);
            string result = new StreamReader(stream).ReadToEnd();
            Assert.Equal("key1=value1&key2=value2", result);
        }
Пример #7
0
        public async Task Ctor_OneEntry_SeparatedByEquals()
        {
            var data = new Dictionary <string, string>();

            data.Add("key", "value");
            var content = new FormUrlEncodedContent(data);

            Stream stream = await content.ReadAsStreamAsync();

            Assert.Equal(9, stream.Length);
            string result = new StreamReader(stream).ReadToEnd();

            Assert.Equal("key=value", result);
        }
Пример #8
0
        public async Task Ctor_OneUnicodeEntry_Encoded()
        {
            var data = new Dictionary <string, string>();

            data.Add("key", "value\u30AF");
            var content = new FormUrlEncodedContent(data);

            Stream stream = await content.ReadAsStreamAsync();

            Assert.Equal(18, stream.Length);
            string result = new StreamReader(stream).ReadToEnd();

            Assert.Equal("key=value%E3%82%AF", result);
        }
        public async Task Ctor_WithSquareBrackets_Unencoded()
        {
            var data = new Dictionary <string, string> {
                { "key[subkey]", "[#value]" }
            };
            var content = new FormUrlEncodedContent(data);

            var stream = await content.ReadAsStreamAsync();

            Assert.Equal(22, stream.Length);
            var result = new StreamReader(stream).ReadToEnd();

            Assert.Equal("key[subkey]=[%23value]", result);
        }
Пример #10
0
        public async Task Ctor_TwoEntries_SeparatedByAnd()
        {
            var data = new Dictionary <string, string>();

            data.Add("key1", "value1");
            data.Add("key2", "value2");
            var content = new FormUrlEncodedContent(data);

            Stream stream = await content.ReadAsStreamAsync();

            Assert.Equal(23, stream.Length);
            string result = new StreamReader(stream).ReadToEnd();

            Assert.Equal("key1=value1&key2=value2", result);
        }
Пример #11
0
        public async Task Ctor_WithSpaces_EncodedAsPlus()
        {
            var data = new Dictionary <string, string>();

            data.Add("key 1", "val%20ue 1"); // %20 is a percent-encoded space, make sure it survives.
            data.Add("key 2", "val%ue 2");
            var content = new FormUrlEncodedContent(data);

            Stream stream = await content.ReadAsStreamAsync();

            Assert.Equal(35, stream.Length);
            string result = new StreamReader(stream).ReadToEnd();

            Assert.Equal("key+1=val%2520ue+1&key+2=val%25ue+2", result);
        }
        public async Task Ctor_WithSpaces_EncodedAsPlus()
        {
            var data = new Dictionary <string, string>
            {
                { "key 1", "val%20ue 1" },
                { "key 2", "val%ue 2" },
            };
            var content = new FormUrlEncodedContent(data);

            var stream = await content.ReadAsStreamAsync();

            Assert.Equal(35, stream.Length);
            var result = new StreamReader(stream).ReadToEnd();

            Assert.Equal("key+1=val%2520ue+1&key+2=val%25ue+2", result);
        }
        public async Task GivenKnownDataDigestIsCorrectlyCalculatedTellerTest()
        {
            // Arrange
            Dictionary <string, string> data = new Dictionary <string, string>
            {
                { "bank_code", "00-00-00" },
                { "account_number", "00000000" },
                { "amount", "0.01" }
            };

            var             content   = new FormUrlEncodedContent(data);
            DigestGenerator generator = new DigestGenerator("SHA256");

            // Act
            var result = generator.CalculateDigest(await content.ReadAsStreamAsync());

            // Assert
            Assert.Equal("SHA256=dX9LYG6i/d+TuzG0QMckFzqOZ6Wll/TlGGjUtqGyMhQ=", result);
        }
Пример #14
0
        public async Task <List <PartnerShop> > GetPartnerShopsPageAsync(string partnerUri, string csrf, int offset, int limit, IBrowsingContext browsingContext, CancellationToken cancellationToken)
        {
            var uri      = Defaults.HalvacardUri + partnerUri + "/nearest-shop";
            var formData = new Dictionary <string, string>()
            {
                { "offset", offset.ToString() },
                { "limit", limit.ToString() },
                { "lat", _commandLineOptions.Latitude },
                { "lng", _commandLineOptions.Longitude },
                { "_csrf", csrf },
            };
            var formDataEncoded = new FormUrlEncodedContent(formData);
            var formDataStream  = await formDataEncoded.ReadAsStreamAsync();

            var documentRequest = new DocumentRequest(new Url(uri))
            {
                Method  = HttpMethod.Post,
                Referer = Defaults.HalvacardUri + partnerUri,
                Body    = formDataStream,
            };

            documentRequest.Headers.TryAdd("Accept", "*/*");
            documentRequest.Headers.TryAdd("User-Agent", UserAgent);
            documentRequest.Headers.TryAdd("Content-Type", "application/x-www-form-urlencoded");
            documentRequest.Headers.TryAdd("X-Requested-With", "XMLHttpRequest");
            var pageContent = await browsingContext.OpenAsync(documentRequest, cancellationToken);

            var pageContentString = pageContent.ToHtml(_plainTextMarkupFormatter);
            var partnerShops      =
                pageContent.StatusCode == HttpStatusCode.OK &&
                !string.IsNullOrWhiteSpace(pageContentString)
                    ? JsonConvert.DeserializeObject <List <PartnerShop> >(pageContentString)
                    : new List <PartnerShop>();

            _logger.LogInformation($"{partnerShops.Count} shops found on {uri} ({nameof(offset)}={offset}, {nameof(limit)}={limit}), status code: {pageContent.StatusCode}");
            return(partnerShops);
        }
Пример #15
0
        public async Task KentorAuthServicesAuthenticationMiddleware_AcsWorks()
        {
            var context = OwinTestHelpers.CreateOwinContext();

            context.Request.Method = "POST";

            var authProps = new AuthenticationProperties()
            {
                IssuedUtc = new DateTime(1975, 05, 05, 05, 05, 05, DateTimeKind.Utc)
            };

            authProps.Dictionary["Test"] = "TestValue";

            var state = new StoredRequestState(new EntityId("https://idp.example.com"),
                                               new Uri("http://localhost/LoggedIn"),
                                               new Saml2Id("InResponseToId"),
                                               authProps.Dictionary);

            var relayState = SecureKeyGenerator.CreateRelayState();

            var cookieData = HttpRequestData.ConvertBinaryData(
                CreateAppBuilder().CreateDataProtector(
                    typeof(KentorAuthServicesAuthenticationMiddleware).FullName)
                .Protect(state.Serialize()));

            context.Request.Headers["Cookie"] = $"Kentor.{relayState}={cookieData}";

            var response =
                @"<saml2p:Response xmlns:saml2p=""urn:oasis:names:tc:SAML:2.0:protocol""
                xmlns:saml2=""urn:oasis:names:tc:SAML:2.0:assertion""
                ID = """ + MethodBase.GetCurrentMethod().Name + @""" Version=""2.0""
                IssueInstant=""2013-01-01T00:00:00Z"" InResponseTo=""InResponseToId"" >
                <saml2:Issuer>
                    https://idp.example.com
                </saml2:Issuer>
                <saml2p:Status>
                    <saml2p:StatusCode Value=""urn:oasis:names:tc:SAML:2.0:status:Success"" />
                </saml2p:Status>
                <saml2:Assertion
                Version=""2.0"" ID=""" + MethodBase.GetCurrentMethod().Name + @"_Assertion1""
                IssueInstant=""2013-09-25T00:00:00Z"">
                    <saml2:Issuer>https://idp.example.com</saml2:Issuer>
                    <saml2:Subject>
                        <saml2:NameID>SomeUser</saml2:NameID>
                        <saml2:SubjectConfirmation Method=""urn:oasis:names:tc:SAML:2.0:cm:bearer"" />
                    </saml2:Subject>
                    <saml2:Conditions NotOnOrAfter=""2100-01-01T00:00:00Z"" />
                </saml2:Assertion>
            </saml2p:Response>";

            var bodyData = new KeyValuePair <string, string>[] {
                new KeyValuePair <string, string>("SAMLResponse",
                                                  Convert.ToBase64String(Encoding.UTF8.GetBytes(SignedXmlHelper.SignXml(response)))),
                new KeyValuePair <string, string>("RelayState", relayState)
            };

            var encodedBodyData = new FormUrlEncodedContent(bodyData);

            context.Request.Body        = encodedBodyData.ReadAsStreamAsync().Result;
            context.Request.ContentType = encodedBodyData.Headers.ContentType.ToString();
            context.Request.Host        = new HostString("localhost");
            context.Request.Path        = new PathString("/AuthServices/Acs");

            var signInAsAuthenticationType = "AuthType";
            var ids = new ClaimsIdentity[] { new ClaimsIdentity(signInAsAuthenticationType),
                                             new ClaimsIdentity(signInAsAuthenticationType) };

            ids[0].AddClaim(new Claim(ClaimTypes.NameIdentifier, "SomeUser", null, "https://idp.example.com"));
            ids[1].AddClaim(new Claim(ClaimTypes.Role, "RoleFromClaimsAuthManager",
                                      null, "ClaimsAuthenticationManagerStub"));

            var subject = new KentorAuthServicesAuthenticationMiddleware(null, CreateAppBuilder(),
                                                                         StubFactory.CreateOwinOptions());

            await subject.Invoke(context);

            context.Response.StatusCode.Should().Be(303);
            context.Response.Headers["Location"].Should().Be("http://localhost/LoggedIn");
            context.Response.Headers["Set-Cookie"].Should().Be($"Kentor.{relayState}=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT");

            context.Authentication.AuthenticationResponseGrant.Principal.Identities
            .ShouldBeEquivalentTo(ids, opt => opt.IgnoringCyclicReferences());

            context.Authentication.AuthenticationResponseGrant.Properties.RedirectUri
            .Should().Be("http://localhost/LoggedIn",
                         "the StoredRequestState.ReturnUrl should overtake the value in the AuthProperties and be stored in the AuthProps");

            context.Authentication.AuthenticationResponseGrant.Properties.Dictionary["Test"]
            .Should().Be("TestValue");

            context.Authentication.AuthenticationResponseGrant.Properties.IssuedUtc
            .Should().Be(authProps.IssuedUtc);
        }
Пример #16
0
 public async Task Ctor_EmptySource_Succeed()
 {
     var content = new FormUrlEncodedContent(new Dictionary<string, string>());
     Stream stream = await content.ReadAsStreamAsync();
     Assert.Equal(0, stream.Length);
 }
Пример #17
0
        public async Task Ctor_WithSpaces_EncodedAsPlus()
        {
            var data = new Dictionary<string, string>();
            data.Add("key 1", "val%20ue 1"); // %20 is a percent-encoded space, make sure it survives.
            data.Add("key 2", "val%ue 2");
            var content = new FormUrlEncodedContent(data);

            Stream stream = await content.ReadAsStreamAsync();
            Assert.Equal(35, stream.Length);
            string result = new StreamReader(stream).ReadToEnd();
            Assert.Equal("key+1=val%2520ue+1&key+2=val%25ue+2", result);
        }
Пример #18
0
        public async Task Ctor_AllAsciiChars_EncodingMatchesHttpUtilty()
        {
            var builder = new StringBuilder();

            for (int ch = 0; ch < 128; ch++)
            {
                builder.Append((char)ch);
            }
            string testString = builder.ToString();

            var data = new Dictionary <string, string>();

            data.Add("key", testString);
            var content = new FormUrlEncodedContent(data);

            Stream stream = await content.ReadAsStreamAsync();

            string result = new StreamReader(stream).ReadToEnd().ToLowerInvariant();

            // Result of UrlEncode invoked in .NET Framework 4.6
            // string expectedResult = "key=" + HttpUtility.UrlEncode(testString).ToLowerInvariant();
            // HttpUtility is not part of ProjectK.

            string expectedResult = "key=%00%01%02%03%04%05%06%07%08%09%0a%0b%0c%0d%0e%0f%10%11%12%13%14%15%16%17%18" +
                                    "%19%1a%1b%1c%1d%1e%1f+!%22%23%24%25%26%27()*%2b%2c-.%2f0123456789%3a%3b%3c%3d%3e%3f%40abcdefghijklm" +
                                    "nopqrstuvwxyz%5b%5c%5d%5e_%60abcdefghijklmnopqrstuvwxyz%7b%7c%7d%7e%7f";

            string knownDiscrepancies = "~!*()";

            _output.WriteLine("Expecting result: '{0}'", expectedResult);
            _output.WriteLine("Actual result   : '{0}'", result);

            int discrepancies = 0;

            for (int i = 0; i < result.Length && i < expectedResult.Length; i++)
            {
                if (result[i] != expectedResult[i])
                {
                    Assert.True((result[i] == '%' || expectedResult[i] == '%'),
                                "Non-Escaping mis-match at position: " + i);

                    if (result[i] == '%')
                    {
                        Assert.True(knownDiscrepancies.Contains(expectedResult[i]),
                                    "Escaped when it shouldn't be: " + expectedResult[i] + " at position " + i);
                        result         = result.Substring(i + 3);
                        expectedResult = expectedResult.Substring(i + 1);
                    }
                    else
                    {
                        Assert.True(knownDiscrepancies.Contains(result[i]),
                                    "Not escaped when it should be : " + result[i] + " at position " + i);
                        result         = result.Substring(i + 1);
                        expectedResult = expectedResult.Substring(i + 3);
                    }
                    i = -1;
                    discrepancies++;
                }
            }
            Assert.Equal(5, discrepancies);
        }
Пример #19
0
        public async Task KentorAuthServicesAuthenticationMiddleware_AcsWorks()
        {
            var context = OwinTestHelpers.CreateOwinContext();

            context.Request.Method = "POST";

            var state = new StoredRequestState(new EntityId("https://idp.example.com"),
                                               new Uri("http://localhost/LoggedIn"),
                                               new AuthenticationProperties());

            ((AuthenticationProperties)state.RelayData).RedirectUri        = state.ReturnUrl.OriginalString;
            ((AuthenticationProperties)state.RelayData).Dictionary["Test"] = "TestValue";

            PendingAuthnRequests.Add(new Saml2Id(MethodBase.GetCurrentMethod().Name + @"RequestID"), state);

            var response =
                @"<saml2p:Response xmlns:saml2p=""urn:oasis:names:tc:SAML:2.0:protocol""
                xmlns:saml2=""urn:oasis:names:tc:SAML:2.0:assertion""
                ID = """ + MethodBase.GetCurrentMethod().Name + @""" Version=""2.0""
                IssueInstant=""2013-01-01T00:00:00Z"" InResponseTo=""" + MethodBase.GetCurrentMethod().Name + @"RequestID"" >
                <saml2:Issuer>
                    https://idp.example.com
                </saml2:Issuer>
                <saml2p:Status>
                    <saml2p:StatusCode Value=""urn:oasis:names:tc:SAML:2.0:status:Success"" />
                </saml2p:Status>
                <saml2:Assertion
                Version=""2.0"" ID=""" + MethodBase.GetCurrentMethod().Name + @"_Assertion1""
                IssueInstant=""2013-09-25T00:00:00Z"">
                    <saml2:Issuer>https://idp.example.com</saml2:Issuer>
                    <saml2:Subject>
                        <saml2:NameID>SomeUser</saml2:NameID>
                        <saml2:SubjectConfirmation Method=""urn:oasis:names:tc:SAML:2.0:cm:bearer"" />
                    </saml2:Subject>
                    <saml2:Conditions NotOnOrAfter=""2100-01-01T00:00:00Z"" />
                </saml2:Assertion>
            </saml2p:Response>";

            var bodyData = new KeyValuePair <string, string>[] {
                new KeyValuePair <string, string>("SAMLResponse",
                                                  Convert.ToBase64String(Encoding.UTF8.GetBytes(SignedXmlHelper.SignXml(response))))
            };

            var encodedBodyData = new FormUrlEncodedContent(bodyData);

            context.Request.Body        = encodedBodyData.ReadAsStreamAsync().Result;
            context.Request.ContentType = encodedBodyData.Headers.ContentType.ToString();
            context.Request.Host        = new HostString("localhost");
            context.Request.Path        = new PathString("/AuthServices/Acs");

            var signInAsAuthenticationType = "AuthType";
            var ids = new ClaimsIdentity[] { new ClaimsIdentity(signInAsAuthenticationType),
                                             new ClaimsIdentity(signInAsAuthenticationType) };

            ids[0].AddClaim(new Claim(ClaimTypes.NameIdentifier, "SomeUser", null, "https://idp.example.com"));
            ids[1].AddClaim(new Claim(ClaimTypes.Role, "RoleFromClaimsAuthManager",
                                      null, "ClaimsAuthenticationManagerStub"));

            var middleware = new KentorAuthServicesAuthenticationMiddleware(null, CreateAppBuilder(),
                                                                            StubFactory.CreateOwinOptions());

            await middleware.Invoke(context);

            context.Response.StatusCode.Should().Be(302);
            context.Response.Headers["Location"].Should().Be("http://localhost/LoggedIn");

            context.Authentication.AuthenticationResponseGrant.Principal.Identities
            .ShouldBeEquivalentTo(ids, opt => opt.IgnoringCyclicReferences());

            context.Authentication.AuthenticationResponseGrant.Properties.RedirectUri
            .Should().Be("http://localhost/LoggedIn");

            context.Authentication.AuthenticationResponseGrant.Properties.Dictionary["Test"]
            .Should().Be("TestValue");
        }
Пример #20
0
        public async Task Ctor_AllAsciiChars_EncodingMatchesHttpUtilty()
        {
            var builder = new StringBuilder();
            for (int ch = 0; ch < 128; ch++)
            {
                builder.Append((char)ch);
            }
            string testString = builder.ToString();

            var data = new Dictionary<string, string>();
            data.Add("key", testString);
            var content = new FormUrlEncodedContent(data);

            Stream stream = await content.ReadAsStreamAsync();
            string result = new StreamReader(stream).ReadToEnd().ToLowerInvariant();

            // Result of UrlEncode invoked in .Net 4.6
            // string expectedResult = "key=" + HttpUtility.UrlEncode(testString).ToLowerInvariant();
            // HttpUtility is not part of ProjectK.

            string expectedResult = "key=%00%01%02%03%04%05%06%07%08%09%0a%0b%0c%0d%0e%0f%10%11%12%13%14%15%16%17%18" +
                "%19%1a%1b%1c%1d%1e%1f+!%22%23%24%25%26%27()*%2b%2c-.%2f0123456789%3a%3b%3c%3d%3e%3f%40abcdefghijklm" +
                "nopqrstuvwxyz%5b%5c%5d%5e_%60abcdefghijklmnopqrstuvwxyz%7b%7c%7d%7e%7f";

            string knownDiscrepancies = "~!*()";

            _output.WriteLine("Expecting result: '{0}'", expectedResult);
            _output.WriteLine("Actual result   : '{0}'", result);

            int discrepancies = 0;
            for (int i = 0; i < result.Length && i < expectedResult.Length; i++)
            {
                if (result[i] != expectedResult[i])
                {
                    Assert.True((result[i] == '%' || expectedResult[i] == '%'),
                        "Non-Escaping mis-match at position: " + i);

                    if (result[i] == '%')
                    {
                        Assert.True(knownDiscrepancies.Contains(expectedResult[i]),
                            "Escaped when it shouldn't be: " + expectedResult[i] + " at position " + i);
                        result = result.Substring(i + 3);
                        expectedResult = expectedResult.Substring(i + 1);
                    }
                    else
                    {
                        Assert.True(knownDiscrepancies.Contains(result[i]),
                            "Not escaped when it should be : " + result[i] + " at position " + i);
                        result = result.Substring(i + 1);
                        expectedResult = expectedResult.Substring(i + 3);
                    }
                    i = -1;
                    discrepancies++;
                }
            }
            Assert.Equal(5, discrepancies);
        }