Ejemplo n.º 1
0
            public Saml2HandlerTestContext()
            {
                var options = new Saml2Options();

                options.SPOptions.EntityId = new EntityId("http://sp.example.com/saml2");

                var idp = new IdentityProvider(
                    new EntityId("https://idp.example.com"),
                    options.SPOptions)
                {
                    SingleSignOnServiceUrl = new Uri("https://idp.example.com/sso"),
                    Binding = Saml2BindingType.HttpRedirect
                };

                idp.SigningKeys.AddConfiguredKey(SignedXmlHelper.TestCert);

                options.IdentityProviders.Add(idp);

                Options = new DummyOptionsMonitor(options);

                Subject = new Saml2Handler(
                    Options, LoggerFactory, UrlEncoder, Clock, new StubDataProtector());

                Subject.InitializeAsync(AuthenticationScheme, HttpContext)
                .Wait();
            }
 public ExtendedSaml2SecurityTokenHandlerTests(Saml2TestFixture fixture, ITestOutputHelper output)
 {
     _fixture = fixture;
     _output  = output;
     _options = new Saml2Options();
     _handler = new ExtendedSaml2SecurityTokenHandler(new ExtendedSaml2Serializer(), _options);
 }
Ejemplo n.º 3
0
        public void Saml2Options_Ctor_Defaults()
        {
            var subject = new Saml2Options();

            subject.CallbackPath.Value.Should()
            .Match("*CallbackPath*ModulePath*");
        }
        public void PostConfigureSaml2Options_PostConfigure_ProvidesDefaultCookieManager()
        {
            var options = new Saml2Options();

            var subject = new PostConfigureSaml2Options( null,
                TestHelpers.GetAuthenticationOptions() );

            subject.PostConfigure( null, options );

            options.CookieManager.Should().NotBeNull();
        }
        public void PostConfigureSaml2Options_PostConfigure_NullLoggerFactoryGivesNullLogger()
        {
            var options = new Saml2Options();

            options.SPOptions.Logger.Should().BeNull("Precondition");

            var subject = new PostConfigureSaml2Options(null);

            subject.PostConfigure(null, options);

            options.SPOptions.Logger.Should().BeOfType <NullLoggerAdapter>();
        }
        public void PostConfigureSaml2Options_PostConfigure_EnsureSignInSchemePreservesSetScheme()
        {
            var options = new Saml2Options();
            options.SignInScheme = "specificSignInScheme";

            var subject = new PostConfigureSaml2Options(null,
                TestHelpers.GetAuthenticationOptions());

            subject.PostConfigure(null, options);

            options.SignInScheme.Should().Be("specificSignInScheme");
        }
        public void PostConfigureSaml2Options_PostConfigure_CustomCookieManagerIsUsed()
        {
            var options = new Saml2Options();
            var cookieManager = Substitute.For<ICookieManager>();
            options.CookieManager = cookieManager;

            var subject = new PostConfigureSaml2Options( null,
                TestHelpers.GetAuthenticationOptions() );

            subject.PostConfigure( null, options );

            options.CookieManager.Should().BeSameAs( cookieManager );
        }
Ejemplo n.º 8
0
        public void PostConfigureSaml2Options_PostConfigure_EnsureSignInSchemeAssignsDefaultSignInScheme()
        {
            var options = new Saml2Options();

            options.SignInScheme.Should().BeNull("Precondition");

            var subject = new PostConfigureSaml2Options(null,
                                                        TestHelpers.GetAuthenticationOptions());

            subject.PostConfigure(null, options);

            options.SignInScheme.Should().Be(TestHelpers.defaultSignInScheme);
        }
        public void PostConfigureSaml2Options_PostConfigure_EnsureSignInSchemeFallbackDefaultScheme()
        {
            var options = new Saml2Options();

            options.SignInScheme.Should().BeNull("Precondition");

            var authOptions = TestHelpers.GetAuthenticationOptions();
            authOptions.Value.DefaultSignInScheme = null;
            authOptions.Value.DefaultScheme = "defaultScheme";

            var subject = new PostConfigureSaml2Options(null,authOptions);

            subject.PostConfigure(null, options);

            options.SignInScheme.Should().Be("defaultScheme");
        }
Ejemplo n.º 10
0
        public void PostConfigureSaml2Options_PostConfigure_Logger()
        {
            var options = new Saml2Options();

            options.SPOptions.Logger.Should().BeNull("Precondition");

            var loggerFactory = Substitute.For<ILoggerFactory>();
            var logger = new MockLogger();
            loggerFactory.CreateLogger<Saml2Handler>().Returns(logger);

            var subject = new PostConfigureSaml2Options(
                loggerFactory, TestHelpers.GetAuthenticationOptions());

            subject.PostConfigure(null, options);

            logger.ReceivedLogLevel.Should().Be(LogLevel.Debug);
            logger.ReceivedMessage.Should().Match("*enabled*");
        }
Ejemplo n.º 11
0
        public void Saml2AuthExtensions_AddSaml2_RegistersSaml2Scheme_DefaultScheme()
        {
            IServiceCollection serviceCollection = new ServiceCollection();
            var builder = new AuthenticationBuilder(serviceCollection);

            var configureOptionsCalled = false;

            builder.AddSaml2(options =>
            {
                configureOptionsCalled = true;
            }).Should().BeSameAs(builder);

            serviceCollection.Should().Contain(
                sc => sc.ImplementationType == typeof(Saml2Handler));

            serviceCollection.Should().Contain(
                sc => sc.ImplementationType == typeof(PostConfigureSaml2Options));

            var authOptions = new AuthenticationOptions();

            serviceCollection.Single(sd => sd.ServiceType == typeof(IConfigureOptions <AuthenticationOptions>))
            .ImplementationInstance.As <IConfigureOptions <AuthenticationOptions> >()
            .Configure(authOptions);

            var saml2Scheme = authOptions.Schemes.Single();

            saml2Scheme.Name.Should().Be(Saml2Defaults.Scheme);
            saml2Scheme.DisplayName.Should().Be(Saml2Defaults.DisplayName);
            saml2Scheme.HandlerType.Should().Be(typeof(Saml2Handler));

            var saml2Options = new Saml2Options();

            serviceCollection.Single(sd => sd.ServiceType == typeof(IConfigureOptions <Saml2Options>))
            .ImplementationInstance.As <ConfigureNamedOptions <Saml2Options> >()
            .Configure(Saml2Defaults.Scheme, saml2Options);

            configureOptionsCalled.Should().BeTrue();
        }
Ejemplo n.º 12
0
 public SessionCookieBuilder(Saml2Options options)
 {
     _options = options;
 }
Ejemplo n.º 13
0
        public static async Task <bool> CouldHandleAsync(this Saml2Options options, string scheme, HttpContext context)
        {
            // Determine this is a valid request for our handler
            if (!context.Request.Path.StartsWithSegments(options.SPOptions.ModulePath, StringComparison.Ordinal))
            {
                return(false);
            }

            var idp = options.IdentityProviders.IsEmpty ? null : options.IdentityProviders.Default;

            if (idp == null)
            {
                return(false);
            }

            if (context.Request.Query["scheme"].FirstOrDefault() == scheme)
            {
                return(true);
            }

            // Determine if the Authority matches the Referrer (short-cut)
            var referrer = context.Request.Headers["Referer"].FirstOrDefault();

            if (!string.IsNullOrWhiteSpace(referrer) &&
                Uri.TryCreate(referrer, UriKind.Absolute, out var referrerUri) &&
                (referrerUri.IsBaseOf(idp.SingleSignOnServiceUrl) ||
                 idp.SingleSignOnServiceUrl.IsBaseOf(referrerUri) ||
                 referrerUri.IsBaseOf(idp.SingleLogoutServiceUrl) ||
                 idp.SingleLogoutServiceUrl.IsBaseOf(referrerUri) ||
                 referrerUri.IsBaseOf(idp.SingleLogoutServiceResponseUrl) ||
                 idp.SingleLogoutServiceResponseUrl.IsBaseOf(referrerUri)))
            {
                return(true);
            }

            // We need to pull out and parse the response or request SAML envelope
            XmlElement assertion = null;

            try
            {
                if (string.Equals(context.Request.Method, "POST", StringComparison.OrdinalIgnoreCase) &&
                    context.Request.HasFormContentType)
                {
                    string encodedMessage;
                    if (context.Request.Form.TryGetValue("SAMLResponse", out var response))
                    {
                        encodedMessage = response.FirstOrDefault();
                    }
                    else
                    {
                        encodedMessage = context.Request.Form["SAMLRequest"];
                    }
                    if (string.IsNullOrWhiteSpace(encodedMessage))
                    {
                        return(false);
                    }
                    assertion = XmlHelpers.XmlDocumentFromString(
                        Encoding.UTF8.GetString(Convert.FromBase64String(encodedMessage)))?.DocumentElement;
                }
                else if (string.Equals(context.Request.Method, "GET", StringComparison.OrdinalIgnoreCase))
                {
                    var encodedPayload = context.Request.Query["SAMLRequest"].FirstOrDefault() ??
                                         context.Request.Query["SAMLResponse"].FirstOrDefault();
                    try
                    {
                        var payload = Convert.FromBase64String(encodedPayload);
                        using var compressed         = new MemoryStream(payload);
                        using var decompressedStream = new DeflateStream(compressed, CompressionMode.Decompress, true);
                        using var deCompressed       = new MemoryStream();
                        await decompressedStream.CopyToAsync(deCompressed);

                        assertion = XmlHelpers.XmlDocumentFromString(
                            Encoding.UTF8.GetString(deCompressed.GetBuffer(), 0, (int)deCompressed.Length))?.DocumentElement;
                    }
                    catch (FormatException ex)
                    {
                        throw new FormatException($"\'{encodedPayload}\' is not a valid Base64 encoded string: {ex.Message}", ex);
                    }
                }
            }
            catch
            {
                return(false);
            }

            if (assertion == null)
            {
                return(false);
            }

            // Double check the entity Ids
            var entityId = assertion["Issuer", Saml2Namespaces.Saml2Name]?.InnerText.Trim();

            return(string.Equals(entityId, idp.EntityId.Id, StringComparison.InvariantCultureIgnoreCase));
        }
Ejemplo n.º 14
0
        public static string ToXmlMetadata(this Saml2Options options)
        {
            IndexedEndpointType[] AssertionConsumerService = options.ServiceProvider.AssertionConsumerServices;
            EndpointType[]        SingleLogoutServices     = options.ServiceProvider.SingleLogoutServices;

            SamlCore.AspNetCore.Authentication.Saml2.Metadata.KeyDescriptorType[] KeyDescriptor = null;
            if (options.hasCertificate)
            {
                KeyDescriptor = new SamlCore.AspNetCore.Authentication.Saml2.Metadata.KeyDescriptorType[]
                {
                    new SamlCore.AspNetCore.Authentication.Saml2.Metadata.KeyDescriptorType()
                    {
                        useSpecified = true,
                        use          = KeyTypes.signing,
                        KeyInfo      = new SamlCore.AspNetCore.Authentication.Saml2.Metadata.KeyInfoType()
                        {
                            ItemsElementName = new [] { SamlCore.AspNetCore.Authentication.Saml2.Metadata.ItemsChoiceType2.X509Data },
                            Items            = new SamlCore.AspNetCore.Authentication.Saml2.Metadata.X509DataType[]
                            {
                                new SamlCore.AspNetCore.Authentication.Saml2.Metadata.X509DataType()
                                {
                                    Items            = new object[] { options.ServiceProvider.X509Certificate2.GetRawCertData() },
                                    ItemsElementName = new [] { SamlCore.AspNetCore.Authentication.Saml2.Metadata.ItemsChoiceType.X509Certificate }
                                }
                            }
                        }
                    },
                    new SamlCore.AspNetCore.Authentication.Saml2.Metadata.KeyDescriptorType()
                    {
                        useSpecified = true,
                        use          = KeyTypes.encryption,
                        KeyInfo      = new SamlCore.AspNetCore.Authentication.Saml2.Metadata.KeyInfoType()
                        {
                            ItemsElementName = new [] { SamlCore.AspNetCore.Authentication.Saml2.Metadata.ItemsChoiceType2.X509Data },
                            Items            = new SamlCore.AspNetCore.Authentication.Saml2.Metadata.X509DataType[]
                            {
                                new SamlCore.AspNetCore.Authentication.Saml2.Metadata.X509DataType()
                                {
                                    Items            = new object[] { options.ServiceProvider.X509Certificate2.GetRawCertData() },
                                    ItemsElementName = new [] { SamlCore.AspNetCore.Authentication.Saml2.Metadata.ItemsChoiceType.X509Certificate }
                                }
                            }
                        }
                    }
                };
            }
            var entityDescriptor = new EntityDescriptorType()
            {
                entityID = options.ServiceProvider.EntityId,
                Items    = new object[]
                {
                    new SPSSODescriptorType()
                    {
                        NameIDFormat = new [] { Saml2Constants.NameIDFormats.Email },
                        protocolSupportEnumeration    = new [] { Saml2Constants.Namespaces.Protocol },
                        AuthnRequestsSignedSpecified  = true,
                        AuthnRequestsSigned           = options.hasCertificate,
                        WantAssertionsSignedSpecified = true,
                        WantAssertionsSigned          = options.WantAssertionsSigned,
                        KeyDescriptor       = KeyDescriptor,
                        SingleLogoutService = SingleLogoutServices,

                        AssertionConsumerService  = AssertionConsumerService,
                        AttributeConsumingService = new AttributeConsumingServiceType[]
                        {
                            new AttributeConsumingServiceType
                            {
                                ServiceName = new localizedNameType[]
                                {
                                    new localizedNameType()
                                    {
                                        Value = options.ServiceProvider.ServiceName,
                                        lang  = options.ServiceProvider.Language
                                    }
                                },
                                ServiceDescription = new localizedNameType[]
                                {
                                    new localizedNameType()
                                    {
                                        Value = options.ServiceProvider.ServiceDescription,
                                        lang  = options.ServiceProvider.Language
                                    }
                                },
                                index              = 0,
                                isDefault          = true,
                                isDefaultSpecified = true,
                                RequestedAttribute = options.RequestedAttributes.ToArray()
                            }
                        },
                        Organization = new OrganizationType()
                        {
                            OrganizationDisplayName = new localizedNameType[] {
                                new localizedNameType
                                {
                                    lang  = options.ServiceProvider.Language,
                                    Value = options.ServiceProvider.OrganizationDisplayName
                                },
                            },
                            OrganizationName = new localizedNameType[] {
                                new localizedNameType
                                {
                                    lang  = options.ServiceProvider.Language,
                                    Value = options.ServiceProvider.OrganizationName
                                },
                            },
                            OrganizationURL = new localizedURIType[] {
                                new localizedURIType
                                {
                                    lang  = options.ServiceProvider.Language,
                                    Value = options.ServiceProvider.OrganizationURL
                                },
                            },
                        },
                    },
                },
                ContactPerson = new ContactType[]
                {
                    new ContactType()
                    {
                        Company         = options.ServiceProvider.ContactPerson.Company,
                        GivenName       = options.ServiceProvider.ContactPerson.GivenName,
                        EmailAddress    = options.ServiceProvider.ContactPerson.EmailAddress,
                        contactType     = options.ServiceProvider.ContactPerson.contactType,
                        TelephoneNumber = options.ServiceProvider.ContactPerson.TelephoneNumber
                    }
                }
            };

            //generate the sp metadata xml file
            string        xmlTemplate   = string.Empty;
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(EntityDescriptorType));

            using (MemoryStream memStm = new MemoryStream())
            {
                xmlSerializer.Serialize(memStm, entityDescriptor);
                memStm.Position = 0;
                xmlTemplate     = new StreamReader(memStm).ReadToEnd();
            }

            return(xmlTemplate);
        }
Ejemplo n.º 15
0
        public static async Task <bool> CouldHandleAsync(this Saml2Options options, string scheme, HttpContext context)
        {
            // Determine this is a valid request for our handler
            if (!context.Request.Path.StartsWithSegments(options.SPOptions.ModulePath, StringComparison.Ordinal))
            {
                return(false);
            }

            var idp = options.IdentityProviders.IsEmpty ? null : options.IdentityProviders.Default;

            if (idp == null)
            {
                return(false);
            }

            if (context.Request.Query["scheme"].FirstOrDefault() == scheme)
            {
                return(true);
            }

            // We need to pull out and parse the response or request SAML envelope
            XmlElement envelope = null;

            try
            {
                if (string.Equals(context.Request.Method, "POST", StringComparison.OrdinalIgnoreCase) &&
                    context.Request.HasFormContentType)
                {
                    string encodedMessage;
                    if (context.Request.Form.TryGetValue("SAMLResponse", out var response))
                    {
                        encodedMessage = response.FirstOrDefault();
                    }
                    else
                    {
                        encodedMessage = context.Request.Form["SAMLRequest"];
                    }
                    if (string.IsNullOrWhiteSpace(encodedMessage))
                    {
                        return(false);
                    }
                    envelope = XmlHelpers.XmlDocumentFromString(
                        Encoding.UTF8.GetString(Convert.FromBase64String(encodedMessage)))?.DocumentElement;
                }
                else if (string.Equals(context.Request.Method, "GET", StringComparison.OrdinalIgnoreCase))
                {
                    var encodedPayload = context.Request.Query["SAMLRequest"].FirstOrDefault() ??
                                         context.Request.Query["SAMLResponse"].FirstOrDefault();
                    try
                    {
                        var payload = Convert.FromBase64String(encodedPayload);
                        using var compressed         = new MemoryStream(payload);
                        using var decompressedStream = new DeflateStream(compressed, CompressionMode.Decompress, true);
                        using var deCompressed       = new MemoryStream();
                        await decompressedStream.CopyToAsync(deCompressed);

                        envelope = XmlHelpers.XmlDocumentFromString(
                            Encoding.UTF8.GetString(deCompressed.GetBuffer(), 0, (int)deCompressed.Length))?.DocumentElement;
                    }
                    catch (FormatException ex)
                    {
                        throw new FormatException($"\'{encodedPayload}\' is not a valid Base64 encoded string: {ex.Message}", ex);
                    }
                }
            }
            catch
            {
                return(false);
            }

            if (envelope == null)
            {
                return(false);
            }

            // Double check the entity Ids
            var entityId = envelope["Issuer", Saml2Namespaces.Saml2Name]?.InnerText.Trim();

            if (!string.Equals(entityId, idp.EntityId.Id, StringComparison.InvariantCultureIgnoreCase))
            {
                return(false);
            }

            if (options.SPOptions.WantAssertionsSigned)
            {
                var assertion         = envelope["Assertion", Saml2Namespaces.Saml2Name];
                var isAssertionSigned = assertion != null && XmlHelpers.IsSignedByAny(assertion, idp.SigningKeys,
                                                                                      options.SPOptions.ValidateCertificates, options.SPOptions.MinIncomingSigningAlgorithm);
                if (!isAssertionSigned)
                {
                    throw new Exception("Cannot verify SAML assertion signature.");
                }
            }

            return(true);
        }
        public async Task <IActionResult> Add([FromBody] SchemeData schemeData)
        {
            var schemeName = string.Format("{0}_{1}", schemeData.Domain, schemeData.Scheme);

            if (schemeData.Scheme == "Google")
            {
                IOptionsMonitorCache <GoogleOptions> oAuthOptionsCache = serviceProvider.GetRequiredService <IOptionsMonitorCache <GoogleOptions> >();
                OAuthPostConfigureOptions <GoogleOptions, GoogleHandler> oAuthPostConfigureOptions = serviceProvider.GetRequiredService <OAuthPostConfigureOptions <GoogleOptions, GoogleHandler> >();

                if (await schemeProvider.GetSchemeAsync(schemeName) == null)
                {
                    schemeProvider.AddScheme(new AuthenticationScheme(schemeName, schemeData.Scheme, typeof(GoogleHandler)));
                }
                else
                {
                    oAuthOptionsCache.TryRemove(schemeName);
                }
                var options = new GoogleOptions
                {
                    ClientId     = "xxxxxxx",
                    ClientSecret = "xxxxxxxxxxxx"
                };
                oAuthPostConfigureOptions.PostConfigure(schemeName, options);
                oAuthOptionsCache.TryAdd(schemeName, options);
            }
            else if (schemeData.Scheme == "Auth0")
            {
                IOptionsMonitorCache <Saml2Options> oAuthOptionsCache         = serviceProvider.GetRequiredService <IOptionsMonitorCache <Saml2Options> >();
                PostConfigureSaml2Options           oAuthPostConfigureOptions = serviceProvider.GetRequiredService <PostConfigureSaml2Options>();

                if (await schemeProvider.GetSchemeAsync(schemeName) == null)
                {
                    schemeProvider.AddScheme(new AuthenticationScheme(schemeName, schemeData.Scheme, typeof(Saml2Handler)));
                }
                else
                {
                    oAuthOptionsCache.TryRemove(schemeName);
                }
                //urn:ccidentity.auth0.com
                var options = new Saml2Options();
                options.SPOptions.EntityId   = new EntityId("https://localhost:44332/auth0");
                options.SPOptions.ModulePath = "/Saml2Auth0";
                options.SPOptions.MinIncomingSigningAlgorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";

                var idp = new IdentityProvider(new EntityId("urn:ccidentity.auth0.com"), options.SPOptions)
                {
                    MetadataLocation = "https://xxxxxxxx/samlp/metadata/7HmaqIPuC32Pc95e0clSqN3n3ogzkTkP",
                    LoadMetadata     = true,
                    AllowUnsolicitedAuthnResponse = true,
                    Binding = Saml2BindingType.HttpRedirect,
                    SingleSignOnServiceUrl = new Uri("https://xxxxxxx/samlp/7HmaqIPuC32Pc95e0clSqN3n3ogzkTkP"),
                };

                idp.SigningKeys.AddConfiguredKey(new X509Certificate2(Convert.FromBase64String("MIIDAzCCAeugAwIBAgIJLNhPpvvzUXRnMA0GCSqGSIb3DQEBCwUAMB8xHTAbBgNVBAMTFGNjaWRlbnRpdHkuYXV0aDAuY29tMB4XDTIwMDQwMTEwMTEzMVoXDTMzMTIwOTEwMTEzMVowHzEdMBsGA1UEAxMUY2NpZGVudGl0eS5hdXRoMC5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDXOaxVEhjYW+eT3YduAnRMGrJGcriVU1e3n3RXB6SPt4QsmXsOcdLItaqKthSKeRTkOtXvRANvve1YrEUeMwWzv9gsKoQrwM5fDKwG+chEJNxEZEtMmGfqasb++taLTduNPphSm1xs0RNHeeFXdJHt4QWVsCMJfH2RRUlRHaqj4niew/uzJOZNiWLnXp+03tiy5uwOyxyOhpMOX9QZqpSwHHzZ8OoLIIxynuSiWipZoeCoxrZKM3kHW9YlwLVZvcqAZhWTbut6sC+Y+1O1Sfh1tr6XxWzcP5GaMMV2xQPgPYYKjYMiMeFSe4E5P3R4QxmEoeOpAhWzHQbiyzMYLIO1AgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFFldi8Vcq5IwPROX5ssxqm+uuQaZMA4GA1UdDwEB/wQEAwIChDANBgkqhkiG9w0BAQsFAAOCAQEA1DWRiUaTCHqPUQRzOOnuiSib2dga2Qd1v39dqaaHrLe345c0eo1yn0cE50xtSTlx++WeIQ3RbXCMm70Za3+AfQhTOisqiHS0Nb+ZrxkHFzl0JNgY4AHQFbYsM3QwZQLBjfhL3KyYoTiQRifn/L9N1F/ZJN5PatoybwwJAbo4V0Y1g9pMSWXhbUKJCBP3Eq/8LPx2erAs3RkheYtz+beviOiXNeNYvUNxmPNy+vpp/zvFG5q20vtK7a3EBbOh1pputoctmAfnGoyjZ06JDAa006iJiGwXlwNonBFClLwbds4H3fc9hv4RsCWlVVdcO+l5FL17nhMRYZUn74lGHOCMZg==")));

                options.IdentityProviders.Add(idp);

                oAuthPostConfigureOptions.PostConfigure(schemeName, options);
                oAuthOptionsCache.TryAdd(schemeName, options);
            }
            else if (schemeData.Scheme == "Saml2")
            {
                IOptionsMonitorCache <Saml2Options> oAuthOptionsCache         = serviceProvider.GetRequiredService <IOptionsMonitorCache <Saml2Options> >();
                PostConfigureSaml2Options           oAuthPostConfigureOptions = serviceProvider.GetRequiredService <PostConfigureSaml2Options>();

                if (await schemeProvider.GetSchemeAsync(schemeName) == null)
                {
                    schemeProvider.AddScheme(new AuthenticationScheme(schemeName, schemeData.Scheme, typeof(Saml2Handler)));
                }
                else
                {
                    oAuthOptionsCache.TryRemove(schemeName);
                }

                var options = new Saml2Options();
                options.SPOptions.EntityId = new EntityId("https://localhost:44332/Saml2");
                options.SPOptions.MinIncomingSigningAlgorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";

                var idp = new IdentityProvider(new EntityId("https://xxxxxxxxxxxx/adfs/services/trust"), options.SPOptions)
                {
                    //MetadataLocation = "https://xxxxxxxxxxxx/FederationMetadata/2007-06/FederationMetadata.xml",
                    //LoadMetadata = true,
                    AllowUnsolicitedAuthnResponse = true,
                    Binding = Saml2BindingType.HttpRedirect,
                    SingleSignOnServiceUrl = new Uri("https://xxxxxxxxx/adfs/ls/"),
                };

                idp.SigningKeys.AddConfiguredKey(new X509Certificate2(Convert.FromBase64String("MIIC5jCCAc6gAwIBAgIQOMQMbu2YTpFIO7bLoDczgjANBgkqhkiG9w0BAQsFADAvMS0wKwYDVQQDEyRBREZTIFNpZ25pbmcgLSBEZXYtMTAxLkJhbmtPZlpvbmUubGswHhcNMjAwMzMwMTQyOTQ5WhcNMjEwMzMwMTQyOTQ5WjAvMS0wKwYDVQQDEyRBREZTIFNpZ25pbmcgLSBEZXYtMTAxLkJhbmtPZlpvbmUubGswggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC0sv1rrY0QcVy8kCYz48dTE0qWlwg7J67kNDuO4um37DKnmSK43QTKMkN4Oe / q6 + a8YV2XW7aHqVzirdyeCWDqWf0fuef0jBhysylwdZI8P8PHAhX632jkQ9dXKqKC9kVEsV + LMzMB98xv3ue + rAjQMctrvdapTgvRTOyu5SEHV7zKN / AXDgqM1AT9ae4prRhg7F37Y6h4DVjCdOZgV7LpmgkkFxFnmk0G5il9yfFnLs2Xw3dQxh8HPj9XCgeNT3GGnui + d69BnESsWDjUBUuBGB / +6WQixC4SnKzbssVTy3W4h3aSSsGljAAJfh5YUafzqCjG7Z6xE16LNBieKjbVAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAH / a2bttVBkWzk4Q7K8qjgC / GQboK1NJewEPdi + 8GKG5RD + hWWz /qmXKT0u6ZklzmNrsxj + jPxIOzlv7Aaa5CbGUHHRoG7mgWnvV7y0Qys3OfRUpIzOK0HzDhe / LlyHyX3TpKDH / b1YQJiE6yHgwEdkO4ZBQsOHDNm9pvWH2YJQqMFbWPA4ZeUASeUO0h + BdR4Fog / MYu86lensZwZUKbq / 1 + M5xao3LZfQh5oyEBpH0roRJOazjMSHV + U4sLdvkvXx6in4BLwt1HiMAm0oA6c + vSW5GANAJBXPupfP6Njt0lpGGC3bLgWOlU65NTPwIZhvAjs / gV / pBa + jVMVxDP0g = ")));

                options.IdentityProviders.Add(idp);

                oAuthPostConfigureOptions.PostConfigure(schemeName, options);
                oAuthOptionsCache.TryAdd(schemeName, options);
            }
            else
            {
                IOptionsMonitorCache <FacebookOptions> oAuthOptionsCache = serviceProvider.GetRequiredService <IOptionsMonitorCache <FacebookOptions> >();
                OAuthPostConfigureOptions <FacebookOptions, FacebookHandler> oAuthPostConfigureOptions = serviceProvider.GetRequiredService <OAuthPostConfigureOptions <FacebookOptions, FacebookHandler> >();

                if (await schemeProvider.GetSchemeAsync(schemeName) == null)
                {
                    schemeProvider.AddScheme(new AuthenticationScheme(schemeName, schemeData.Scheme, typeof(FacebookHandler)));
                }
                else
                {
                    oAuthOptionsCache.TryRemove(schemeName);
                }
                var options = new FacebookOptions
                {
                    AppId     = "xxxxxxxxxxxx",
                    AppSecret = "xxxxxxxxxxxxxxxxx"
                };

                oAuthOptionsCache.TryAdd(schemeName, options);
                oAuthPostConfigureOptions.PostConfigure(schemeName, options);
                oAuthOptionsCache.TryAdd(schemeName, options);
            }

            return(Redirect("/"));
        }
Ejemplo n.º 17
0
 public RequestIdCookieBuilder(Saml2Options options)
 {
     _options = options;
 }
 public WsSecuritySaml2SecurityTokenHandler(ExtendedSaml2Serializer serializer, Saml2Options options) : base(serializer, options)
 {
 }
Ejemplo n.º 19
0
        private static void ConfigureSamlIdp(Configuration.IdentityProvider identityProvider, Saml2Options options)
        {
            Log.Information($"Adding EntityId: {identityProvider.EntityId}");
            var idp = new IdentityProvider(new EntityId(identityProvider.EntityId), options.SPOptions)
            {
                Binding = Saml2BindingType.HttpRedirect,
                SingleSignOnServiceUrl = new Uri(identityProvider.SignOnUrl),
            };

            if (identityProvider.LoadMetadata)
            {
                idp.MetadataLocation = identityProvider.MetadataLocation;
                idp.LoadMetadata     = true;
            }
            else
            {
                Log.Information($"Adding certificate. Name: {identityProvider.CertificateName}");
                idp.SigningKeys.AddConfiguredKey(new X509Certificate2(identityProvider.CertificateName));
            }

            options.IdentityProviders.Add(idp);
        }
Ejemplo n.º 20
0
        public static void SetSPOptions(Saml2Options options)
        {
            var paramSPOptions = Parameters.Authentication.SamlParameters.SPOptions;

            options.SPOptions.AuthenticateRequestSigningBehavior
                = paramSPOptions.AuthenticateRequestSigningBehavior
                  .ToEnum(SigningBehavior.IfIdpWantAuthnRequestsSigned);
            options.SPOptions.ReturnUrl
                = paramSPOptions.ReturnUrl.IsNullOrEmpty() ? null : new Uri(paramSPOptions.ReturnUrl);
            options.SPOptions.EntityId
                = paramSPOptions.EntityId.IsNullOrEmpty() ? null : new EntityId(paramSPOptions.EntityId);
            options.SPOptions.MinIncomingSigningAlgorithm
                = paramSPOptions.MinIncomingSigningAlgorithm
                  ?? options.SPOptions.MinIncomingSigningAlgorithm;
            options.SPOptions.OutboundSigningAlgorithm
                = paramSPOptions.OutboundSigningAlgorithm
                  ?? options.SPOptions.OutboundSigningAlgorithm;
            options.SPOptions.PublicOrigin
                = paramSPOptions.PublicOrigin.IsNullOrEmpty()? null: new Uri(paramSPOptions.PublicOrigin);
            if (paramSPOptions.IgnoreMissingInResponseTo == true)
            {
                options.SPOptions.Compatibility.IgnoreMissingInResponseTo = true;
            }
            if (paramSPOptions.ServiceCertificates != null)
            {
                foreach (var cert in paramSPOptions.ServiceCertificates)
                {
                    var x509Store = new X509Store(
                        cert.StoreName.ToEnum(StoreName.My),
                        cert.StoreLocation.ToEnum(StoreLocation.CurrentUser));
                    x509Store.Open(OpenFlags.OpenExistingOnly);
                    try
                    {
                        var cer = x509Store.Certificates.Find(
                            cert.X509FindType.ToEnum(X509FindType.FindByThumbprint),
                            cert.FindValue,
                            false);
                        var serviceCert = new Sustainsys.Saml2.ServiceCertificate()
                        {
                            Certificate = cer[0],
                            Status      = cert.Status.ToEnum(CertificateStatus.Current),
                            Use         = cert.Use.ToEnum(CertificateUse.Both)
                        };
                        options.SPOptions.ServiceCertificates.Add(serviceCert);
                    }
                    finally
                    {
                        x509Store.Close();
                    }
                }
            }
            var paramIdps = Parameters.Authentication.SamlParameters.IdentityProviders;

            if (paramIdps != null)
            {
                foreach (var paramIdp in paramIdps)
                {
                    var idp = new Sustainsys.Saml2.IdentityProvider(
                        new EntityId(paramIdp.EntityId),
                        options.SPOptions)
                    {
                        SingleSignOnServiceUrl        = paramIdp.SignOnUrl.IsNullOrEmpty() ? null : new Uri(paramIdp.SignOnUrl),
                        SingleLogoutServiceUrl        = paramIdp.LogoutUrl.IsNullOrEmpty() ? null : new Uri(paramIdp.LogoutUrl),
                        AllowUnsolicitedAuthnResponse = paramIdp.AllowUnsolicitedAuthnResponse,
                        Binding = paramIdp.Binding.ToEnum(Saml2BindingType.HttpRedirect),
                        WantAuthnRequestsSigned       = paramIdp.WantAuthnRequestsSigned,
                        DisableOutboundLogoutRequests = paramIdp.DisableOutboundLogoutRequests
                    };
                    if (paramIdp.LoadMetadata)
                    {
                        idp.MetadataLocation = paramIdp.MetadataLocation.IsNullOrEmpty()
                            ? idp.MetadataLocation
                            : paramIdp.MetadataLocation;
                        idp.LoadMetadata = paramIdp.LoadMetadata;
                    }
                    if (paramIdp.SigningCertificate != null)
                    {
                        var store = new X509Store(
                            paramIdp.SigningCertificate.StoreName.ToEnum(StoreName.My),
                            paramIdp.SigningCertificate.StoreLocation.ToEnum(StoreLocation.CurrentUser));
                        store.Open(OpenFlags.OpenExistingOnly);
                        try
                        {
                            var certs = store.Certificates.Find(
                                paramIdp.SigningCertificate.X509FindType.ToEnum(X509FindType.FindByThumbprint),
                                paramIdp.SigningCertificate.FindValue, false);
                            idp.SigningKeys.AddConfiguredKey(certs[0]);
                        }
                        finally
                        {
                            store.Close();
                        }
                    }
                    options.IdentityProviders.Add(idp);
                }
            }
        }