예제 #1
0
        public async Task KentorAuthServicesAuthenticationMiddleware_SignInUrlRedirectsToIdp()
        {
            var context = OwinTestHelpers.CreateOwinContext();

            context.Request.Host = new HostString("localhost");
            var signinPath = "/AuthServices/SignIn";

            context.Request.Path        = new PathString(signinPath);
            context.Request.QueryString = new QueryString("ReturnUrl=%2FHome&idp=https%3A%2F%2Fidp2.example.com");

            var options    = new KentorAuthServicesAuthenticationOptions(true);
            var middleware = new KentorAuthServicesAuthenticationMiddleware(
                null, CreateAppBuilder(), options);

            await middleware.Invoke(context);

            context.Response.StatusCode.Should().Be(303);
            context.Response.Headers["Location"].Should().StartWith("https://idp2.example.com/idp?SAMLRequest");

            var relayState = ExtractRelayState(context);

            var storedAuthnData = ExtractRequestState(options.DataProtector, context);

            storedAuthnData.ReturnUrl.Should().Be("http://localhost/Home");
        }
예제 #2
0
        public async Task KentorAuthServicesAuthenticationMiddleware_StoresAuthenticationProperties()
        {
            var returnUrl = "http://sp.example.com/returnurl";

            var prop = new AuthenticationProperties()
            {
                RedirectUri = returnUrl
            };

            prop.Dictionary["test"] = "SomeValue";

            var options    = new KentorAuthServicesAuthenticationOptions(true);
            var middleware = new KentorAuthServicesAuthenticationMiddleware(
                new StubOwinMiddleware(401,
                                       new AuthenticationResponseChallenge(
                                           new string[] { "KentorAuthServices" }, prop)),
                CreateAppBuilder(),
                options);

            var context = OwinTestHelpers.CreateOwinContext();

            await middleware.Invoke(context);

            var storedAuthnData = ExtractRequestState(options.DataProtector, context);

            new AuthenticationProperties(storedAuthnData.RelayData).Dictionary["test"].Should().Be("SomeValue");
        }
예제 #3
0
        public async Task KentorAuthServicesAuthenicationMiddleware_StoresAuthenticationProperties()
        {
            var returnUrl = "http://sp.example.com/returnurl";

            var prop = new AuthenticationProperties()
            {
                RedirectUri = returnUrl
            };

            prop.Dictionary["test"] = "SomeValue";

            var middleware = new KentorAuthServicesAuthenticationMiddleware(
                new StubOwinMiddleware(401, new AuthenticationResponseChallenge(
                                           new string[] { "KentorAuthServices" }, prop)),
                CreateAppBuilder(), new KentorAuthServicesAuthenticationOptions(true));

            var context = OwinTestHelpers.CreateOwinContext();

            await middleware.Invoke(context);

            var requestId = AuthnRequestHelper.GetRequestId(new Uri(context.Response.Headers["Location"]));

            StoredRequestState storedAuthnData;

            PendingAuthnRequests.TryRemove(new Saml2Id(requestId), out storedAuthnData);

            ((AuthenticationProperties)storedAuthnData.RelayData).Dictionary["test"].Should().Be("SomeValue");
        }
예제 #4
0
        public async Task KentorAuthServicesAuthenticationMiddleware_LogoutsOnLogoutRequest()
        {
            var options = new KentorAuthServicesAuthenticationOptions(true);
            var subject = new KentorAuthServicesAuthenticationMiddleware(null, CreateAppBuilder(), options);

            var context = OwinTestHelpers.CreateOwinContext();

            var request = new Saml2LogoutRequest()
            {
                SessionIndex       = "SessionId",
                DestinationUrl     = new Uri("http://sp.example.com/AuthServices/Logout"),
                NameId             = new Saml2NameIdentifier("NameId"),
                Issuer             = new EntityId("https://idp.example.com"),
                SigningCertificate = SignedXmlHelper.TestCert
            };

            var url = Saml2Binding.Get(Saml2BindingType.HttpRedirect)
                      .Bind(request).Location;

            context.Request.Path        = new PathString(url.AbsolutePath);
            context.Request.QueryString = new QueryString(url.Query.TrimStart('?'));

            await subject.Invoke(context);

            context.Response.StatusCode.Should().Be(303);
            context.Response.Headers["Location"].Should().StartWith("https://idp.example.com/logout?SAMLResponse");

            context.Authentication.AuthenticationResponseRevoke.Should().NotBeNull();
            context.Authentication.AuthenticationResponseRevoke.AuthenticationTypes
            .Should().BeEmpty();
        }
예제 #5
0
        public async Task KentorAuthServicesAuthenticationMiddleware_CreatesRedirectOnAuthRevoke()
        {
            var revoke = new AuthenticationResponseRevoke(new string[0]);

            var options = new KentorAuthServicesAuthenticationOptions(true);

            options.SPOptions.PublicOrigin = new Uri("https://sp.example.com/ExternalPath/");

            var subject = new KentorAuthServicesAuthenticationMiddleware(
                new StubOwinMiddleware(200, revoke: revoke),
                CreateAppBuilder(),
                options);

            var context = OwinTestHelpers.CreateOwinContext();

            context.Request.Scheme   = "http";
            context.Request.Host     = new HostString("sp-internal.example.com");
            context.Request.PathBase = new PathString("/InternalPath");
            context.Request.Path     = new PathString("/LoggedOut");

            Thread.CurrentPrincipal = new ClaimsPrincipal(
                new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, "NameId", null, "https://idp.example.com"),
                new Claim(AuthServicesClaimTypes.SessionIndex, "SessionId", null, "https://idp.example.com")
            }, "Federation"));

            await subject.Invoke(context);

            context.Response.StatusCode.Should().Be(303);
            context.Response.Headers["Location"].Should().StartWith("https://idp.example.com/logout?SAMLRequest");
            var returnUrl = ExtractRequestState(options.DataProtector, context).ReturnUrl;

            returnUrl.Should().Be("https://sp.example.com/ExternalPath/LoggedOut");
        }
        public async Task KentorAuthServicesAuthenticationMiddleware_MetadataWorks()
        {
            var context = OwinTestHelpers.CreateOwinContext();

            context.Request.Host = new HostString("localhost");
            var metadataPath = "/SomeMetadataPath";

            context.Request.Path = new PathString(metadataPath);

            var middleware = new KentorAuthServicesAuthenticationMiddleware(null, CreateAppBuilder(),
                                                                            new KentorAuthServicesAuthenticationOptions()
            {
                MetadataPath = new PathString(metadataPath)
            });

            await middleware.Invoke(context);

            context.Response.Body.Seek(0, SeekOrigin.Begin);

            context.Response.ContentType.Should().Contain("application/samlmetadata+xml");

            var xmlData = XDocument.Load(context.Response.Body);

            xmlData.Document.Root.Name.Should().Be(Saml2Namespaces.Saml2Metadata + "EntityDescriptor");
        }
예제 #7
0
        public async Task KentorAuthServicesAuthenticationMiddleware_CreatesPostOnAuthChallenge()
        {
            var middleware = new KentorAuthServicesAuthenticationMiddleware(
                new StubOwinMiddleware(401, new AuthenticationResponseChallenge(
                                           new string[] { "KentorAuthServices" }, new AuthenticationProperties(
                                               new Dictionary <string, string>()
            {
                { "idp", "http://localhost:13428/idpMetadata" }
            }))),
                CreateAppBuilder(),
                new KentorAuthServicesAuthenticationOptions(true));

            var context = OwinTestHelpers.CreateOwinContext();

            await middleware.Invoke(context);

            context.Response.StatusCode.Should().Be(200);
            context.Response.Body.Seek(0, SeekOrigin.Begin);

            // Fix to #295, where content length is incorrectly set to 0 by the
            // next middleware. It appears as it works if the content length is
            // simply removed. See discussion in GitHub issue #295.
            context.Response.ContentLength.Should().NotHaveValue();

            using (var reader = new StreamReader(context.Response.Body))
            {
                string bodyContent = reader.ReadToEnd();

                // Checking some random stuff in body to make sure it looks like a SAML Post.
                bodyContent.Should().Contain("<form action");
                bodyContent.Should().Contain("<input type=\"hidden\" name=\"SAMLRequest\"");
            }
        }
예제 #8
0
        public async Task KentorAuthServicesAuthenticationMiddleware_CreatesRedirectOnSpecifiedAuthRevoke_WhenPassive()
        {
            var subject = new KentorAuthServicesAuthenticationMiddleware(
                new StubOwinMiddleware(200, revoke: new AuthenticationResponseRevoke(
                                           new string[] { "KentorAuthServices" })),
                CreateAppBuilder(),
                new KentorAuthServicesAuthenticationOptions(true)
            {
                AuthenticationMode = AuthenticationMode.Passive
            });

            var context = OwinTestHelpers.CreateOwinContext();

            Thread.CurrentPrincipal = new ClaimsPrincipal(
                new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, "NameId", null, "https://idp.example.com"),
                new Claim(AuthServicesClaimTypes.SessionIndex, "SessionId", null, "https://idp.example.com")
            }, "Federation"));

            await subject.Invoke(context);

            context.Response.StatusCode.Should().Be(303);
            context.Response.Headers["Location"].Should().StartWith("https://idp.example.com/logout?SAMLRequest");
        }
예제 #9
0
        public async Task KentorAuthServicesAuthenticationMiddleware_SignInUrlRedirectsToIdp()
        {
            var context = OwinTestHelpers.CreateOwinContext();

            context.Request.Host = new HostString("localhost");
            var signinPath = "/AuthServices/SignIn";

            context.Request.Path        = new PathString(signinPath);
            context.Request.QueryString = new QueryString("ReturnUrl=%2FHome&idp=https%3A%2F%2Fidp2.example.com");

            var middleware = new KentorAuthServicesAuthenticationMiddleware(null, CreateAppBuilder(),
                                                                            new KentorAuthServicesAuthenticationOptions(true));

            await middleware.Invoke(context);

            context.Response.StatusCode.Should().Be(303);
            context.Response.Headers["Location"].Should().StartWith("https://idp2.example.com/idp?SAMLRequest");

            var requestId = AuthnRequestHelper.GetRequestId(new Uri(context.Response.Headers["Location"]));

            StoredRequestState storedAuthnData;

            PendingAuthnRequests.TryRemove(new Saml2Id(requestId), out storedAuthnData);

            storedAuthnData.ReturnUrl.Should().Be("http://localhost/Home");
        }
예제 #10
0
        public async Task KentorAuthServicesAuthenticationMiddleware_CreatesPostOnAuthChallenge()
        {
            var middleware = new KentorAuthServicesAuthenticationMiddleware(
                new StubOwinMiddleware(401, new AuthenticationResponseChallenge(
                                           new string[] { "KentorAuthServices" }, new AuthenticationProperties(
                                               new Dictionary <string, string>()
            {
                { "idp", "http://localhost:13428/idpMetadata" }
            }))),
                CreateAppBuilder(),
                new KentorAuthServicesAuthenticationOptions(true));

            var context = OwinTestHelpers.CreateOwinContext();

            await middleware.Invoke(context);

            context.Response.StatusCode.Should().Be(200);
            context.Response.Body.Seek(0, SeekOrigin.Begin);

            using (var reader = new StreamReader(context.Response.Body))
            {
                string bodyContent = reader.ReadToEnd();

                // Checking some random stuff in body to make sure it looks like a SAML Post.
                bodyContent.Should().Contain("<form action");
                bodyContent.Should().Contain("<input type=\"hidden\" name=\"SAMLRequest\"");
            }
        }
예제 #11
0
        public async void EnvInvoke_ReturnsExpected()
        {
            // arrange
            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.AddInMemoryCollection(OwinTestHelpers.Appsettings);
            var config = configurationBuilder.Build();
            var ep     = new EnvEndpoint(new EnvEndpointOptions(), config, new GenericHostingEnvironment()
            {
                EnvironmentName = "EnvironmentName"
            });
            var mgmt = new CloudFoundryManagementOptions()
            {
                Path = "/"
            };
            var middle = new EndpointOwinMiddleware <EnvironmentDescriptor>(null, ep, new List <IManagementOptions> {
                mgmt
            });
            var context = OwinTestHelpers.CreateRequest("GET", "/env");

            // act
            var json = await middle.InvokeAndReadResponse(context);

            // assert
            var expected = "{\"activeProfiles\":[\"EnvironmentName\"],\"propertySources\":[{\"properties\":{\"Logging:IncludeScopes\":{\"value\":\"false\"},\"Logging:LogLevel:Default\":{\"value\":\"Warning\"},\"Logging:LogLevel:Pivotal\":{\"value\":\"Information\"},\"Logging:LogLevel:Steeltoe\":{\"value\":\"Information\"},\"management:endpoints:enabled\":{\"value\":\"true\"},\"management:endpoints:path\":{\"value\":\"/cloudfoundryapplication\"}},\"name\":\"MemoryConfigurationProvider\"}]}";

            Assert.Equal(expected, json);
        }
        public async void HeapDumpInvoke_ReturnsExpected()
        {
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                var           opts          = new HeapDumpEndpointOptions();
                var           mopts         = TestHelpers.GetManagementOptions(opts);
                LoggerFactory loggerFactory = new LoggerFactory();
                loggerFactory.AddConsole(minLevel: LogLevel.Debug);
                var logger1 = loggerFactory.CreateLogger <HeapDumper>();
                var logger2 = loggerFactory.CreateLogger <HeapDumpEndpoint>();
                var logger3 = loggerFactory.CreateLogger <HeapDumpEndpointOwinMiddleware>();

                HeapDumper obs     = new HeapDumper(opts, logger: logger1);
                var        ep      = new HeapDumpEndpoint(opts, obs, logger2);
                var        middle  = new HeapDumpEndpointOwinMiddleware(null, ep, mopts, logger3);
                var        context = OwinTestHelpers.CreateRequest("GET", "/cloudfoundryapplication/heapdump", GetResponseBodyStream());
                await middle.Invoke(context);

                context.Response.Body.Seek(0, SeekOrigin.Begin);
                byte[] buffer = new byte[1024];
                await context.Response.Body.ReadAsync(buffer, 0, 1024);

                Assert.NotEqual(0, buffer[0]);
            }
        }
예제 #13
0
        public void CommandResultExtensions_DoesNotApplyCookieWhenNoNameSet()
        {
            var cr = new CommandResult()
            {
                RequestState = new StoredRequestState(
                    new EntityId("http://idp.example.com"),
                    new Uri("http://sp.example.com/loggedout"),
                    new Saml2Id("id123"),
                    null),
                SetCookieName = null
            };

            var context = OwinTestHelpers.CreateOwinContext();

            var dataProtector = new StubDataProtector();

            cr.Apply(context, dataProtector);

            var setCookieHeader = context.Response.Headers["Set-Cookie"];

            var protectedData = HttpRequestData.ConvertBinaryData(
                StubDataProtector.Protect(cr.GetSerializedRequestState()));

            setCookieHeader.Should().Be(null);
        }
예제 #14
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");
        }
예제 #15
0
        public void OwinContextExtensionsTests_ToHttpRequestData_HandlesRelayStateWithoutCookie()
        {
            var ctx = OwinTestHelpers.CreateOwinContext();

            ctx.Request.QueryString = new QueryString("RelayState", "SomeState");

            ctx.Invoking(async c => await c.ToHttpRequestData(null))
            .ShouldNotThrow();
        }
예제 #16
0
        public async Task OwinContextExtensionsTests_ToHttpRequestData_ApplicationNotInRoot()
        {
            var ctx = OwinTestHelpers.CreateOwinContext();

            ctx.Request.PathBase = new PathString("/ApplicationPath");

            var subject = await ctx.ToHttpRequestData();

            subject.ApplicationUrl.Should().Be(new Uri("http://sp.example.com/ApplicationPath"));
        }
예제 #17
0
        public async Task KentorAuthServicesAuthenticationMiddleware_AugmentsGeneratedClaimsWithLogoutInfo()
        {
            var context = OwinTestHelpers.CreateOwinContext();

            string[] specifiedAuthTypes = null;

            context.Set <AuthenticateDelegate>("security.Authenticate",
                                               (authTypes, callback, state) =>
            {
                specifiedAuthTypes      = authTypes;
                var originalNameIdClaim = new Claim(ClaimTypes.NameIdentifier, "Saml2NameId", null, "http://idp.example.com");
                originalNameIdClaim.Properties[ClaimProperties.SamlNameIdentifierFormat] = "urn:format";

                callback(new ClaimsIdentity(new Claim[]
                {
                    originalNameIdClaim,
                    new Claim(AuthServicesClaimTypes.SessionIndex, "SessionId", null, "http://idp.example.com"),
                    new Claim(ClaimTypes.Role, "SomeRole", null, "http://idp.example.com")
                }, "Federation"),
                         new Dictionary <string, string>(),
                         new Dictionary <string, object>(),
                         state);
                return(Task.FromResult(0));
            });

            var options = new KentorAuthServicesAuthenticationOptions(true);

            var subject = new KentorAuthServicesAuthenticationMiddleware(
                new StubOwinMiddleware(303, grant: new AuthenticationResponseGrant(
                                           new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, "ApplicationNameId")
            }, "ApplicationIdentity"), new AuthenticationProperties())),
                CreateAppBuilder(),
                options);

            await subject.Invoke(context);

            specifiedAuthTypes.Should().HaveCount(1)
            .And.Subject.Single().Should().Be(DefaultSignInAsAuthenticationType);

            var expectedLogoutNameIdClaim = new Claim(AuthServicesClaimTypes.LogoutNameIdentifier, "Saml2NameId", null, "http://idp.example.com");

            expectedLogoutNameIdClaim.Properties[ClaimProperties.SamlNameIdentifierFormat] = "urn:format";

            var expected = new ClaimsIdentity(new Claim[]
            {
                new Claim(ClaimTypes.NameIdentifier, "ApplicationNameId"),
                new Claim(AuthServicesClaimTypes.SessionIndex, "SessionId", null, "http://idp.example.com"),
                expectedLogoutNameIdClaim
            }, "ApplicationIdentity");

            context.Authentication.AuthenticationResponseGrant.Identity
            .ShouldBeEquivalentTo(expected, opt => opt.IgnoringCyclicReferences());
        }
예제 #18
0
        public async Task AuthServicesUrls_Ctor_FromOwinHttpRequestData_PublicOrigin()
        {
            var ctx     = OwinTestHelpers.CreateOwinContext();
            var options = StubFactory.CreateOptionsPublicOrigin(new Uri("https://my.public.origin:8443/"));
            var subject = await ctx.ToHttpRequestData(null);

            var urls = new AuthServicesUrls(subject, options.SPOptions);

            urls.AssertionConsumerServiceUrl.ShouldBeEquivalentTo("https://my.public.origin:8443/AuthServices/Acs");
            urls.SignInUrl.ShouldBeEquivalentTo("https://my.public.origin:8443/AuthServices/SignIn");
        }
예제 #19
0
        public async void GetPermissions_ReturnsExpected()
        {
            var opts    = new CloudFoundryOptions();
            var middle  = new CloudFoundrySecurityOwinMiddleware(null, opts, null);
            var context = OwinTestHelpers.CreateRequest("GET", "/");
            var result  = await middle.GetPermissions(context);

            Assert.NotNull(result);
            Assert.Equal(Endpoint.Security.Permissions.NONE, result.Permissions);
            Assert.Equal(HttpStatusCode.Unauthorized, result.Code);
        }
        public async void CloudFoundryInvoke_ReturnsExpected()
        {
            // arrange
            var middle  = new CloudFoundryEndpointOwinMiddleware(null, new TestCloudFoundryEndpoint(new CloudFoundryOptions()));
            var context = OwinTestHelpers.CreateRequest("GET", "/");

            // act
            var json = await middle.InvokeAndReadResponse(context);

            // assert
            Assert.Equal("{\"type\":\"steeltoe\",\"_links\":{}}", json);
        }
예제 #21
0
        public async Task KentorAuthServicesAuthenticationMiddleware_NoRedirectWithoutChallenge()
        {
            var middleware = new KentorAuthServicesAuthenticationMiddleware(
                new StubOwinMiddleware(401, null), CreateAppBuilder(),
                new KentorAuthServicesAuthenticationOptions(true));

            var context = OwinTestHelpers.CreateOwinContext();

            await middleware.Invoke(context);

            context.Response.StatusCode.Should().Be(401);
        }
예제 #22
0
        public async void LoggersInvoke_ReturnsExpected()
        {
            var ep      = new TestLoggersEndpoint(new LoggersOptions());
            var middle  = new LoggersEndpointOwinMiddleware(null, ep);
            var context = OwinTestHelpers.CreateRequest("GET", "/loggers");
            await middle.Invoke(context);

            context.Response.Body.Seek(0, SeekOrigin.Begin);
            StreamReader rdr  = new StreamReader(context.Response.Body);
            string       json = await rdr.ReadToEndAsync();

            Assert.Equal("{}", json);
        }
        public async void TraceInvoke_ReturnsExpected()
        {
            // arrange
            var opts    = new TraceOptions();
            var ep      = new TestTraceEndpoint(opts, new TraceDiagnosticObserver(opts));
            var middle  = new EndpointOwinMiddleware <List <TraceResult> >(null, ep);
            var context = OwinTestHelpers.CreateRequest("GET", "/trace");

            // act
            var json = await middle.InvokeAndReadResponse(context);

            // assert
            Assert.Equal("[]", json);
        }
예제 #24
0
        public async Task KentorAuthServicesAuthenticationMiddleware_RedirectsOnAuthChallenge()
        {
            var middleware = new KentorAuthServicesAuthenticationMiddleware(
                new StubOwinMiddleware(401, new AuthenticationResponseChallenge(
                                           new string[] { "KentorAuthServices" }, null)), CreateAppBuilder(),
                new KentorAuthServicesAuthenticationOptions(true));

            var context = OwinTestHelpers.CreateOwinContext();

            await middleware.Invoke(context);

            context.Response.StatusCode.Should().Be(303);
            context.Response.Headers["Location"].Should().StartWith("https://idp.example.com/idp");
        }
예제 #25
0
        public async Task KentorAuthServicesAuthenticationMiddleware_NoRedirectOnNon401()
        {
            var middleware = new KentorAuthServicesAuthenticationMiddleware(
                new StubOwinMiddleware(200, new AuthenticationResponseChallenge(
                                           new string[] { "KentorAuthServices" }, null)), CreateAppBuilder(),
                new KentorAuthServicesAuthenticationOptions(true));

            var context = OwinTestHelpers.CreateOwinContext();

            await middleware.Invoke(context);

            context.Response.StatusCode.Should().Be(200);
            context.Response.Headers["Location"].Should().BeNull();
        }
예제 #26
0
        public async void HypermediaEndpointInvoke_ReturnsExpected()
        {
            // arrange
            var mgmtOptions = new List <IManagementOptions> {
                new ActuatorManagementOptions()
            };
            var middle = new ActuatorHypermediaEndpointOwinMiddleware(null, new TestActuatorHypermediaEndpoint(new HypermediaEndpointOptions(), mgmtOptions), mgmtOptions);

            var context = OwinTestHelpers.CreateRequest("GET", "/actuator");

            // act
            var json = await middle.InvokeAndReadResponse(context);

            // assert
            Assert.Equal("{\"type\":\"steeltoe\",\"_links\":{}}", json);
        }
예제 #27
0
        public async Task OwinContextExtensionsTests_ToHttpRequestData_ReadsRelayStateCookie()
        {
            var ctx = OwinTestHelpers.CreateOwinContext();

            ctx.Request.QueryString = new QueryString("RelayState", "SomeState");

            var cookieData = "???>>>Some_Cookie_Data";

            var protectedData = StubDataProtector.Protect(cookieData);

            ctx.Request.Headers["Cookie"] = $"Kentor.SomeState={protectedData}";

            var actual = await ctx.ToHttpRequestData(StubDataProtector.Unprotect);

            actual.CookieData.Should().Be(cookieData);
        }
예제 #28
0
        public async Task OwinContextExtensionsTests_ToHttpRequestData()
        {
            IOwinContext ctx = OwinTestHelpers.CreateOwinContext();

            ctx.Request.Body        = new MemoryStream(Encoding.UTF8.GetBytes("Input1=Value1&Input2=Value2"));
            ctx.Request.Method      = "POST";
            ctx.Request.ContentType = "application/x-www-form-urlencoded";

            var subject = await ctx.ToHttpRequestData();

            subject.Url.Should().Be(ctx.Request.Uri);
            subject.Form.Count.Should().Be(2);
            subject.Form["Input1"].Should().Be("Value1");
            subject.Form["Input2"].Should().Be("Value2");
            subject.HttpMethod.Should().Be("POST");
        }
예제 #29
0
        public async Task KentorAuthServicesAuthenticationMiddleware_DoesntRedirectOnUnSpecificAuthChallenge_WhenPassive()
        {
            var middleware = new KentorAuthServicesAuthenticationMiddleware(
                new StubOwinMiddleware(401, new AuthenticationResponseChallenge(
                                           new string[0], null)), CreateAppBuilder(),
                new KentorAuthServicesAuthenticationOptions(true)
            {
                AuthenticationMode = AuthenticationMode.Passive
            });

            var context = OwinTestHelpers.CreateOwinContext();

            await middleware.Invoke(context);

            context.Response.StatusCode.Should().Be(401);
        }
        public async void InfoInvoke_ReturnsExpected()
        {
            // arrange
            var ep = new TestInfoEndpoint(new InfoOptions(), new List <IInfoContributor>()
            {
                new GitInfoContributor()
            });
            var middle  = new EndpointOwinMiddleware <Dictionary <string, object> >(null, ep);
            var context = OwinTestHelpers.CreateRequest("GET", "/info");

            // act
            var json = await middle.InvokeAndReadResponse(context);

            // assert
            Assert.Equal("{}", json);
        }