Example #1
0
        public void KentorAuthServicesAuthenticationOptions_Ctor_SetsDefault()
        {
            var subject = new KentorAuthServicesAuthenticationOptions(true);

            subject.Description.Caption.Should().Be(Constants.DefaultCaption);
            subject.AuthenticationMode.Should().Be(AuthenticationMode.Passive);
        }
Example #2
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();
        }
Example #3
0
        private void ConfigureSaml2(IAppBuilder app, string signInAsType)
        {
            var options = new KentorAuthServicesAuthenticationOptions(false)
            {
                SPOptions = new SPOptions
                {
                    EntityId = new EntityId("http://localhost:4589/IdSrv3/AuthServices"),
                },
                SignInAsAuthenticationType = signInAsType,
                Caption = "SAML2p"
            };

            UseIdSrv3LogoutOnFederatedLogout(app, options);

            options.SPOptions.SystemIdentityModelIdentityConfiguration.AudienceRestriction.AudienceMode
                = AudienceUriMode.Never;

            options.SPOptions.ServiceCertificates.Add(new X509Certificate2(
                                                          AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "/App_Data/Kentor.AuthServices.Tests.pfx"));

            options.IdentityProviders.Add(new IdentityProvider(
                                              new EntityId("http://localhost:52071/Metadata"),
                                              options.SPOptions)
            {
                LoadMetadata = true
            });

            app.UseKentorAuthServicesAuthentication(options);
        }
Example #4
0
        public void KentorAuthServicesAuthenticationOptions_Ctor_IgnoresConfiguration()
        {
            var subject = new KentorAuthServicesAuthenticationOptions(false);

            subject.SPOptions.Should().BeNull();
            subject.IdentityProviders.IsEmpty.Should().BeTrue();
        }
Example #5
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");
        }
        private static KentorAuthServicesAuthenticationOptions CreateAuthServicesOptions()
        {
            var spOptions = new SPOptions
            {
                EntityId  = new EntityId(AuthConfig.ApplicationIdpEntityId),
                ReturnUrl = AuthConfig.ExternalAuthDefaultCallbackUrl,
                AuthenticateRequestSigningBehavior = SigningBehavior.Always
            };

            spOptions.ServiceCertificates.Add(new ServiceCertificate
            {
                Use         = CertificateUse.Signing,
                Certificate = GetSPCertificateFromAppData()
            });

            var authServicesOptions = new KentorAuthServicesAuthenticationOptions(false)
            {
                SPOptions = spOptions
            };

            var idp = new IdentityProvider(new EntityId(AuthConfig.ExternalIdpEntityId.AbsoluteUri), spOptions)
            {
                AllowUnsolicitedAuthnResponse = true,
                Binding                 = Saml2BindingType.HttpRedirect,
                MetadataLocation        = AuthConfig.ExternalIdpMetadataPath,
                WantAuthnRequestsSigned = true
            };

            idp.SigningKeys.AddConfiguredKey(new X509Certificate2(AuthConfig.ExternalIdpCertificatePath));
            authServicesOptions.IdentityProviders.Add(idp);
            return(authServicesOptions);
        }
Example #7
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");
        }
Example #8
0
        private void ConfigureIdentityProviders(IAppBuilder app, string signInAsType)
        {
            var authServicesOptions = new KentorAuthServicesAuthenticationOptions(false)
            {
                SPOptions = new SPOptions
                {
                    EntityId = new EntityId("https://localhost:44300/identity/AuthServices")
                },
                SignInAsAuthenticationType = signInAsType,
                AuthenticationType         = "okta",
                Caption = "Okta"
            };

            authServicesOptions.IdentityProviders.Add(new IdentityProvider(
                                                          new EntityId("http://www.okta.com/exk5dcmpavv9xKCZC0h7"), authServicesOptions.SPOptions)
            {
                LoadMetadata = true,
                MetadataUrl  = new Uri("https://dev-169318.oktapreview.com/app/exk5dcmpavv9xKCZC0h7/sso/saml/metadata"),
                AllowUnsolicitedAuthnResponse = true
            });

            app.UseKentorAuthServicesAuthentication(authServicesOptions);

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions
            {
                AuthenticationType         = "Google",
                Caption                    = "Sign-in with Google",
                SignInAsAuthenticationType = signInAsType,

                ClientId     = "297503349559-dmgmcoqfpkr7kr93e3kh0kj4gfrigbgf.apps.googleusercontent.com",
                ClientSecret = "hllqf-f_5xvozZnG9YRvOfo1"
            });
        }
Example #9
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");
        }
Example #10
0
        private static KentorAuthServicesAuthenticationOptions CreateAuthServicesOptions()
        {
            var spOptions           = CreateSPOptions();
            var authServicesOptions = new KentorAuthServicesAuthenticationOptions(false)
            {
                SPOptions = spOptions
            };

            var idp = new IdentityProvider(new EntityId("https://sso.local.com/saml/80e7278f-b61c-4e21-8f43-155cabb8846a/Metadata"), spOptions)
            {
                AllowUnsolicitedAuthnResponse = true,
                Binding = Saml2BindingType.HttpRedirect,
                SingleSignOnServiceUrl = new Uri("https://sso.local.com/saml/80e7278f-b61c-4e21-8f43-155cabb8846a")
            };

            idp.SigningKeys.AddConfiguredKey(
                new X509Certificate2(
                    HostingEnvironment.MapPath(
                        "~/App_Data/Kentor.AuthServices.StubIdp.cer")));

            authServicesOptions.IdentityProviders.Add(idp);

            // It's enough to just create the federation and associate it
            // with the options. The federation will load the metadata and
            // update the options with any identity providers found.
            new Federation("https://sso.local.com/saml/80e7278f-b61c-4e21-8f43-155cabb8846a/Federation", true, authServicesOptions);

            return(authServicesOptions);
        }
Example #11
0
        private static KentorAuthServicesAuthenticationOptions CreateAuthServicesOptions()
        {
            var spOptions           = CreateSPOptions();
            var authServicesOptions = new KentorAuthServicesAuthenticationOptions(false)
            {
                SPOptions = spOptions
            };

            authServicesOptions.IdentityProviders.Add(
                new IdentityProvider(
                    new EntityId("http://stubidp.kentor.se/Metadata"), spOptions)
            {
                AllowUnsolicitedAuthnResponse = true,
                Binding = Saml2BindingType.HttpRedirect,
                SingleSignOnServiceUrl = new Uri("http://stubidp.kentor.se"),
                SigningKey             = new X509Certificate2(
                    HostingEnvironment.MapPath("~/App_Data/Kentor.AuthServices.StubIdp.pfx"))
                                         .PublicKey.Key
            });

            // It's enough to just create the federation and associate it
            // with the options. The federation will load the metadata and
            // update the options with any identity providers found.
            new Federation(new Uri("http://localhost:52071/Federation"), true, authServicesOptions);

            return(authServicesOptions);
        }
Example #12
0
        public void KentorAuthServicesAuthenticationOptions_SetsDefault()
        {
            var subject = new KentorAuthServicesAuthenticationOptions();

            subject.Description.Caption.Should().Be(Constants.DefaultCaption);
            subject.AuthenticationMode.Should().Be(AuthenticationMode.Passive);
            subject.MetadataPath.ToString().Should().Be("/AuthServices");
        }
Example #13
0
        public void KentorAuthServicesAuthenticationOptions_Caption()
        {
            var subject = new KentorAuthServicesAuthenticationOptions(false)
            {
                Caption = "MyCaption"
            };

            subject.Caption.Should().Be("MyCaption");
            subject.Description.Caption.Should().Be("MyCaption");
        }
        public void KentorAuthServicesAuthenticationExtensions_UseKentorAuthServicesAuthentication()
        {
            var app = Substitute.For <IAppBuilder>();

            var options = new KentorAuthServicesAuthenticationOptions(true);

            app.UseKentorAuthServicesAuthentication(options);

            app.Received().Use(typeof(KentorAuthServicesAuthenticationMiddleware), app, options);
        }
Example #15
0
        public void KentorAuthServicesAuthenticationOptions_Ctor_LoadsConfiguration()
        {
            var subject = new KentorAuthServicesAuthenticationOptions(true);

            subject.SPOptions.EntityId.Id.Should().Be("https://github.com/KentorIT/authservices");

            subject.IdentityProviders.IsEmpty.Should().BeFalse();
            subject.IdentityProviders[new EntityId("https://idp.example.com")]
            .SingleSignOnServiceUrl.Should().Be("https://idp.example.com/idp");
        }
Example #16
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());
        }
Example #17
0
        public void KentorAuthServicesAuthenticationMiddleware_CtorSetsDefaultAuthOption()
        {
            var options = new KentorAuthServicesAuthenticationOptions(true);

            options.SignInAsAuthenticationType.Should().BeNull();

            var middleware = new KentorAuthServicesAuthenticationMiddleware(new StubOwinMiddleware(0, null),
                                                                            CreateAppBuilder(), options);

            options.SignInAsAuthenticationType.Should().Be(DefaultSignInAsAuthenticationType);
        }
Example #18
0
        public void KentorAuthServicesAuthenticationOptions_Ctor_LoadsFederationFromConfigurationAndRegistersIdp()
        {
            var subject = new KentorAuthServicesAuthenticationOptions(true);

            Action a = () =>
            {
                var i = subject.IdentityProviders[new EntityId("http://idp.federation.example.com/metadata")];
            };

            a.ShouldNotThrow();
        }
Example #19
0
        public void KentorAuthServicesAuthenticationMiddleware_Ctor_NullCheckOptionsSpOptions()
        {
            var options = new KentorAuthServicesAuthenticationOptions(false);

            Action a = () => new KentorAuthServicesAuthenticationMiddleware(
                new StubOwinMiddleware(404),
                CreateAppBuilder(),
                options);

            a.ShouldThrow <ConfigurationErrorsException>()
            .WithMessage("The options.SPOptions property cannot be null. There is an implementation class Kentor.AuthServices.Configuration.SPOptions that you can instantiate. The EntityId property of that class is mandatory. It must be set to the EntityId used to represent this system.");
        }
        /// <summary>
        /// Add Kentor AuthServices SAML2 authentication to the Owin pipeline.
        /// </summary>
        /// <param name="app">Owin pipeline builder.</param>
        /// <param name="options">Options for the middleware.</param>
        /// <returns></returns>
        public static IAppBuilder UseKentorAuthServicesAuthentication(this IAppBuilder app,
                                                                      KentorAuthServicesAuthenticationOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }

            app.Use(typeof(KentorAuthServicesAuthenticationMiddleware), app, options);

            return(app);
        }
Example #21
0
        public void Configuration(IAppBuilder app)
        {
            var authServicesOptions = new KentorAuthServicesAuthenticationOptions(false)
            {
                SPOptions = new SPOptions
                {
                    EntityId = new EntityId("http://sp.example.com")
                },

                SignInAsAuthenticationType = "External",
                AuthenticationType         = "saml2p",
                Caption = "SAML2p"
            };

            authServicesOptions.IdentityProviders.Add(new IdentityProvider(new EntityId("http://stubidp.kentor.se/Metadata"), authServicesOptions.SPOptions)
            {
                LoadMetadata = true
            });


            var cors    = new InMemoryCorsPolicyService(Clients.Get());
            var factory = new IdentityServerServiceFactory()
                          .UseInMemoryClients(Clients.Get())
                          .UseInMemoryScopes(Scopes.Get())
                          .UseInMemoryUsers(Users.Get());

            factory.CorsPolicyService = new Registration <ICorsPolicyService>(cors);

            var options = new IdentityServerOptions
            {
                Factory = factory,
                AuthenticationOptions = new AuthenticationOptions()
                {
                    IdentityProviders = (appBuilder, signInAsType) =>
                    {
                        Kentor.AuthServices.Configuration.Options.GlobalEnableSha256XmlSignatures();
                        app.UseKentorAuthServicesAuthentication(authServicesOptions);
                    }
                },
                LoggingOptions = new LoggingOptions()
                {
                    EnableHttpLogging       = true,
                    EnableKatanaLogging     = true,
                    EnableWebApiDiagnostics = true
                }
            };

            app.UseIdentityServer(options);
        }
Example #22
0
        public void KentorAuthServicesAuthenticationMiddleware_Ctor_NullCheckOptionsSpOptionsEntityId()
        {
            var options = new KentorAuthServicesAuthenticationOptions(false)
            {
                SPOptions = new SPOptions()
            };

            Action a = () => new KentorAuthServicesAuthenticationMiddleware(
                new StubOwinMiddleware(404),
                CreateAppBuilder(),
                options);

            a.ShouldThrow <ConfigurationErrorsException>()
            .WithMessage("The SPOptions.EntityId property cannot be null. It must be set to the EntityId used to represent this system.");
        }
Example #23
0
        private static KentorAuthServicesAuthenticationOptions CreateAuthServicesOptions()
        {
            //Retrieve settings
            var commonLoginUrl        = RetrieveAppSetting("CommonLoginUrl");
            var singleSignOnIssuerUrl = RetrieveAppSetting("SingleSignOnIssuerUrl");
            var singleSignOnTargetUrl = RetrieveAppSetting("SingleSignOnTargetUrl");
            var singleLogoutTargetUrl = WebConfigurationManager.AppSettings["SingleLogoutTargetUrl"];

            //Configure service provider
            var serviceProvider = new SPOptions
            {
                EntityId  = new EntityId(commonLoginUrl),
                ReturnUrl = new Uri(commonLoginUrl + "/Account/ExternalLoginCallback"),
            };

            //Configure identity provider
            var identityProvider = new IdentityProvider(new EntityId(singleSignOnIssuerUrl), serviceProvider)
            {
                AllowUnsolicitedAuthnResponse = true,
                Binding = Saml2BindingType.HttpRedirect,
                SingleSignOnServiceUrl = new Uri(singleSignOnTargetUrl)
            };

            //Set single logout if it has been specified
            if (!string.IsNullOrEmpty(singleLogoutTargetUrl))
            {
                identityProvider.SingleLogoutServiceUrl = new Uri(singleLogoutTargetUrl);
            }

            //Load certificate
            var certificatePath = HostingEnvironment.MapPath("~/App_Data/IdentityProviderCertificate.cer");

            if (string.IsNullOrEmpty(certificatePath))
            {
                throw new Exception($"Could not find the identity provider certificate path. Value given was: {certificatePath}.");
            }
            identityProvider.SigningKeys.AddConfiguredKey(new X509Certificate2(certificatePath));

            //Return authenticaton options
            var authenticationOptions = new KentorAuthServicesAuthenticationOptions(false)
            {
                SPOptions = serviceProvider
            };

            authenticationOptions.IdentityProviders.Add(identityProvider);
            return(authenticationOptions);
        }
Example #24
0
        private static KentorAuthServicesAuthenticationOptions CreateAuthServicesOptions()
        {
            var authServicesOptions = new KentorAuthServicesAuthenticationOptions(false)
            {
                SPOptions = new SPOptions {
                    EntityId = new EntityId("urn:" + ConfigurationManager.AppSettings["auth0:ApplicationName"]), ReturnUrl = new Uri(ConfigurationManager.AppSettings["auth0:ReturnUrl"])
                }
            };

            authServicesOptions.IdentityProviders.Add(new IdentityProvider(new EntityId("urn:" + ConfigurationManager.AppSettings["auth0:Domain"]), authServicesOptions.SPOptions)
            {
                AllowUnsolicitedAuthnResponse = true,
                MetadataUrl = new Uri(String.Format("https://{0}/samlp/metadata/{1}", ConfigurationManager.AppSettings["auth0:Domain"], ConfigurationManager.AppSettings["auth0:ClientId"])),
                Binding     = Saml2BindingType.HttpPost
            });
            return(authServicesOptions);
        }
Example #25
0
        private static KentorAuthServicesAuthenticationOptions CreateAuthServicesOptions()
        {
            var authServicesOptions = new KentorAuthServicesAuthenticationOptions(false)
            {
                SPOptions = new SPOptions {
                    EntityId = new EntityId("urn:MyApp"), ReturnUrl = new Uri("http://localhost:3500/")
                }
            };

            authServicesOptions.IdentityProviders.Add(new IdentityProvider(new EntityId("urn:YOUR-TENANT.auth0.com"), authServicesOptions.SPOptions)
            {
                AllowUnsolicitedAuthnResponse = true,
                MetadataUrl = new Uri("https://YOUR-TENANT.auth0.com/samlp/metadata/YOUR-CLIENT-ID"),
                Binding     = Saml2BindingType.HttpPost
            });
            return(authServicesOptions);
        }
        private void ConfigureSecurity(IAppBuilder app)
        {
            app.Use(async(context, next) => { await next.Invoke(); });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            app.Use(async(context, next) => { await next.Invoke(); });

            var authOptions = new KentorAuthServicesAuthenticationOptions(true)
            {
                SPOptions = { Logger = new SeriLogAdapter(Log.Logger) }
            };

            var authServiceNotifications = new AuthServiceNotifications(authOptions.SPOptions, true);

            authOptions.Notifications.AcsCommandResultCreated += authServiceNotifications.AcsCommandResultCreated;

            app.UseKentorAuthServicesAuthentication(authOptions);

            app.Use(async(context, next) => { await next.Invoke(); });

            Log.Information("ConfigureSecurity: tokenExpiry={TokenExpiryInMinutes}",
                            AuthenticationHelper.TokenExpiryInMinutes);

            var oAuthAuthorizationServerOptions = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(AuthenticationHelper.TokenExpiryInMinutes),
                Provider = new AuthorizationServerProvider()
            };

            app.UseOAuthAuthorizationServer(oAuthAuthorizationServerOptions);

            app.Use(async(context, next) => { await next.Invoke(); });

            var authNOptions = AuthenticationHelper.WebApiBearerAuthenticationOptions =
                new OAuthBearerAuthenticationOptions();

            app.UseOAuthBearerAuthentication(authNOptions);

            app.Use(async(context, next) => { await next.Invoke(); });
        }
Example #27
0
        public async Task KentorAuthServicesAuthenticationMiddleware_HandlesLogoutResponse()
        {
            var app     = CreateAppBuilder();
            var options = new KentorAuthServicesAuthenticationOptions(true);
            var subject = new KentorAuthServicesAuthenticationMiddleware(
                null,
                app,
                options);

            var context = OwinTestHelpers.CreateOwinContext();

            var relayState = "MyRelayState";
            var response   = new Saml2LogoutResponse(Saml2StatusCode.Success)
            {
                DestinationUrl     = new Uri("https://sp.example.com/AuthServices/Logout"),
                RelayState         = relayState,
                SigningCertificate = SignedXmlHelper.TestCert,
                Issuer             = new EntityId("https://idp.example.com")
            };
            var requestUri = Saml2Binding.Get(Saml2BindingType.HttpRedirect).Bind(response).Location;

            var cookieData = HttpRequestData.EscapeBase64CookieValue(
                Convert.ToBase64String(
                    options.DataProtector.Protect(
                        Encoding.UTF8.GetBytes("http://loggedout.example.com/"))));

            context.Request.Headers["Cookie"] = $"Kentor.{relayState}={cookieData}";
            context.Request.Path        = new PathString(requestUri.AbsolutePath);
            context.Request.QueryString = new QueryString(requestUri.Query.TrimStart('?'));

            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().Be("http://loggedout.example.com/");
        }
        private void ConfigureIdentityProviders(IAppBuilder app, string signInAsType)
        {
            // Configure Kentor SAML Identity Provider
            var authServicesOptions = new KentorAuthServicesAuthenticationOptions(false)
            {
                SPOptions = new SPOptions
                {
                    EntityId  = new EntityId(BaseUrl),
                    ReturnUrl = new Uri(BaseUrl),
                    AttributeConsumingServices = { GetAttributeService() },
                    //WantAssertionsSigned = true,
                    //AuthenticateRequestSigningBehavior = SigningBehavior.IfIdpWantAuthnRequestsSigned // TODO: decide what needs to be here in prod
                },
                SignInAsAuthenticationType = signInAsType,
                AuthenticationType         = "saml2p",
                Caption = "SAML2p",
            };

            // Map claims Shibboleth->OIDC using a custom claims manager: https://github.com/KentorIT/authservices/blob/master/doc/ClaimsAuthenticationManager.md
            authServicesOptions.SPOptions.SystemIdentityModelIdentityConfiguration.ClaimsAuthenticationManager =
                new ShibbolethClaimsMapper();

            authServicesOptions.SPOptions.ServiceCertificates.Add(LoadCertificate());

            var ucdShibIdp = new IdentityProvider(
                new EntityId("urn:mace:incommon:ucdavis.edu"),
                authServicesOptions.SPOptions)
            {
                LoadMetadata     = true,
                MetadataLocation = "https://shibboleth.ucdavis.edu/idp/shibboleth",
                AllowUnsolicitedAuthnResponse = true,
            };

            ucdShibIdp.SigningKeys.AddConfiguredKey(LoadCertificate());
            authServicesOptions.IdentityProviders.Add(ucdShibIdp);

            // Federate against the IdP
            //new Federation(FederationUrl, true, authServicesOptions);

            app.UseKentorAuthServicesAuthentication(authServicesOptions);
        }
Example #29
0
        public async Task KentorAuthServicesAuthenticationMiddleware_RedirectRemembersReturnPath()
        {
            var returnUrl = "http://sp.example.com/returnurl";

            var options = new KentorAuthServicesAuthenticationOptions(true);
            var subject = new KentorAuthServicesAuthenticationMiddleware(
                new StubOwinMiddleware(401, new AuthenticationResponseChallenge(
                                           new string[] { "KentorAuthServices" }, new AuthenticationProperties()
            {
                RedirectUri = returnUrl
            })),
                CreateAppBuilder(), options);

            var context = OwinTestHelpers.CreateOwinContext();

            await subject.Invoke(context);

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

            storedState.ReturnUrl.Should().Be(returnUrl);
        }
Example #30
0
        // Using Kentor.AuthServices
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions {
                AuthenticationType = "cookie"
            });

            var spOptions = new SPOptions
            {
                EntityId = new EntityId("http://localhost:50155/AuthServices"),
                AuthenticateRequestSigningBehavior = SigningBehavior.Always
            };

            spOptions.ServiceCertificates.Add(new ServiceCertificate
            {
                Certificate = new X509Certificate2(HostingEnvironment.MapPath("~/testclient.pfx"), "test"),
                Use         = CertificateUse.Signing
            });

            var options = new KentorAuthServicesAuthenticationOptions(false)
            {
                SPOptions                  = spOptions,
                AuthenticationType         = "saml2p",
                SignInAsAuthenticationType = "cookie"
            };

            var idp = new IdentityProvider(new EntityId("http://localhost:5000"), options.SPOptions)
            {
                SingleSignOnServiceUrl = new Uri("http://localhost:5000/saml/sso"),
                Binding = Saml2BindingType.HttpRedirect,
                SingleLogoutServiceUrl     = new Uri("http://localhost:5000/saml/slo"),
                SingleLogoutServiceBinding = Saml2BindingType.HttpPost,
                WantAuthnRequestsSigned    = true
            };

            idp.SigningKeys.AddConfiguredKey(new X509Certificate2(HostingEnvironment.MapPath("~/idsrv3test.cer")));

            options.IdentityProviders.Add(idp);

            app.UseKentorAuthServicesAuthentication(options);
        }