コード例 #1
0
ファイル: ConditionGroup.cs プロジェクト: RyanHauert/fubumvc
        public void RestrictToAudience(string uri)
        {
            var restriction = new AudienceRestriction();
            restriction.Add(uri);

            Add(restriction);
        }
コード例 #2
0
        /// <summary>
        /// Returns an instance of the class with meaningful default values set.
        /// </summary>
        /// <returns></returns>
        public static Saml20AuthnRequest GetDefault()
        {
            SAML20FederationConfig config = SAML20FederationConfig.GetConfig();

            if (config.ServiceProvider == null || string.IsNullOrEmpty(config.ServiceProvider.ID))
            {
                throw new Saml20FormatException(Resources.ServiceProviderNotSet);
            }

            Saml20AuthnRequest result = new Saml20AuthnRequest();

            result.Issuer = config.ServiceProvider.ID;

            List <ConditionAbstract> audienceRestrictions = new List <ConditionAbstract>(1);

            AudienceRestriction audienceRestriction = new AudienceRestriction();

            audienceRestriction.Audience = new List <string>(1);
            audienceRestriction.Audience.Add(config.ServiceProvider.ID);
            audienceRestrictions.Add(audienceRestriction);

            result.SetConditions(audienceRestrictions);

            return(result);
        }
        private static AudienceRestriction GetAudienceRestriction(Saml2AuthenticationOptions options)
        {
            if (!options.TokenValidationParameters.ValidateAudience)
            {
                return(new AudienceRestriction(AudienceUriMode.Never));
            }

            var audienceRestriction = new AudienceRestriction(AudienceUriMode.Always);

            if (!string.IsNullOrWhiteSpace(options.Wtrealm))
            {
                audienceRestriction.AllowedAudienceUris.Add(new Uri(options.Wtrealm));
            }

            if (!string.IsNullOrWhiteSpace(options.TokenValidationParameters.ValidAudience))
            {
                audienceRestriction.AllowedAudienceUris.Add(new Uri(options.TokenValidationParameters.ValidAudience));
            }

            if (options.TokenValidationParameters.ValidAudiences != null)
            {
                foreach (var audience in options.TokenValidationParameters.ValidAudiences)
                {
                    audienceRestriction.AllowedAudienceUris.Add(new Uri(audience));
                }
            }

            return(audienceRestriction);
        }
コード例 #4
0
        protected override void BuildInternal(AuthnRequest request, AuthnRequestConfiguration configuration)
        {
            var audienceRestriction = new AudienceRestriction();

            configuration.AudienceRestriction.Aggregate(audienceRestriction, (a, next) => { a.Audience.Add(next); return(a); });
            request.Conditions.Items.Add(audienceRestriction);
        }
コード例 #5
0
        // Create a SAML response with the user's local identity.
        private SAMLResponse CreateSAMLResponse()
        {
            Trace.Write("IdP", "Creating SAML response");

            SAMLResponse samlResponse = new SAMLResponse();

            samlResponse.Destination = Configuration.AssertionConsumerServiceURL;
            Issuer issuer = new Issuer(Configuration.Issuer);

            samlResponse.Issuer = issuer;
            samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null);

            SAMLAssertion samlAssertion = new SAMLAssertion();

            samlAssertion.Issuer = issuer;

            // For simplicity, a configured Salesforce user name is used.
            // NB. You must update the web.config to specify a valid Salesforce user name.
            // In a real world application you would perform some sort of local to Salesforce identity mapping.
            Subject                 subject                 = new Subject(new NameID(Configuration.SalesforceLoginID, null, null, SAMLIdentifiers.NameIdentifierFormats.Unspecified, null));
            SubjectConfirmation     subjectConfirmation     = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer);
            SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();

            subjectConfirmationData.Recipient           = Configuration.AssertionConsumerServiceURL;
            subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
            subject.SubjectConfirmations.Add(subjectConfirmation);
            samlAssertion.Subject = subject;

            Conditions          conditions          = new Conditions(new TimeSpan(1, 0, 0));
            AudienceRestriction audienceRestriction = new AudienceRestriction();

            audienceRestriction.Audiences.Add(new Audience(audienceURI));
            conditions.ConditionsList.Add(audienceRestriction);
            samlAssertion.Conditions = conditions;

            subjectConfirmationData.NotOnOrAfter = conditions.NotOnOrAfter;

            AuthnStatement authnStatement = new AuthnStatement();

            authnStatement.AuthnContext = new AuthnContext();
            authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Unspecified);
            samlAssertion.Statements.Add(authnStatement);

            AttributeStatement attributeStatement = new AttributeStatement();

            attributeStatement.Attributes.Add(new SAMLAttribute(AttributeNames.SSOStartPage, SAMLIdentifiers.AttributeNameFormats.Unspecified, null, CreateAbsoluteURL("~/Login.aspx")));
            attributeStatement.Attributes.Add(new SAMLAttribute(AttributeNames.LogoutURL, SAMLIdentifiers.AttributeNameFormats.Unspecified, null, CreateAbsoluteURL("~/Logout.aspx")));
            samlAssertion.Statements.Add(attributeStatement);

            samlResponse.Assertions.Add(samlAssertion);

            Trace.Write("IdP", "Created SAML response");

            return(samlResponse);
        }
コード例 #6
0
        public Saml2AuthnRequest CreateAuthnRequest(string providerName, string authnRequestId, string assertionConsumerServiceUrl)
        {
            var identityProviderConfiguration = _configurationProvider.GetIdentityProviderConfiguration(providerName);
            var request = new Saml2AuthnRequest
            {
                ID              = authnRequestId,
                Issuer          = ServiceProviderConfiguration.EntityId,
                ForceAuthn      = identityProviderConfiguration.ForceAuth,
                IsPassive       = identityProviderConfiguration.IsPassive,
                Destination     = identityProviderConfiguration.SingleSignOnService,
                IssuerFormat    = identityProviderConfiguration.IssuerFormat,
                IssueInstant    = DateTime.UtcNow,
                ProtocolBinding = identityProviderConfiguration.ProtocolBinding
            };

            request.Request.AssertionConsumerServiceURL = assertionConsumerServiceUrl;

            var audienceRestrictions = new List <ConditionAbstract>(1);
            var audienceRestriction  =
                new AudienceRestriction {
                Audience = new List <string>(1)
                {
                    ServiceProviderConfiguration.EntityId
                }
            };

            audienceRestrictions.Add(audienceRestriction);
            request.Request.Conditions = new Conditions {
                Items = audienceRestrictions
            };

            if (identityProviderConfiguration.AllowCreate.HasValue &&
                identityProviderConfiguration.NameIdPolicyFormat.IsNotNullOrEmpty())
            {
                request.Request.NameIDPolicy = new NameIDPolicy
                {
                    AllowCreate = identityProviderConfiguration.AllowCreate,
                    Format      = identityProviderConfiguration.NameIdPolicyFormat
                };
            }

            if (identityProviderConfiguration.AuthnContextComparisonType.IsNotNullOrEmpty())
            {
                request.Request.RequestedAuthnContext = new RequestedAuthnContext
                {
                    Comparison          = (AuthnContextComparisonType)Enum.Parse(typeof(AuthnContextComparisonType), identityProviderConfiguration.AuthnContextComparisonType),
                    ComparisonSpecified = true,
                    Items = identityProviderConfiguration.AuthnContextComparisonItems
                };
            }

            return(request);
        }
コード例 #7
0
        // Create a SAML response with the user's local identity, if any, or indicating an error.
        private SAMLResponse CreateSAMLResponse(AuthnRequest authnRequest)
        {
            Trace.Write("IdP", "Creating SAML response");

            SAMLResponse samlResponse = new SAMLResponse();

            samlResponse.InResponseTo = authnRequest.ID;
            samlResponse.Destination  = authnRequest.AssertionConsumerServiceURL;
            Issuer issuer = new Issuer(CreateAbsoluteURL("~/"));

            samlResponse.Issuer = issuer;

            if (User.Identity.IsAuthenticated)
            {
                samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null);

                SAMLAssertion samlAssertion = new SAMLAssertion();
                samlAssertion.Issuer = issuer;

                samlAssertion.Conditions = new Conditions(new TimeSpan(0, 10, 0));
                AudienceRestriction audienceRestriction = new AudienceRestriction();
                audienceRestriction.Audiences.Add(new Audience(authnRequest.AssertionConsumerServiceURL));
                samlAssertion.Conditions.ConditionsList.Add(audienceRestriction);

                Subject                 subject                 = new Subject(new NameID(User.Identity.Name));
                SubjectConfirmation     subjectConfirmation     = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer);
                SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();
                subjectConfirmationData.InResponseTo = authnRequest.ID;
                subjectConfirmationData.Recipient    = authnRequest.AssertionConsumerServiceURL;
                subjectConfirmationData.NotBefore    = samlAssertion.Conditions.NotBefore;
                subjectConfirmationData.NotOnOrAfter = samlAssertion.Conditions.NotOnOrAfter;

                subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
                subject.SubjectConfirmations.Add(subjectConfirmation);
                samlAssertion.Subject = subject;

                AuthnStatement authnStatement = new AuthnStatement();
                authnStatement.AuthnContext = new AuthnContext();
                authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Password);
                samlAssertion.Statements.Add(authnStatement);

                samlResponse.Assertions.Add(samlAssertion);
            }
            else
            {
                samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Responder, SAMLIdentifiers.SecondaryStatusCodes.AuthnFailed, "The user is not authenticated at the identity provider");
            }

            Trace.Write("IdP", "Created SAML response");

            return(samlResponse);
        }
コード例 #8
0
        private static AudienceRestriction GetAudienceRestriction(bool audienceRestricted, IEnumerable <string> allowedAudienceUris)
        {
            var audienceRestriction = new AudienceRestriction(audienceRestricted ? System.IdentityModel.Selectors.AudienceUriMode.Always : System.IdentityModel.Selectors.AudienceUriMode.Never);

            if (audienceRestricted)
            {
                foreach (var audienceUri in allowedAudienceUris)
                {
                    audienceRestriction.AllowedAudienceUris.Add(new Uri(audienceUri));
                }
            }
            return(audienceRestriction);
        }
        /// <summary>
        /// Check if an audience restriction from configuration should be
        /// applied or if we should revert to the default behaviour of
        /// restricting the audience to the entity id.
        /// </summary>
        /// <param name="spOptions">Sp Options with configuration</param>
        /// <returns>Configured or created audience restriction.</returns>
        private static AudienceRestriction GetAudienceRestriction(SPOptions spOptions)
        {
            var audienceRestriction = spOptions.SystemIdentityModelIdentityConfiguration.AudienceRestriction;

            if (audienceRestriction.AudienceMode != AudienceUriMode.Never &&
                !audienceRestriction.AllowedAudienceUris.Any())
            {
                // Create a new instance instead of modifying the one from the
                // configuration.
                audienceRestriction = new AudienceRestriction(audienceRestriction.AudienceMode);
                audienceRestriction.AllowedAudienceUris.Add(new Uri(spOptions.EntityId.Id));
            }

            return(audienceRestriction);
        }
コード例 #10
0
        static MorePublicSaml2SecurityTokenHandler()
        {
            var audienceRestriction = new AudienceRestriction(AudienceUriMode.Always);

            audienceRestriction.AllowedAudienceUris.Add(
                new Uri(KentorAuthServicesSection.Current.EntityId));

            defaultInstance = new MorePublicSaml2SecurityTokenHandler()
            {
                Configuration = new SecurityTokenHandlerConfiguration()
                {
                    IssuerNameRegistry  = new ReturnRequestedIssuerNameRegistry(),
                    AudienceRestriction = audienceRestriction
                }
            };
        }
コード例 #11
0
            public void ThrowsExceptionWhenAudienceRestrictionAudienceFormatIsInvalid()
            {
                // Arrange
                var assertion = AssertionUtil.GetBasicAssertion();
                var validator = new Saml20AssertionValidator(AssertionUtil.GetAudiences(), false);

                var audienceRestriction = new AudienceRestriction
                {
                    Audience = new List <string>(new[] { "malformed uri" })
                };

                assertion.Conditions.Items = new List <ConditionAbstract>(new ConditionAbstract[] { audienceRestriction });

                // Act
                validator.ValidateAssertion(assertion);
            }
コード例 #12
0
            public void ThrowsExceptionWhenAudienceRestrictionAudienceFormatIsInvalid()
            {
                // Arrange
                var assertion = AssertionUtil.GetBasicAssertion();
                var validator = new Saml20AssertionValidator(AssertionUtil.GetAudiences(), false);

                var audienceRestriction = new AudienceRestriction
                {
                    Audience = new List <string>(new[] { "malformed uri" })
                };

                assertion.Conditions.Items = new List <ConditionAbstract>(new ConditionAbstract[] { audienceRestriction });

                // Act
                Assert.Throws <Saml20FormatException>(() => validator.ValidateAssertion(assertion), "Audience element has value which is not a wellformed absolute uri");
            }
コード例 #13
0
        /// <summary>
        /// Returns an instance of the class with meaningful default values set.
        /// </summary>
        /// <returns></returns>
        public static Saml20AuthnRequest GetDefault(string issuer)
        {
            Saml20AuthnRequest result = new Saml20AuthnRequest();

            result.Issuer = issuer;

            List <ConditionAbstract> audienceRestrictions = new List <ConditionAbstract>(1);

            AudienceRestriction audienceRestriction = new AudienceRestriction();

            audienceRestriction.Audience = new List <string>(1);
            audienceRestriction.Audience.Add(issuer);
            audienceRestrictions.Add(audienceRestriction);

            result.SetConditions(audienceRestrictions);

            return(result);
        }
コード例 #14
0
        public Saml2PSecurityTokenHandler(SAML2AuthenticationOptions spOptions)
        {
            if (spOptions == null)
            {
                throw new ArgumentNullException(spOptions.GetType().Name);
            }

            var audienceRestriction = new AudienceRestriction(AudienceUriMode.Always);

            audienceRestriction.AllowedAudienceUris.Add(
                new Uri(spOptions.EntityId.Id, UriKind.RelativeOrAbsolute));

            Configuration = new SecurityTokenHandlerConfiguration
            {
                IssuerNameRegistry  = new ReturnRequestedIssuerNameRegistry(),
                AudienceRestriction = audienceRestriction,
                // SaveBootstrapContext = spOptions.SystemIdentityModelIdentityConfiguration.SaveBootstrapContext
            };
        }
コード例 #15
0
            public void ValidatesAudienceRestrictionWithMultipleAudienceRestrictions()
            {
                // Arrange
                var assertion = AssertionUtil.GetBasicAssertion();
                var validator = new Saml20AssertionValidator(AssertionUtil.GetAudiences(), false);

                var audienceConditions  = new List <ConditionAbstract>(assertion.Conditions.Items);
                var audienceRestriction = new AudienceRestriction
                {
                    Audience = new List <string>(new[] { "urn:borger.dk:id" })
                };

                audienceConditions.Add(audienceRestriction);

                assertion.Conditions.Items = audienceConditions;

                // Act
                validator.ValidateAssertion(assertion);
            }
コード例 #16
0
            public void ThrowsExceptionWhenAudienceRestrictionAnyAudienceRestrictionIsNotMet()
            {
                // Arrange
                var assertion = AssertionUtil.GetBasicAssertion();
                var validator = new Saml20AssertionValidator(AssertionUtil.GetAudiences(), false);

                var audienceConditions  = new List <ConditionAbstract>(assertion.Conditions.Items);
                var audienceRestriction = new AudienceRestriction
                {
                    Audience = new List <string>(new[] { "http://well/formed.uri" })
                };

                audienceConditions.Add(audienceRestriction);

                assertion.Conditions.Items = audienceConditions;

                // Act
                validator.ValidateAssertion(assertion);
            }
コード例 #17
0
            public void ThrowsExceptionWhenAudienceRestrictionAnyAudienceRestrictionIsNotMet()
            {
                // Arrange
                var assertion = AssertionUtil.GetBasicAssertion();
                var validator = new Saml20AssertionValidator(AssertionUtil.GetAudiences(), false);

                var audienceConditions  = new List <ConditionAbstract>(assertion.Conditions.Items);
                var audienceRestriction = new AudienceRestriction
                {
                    Audience = new List <string>(new[] { "http://well/formed.uri" })
                };

                audienceConditions.Add(audienceRestriction);

                assertion.Conditions.Items = audienceConditions;

                // Act
                Assert.Throws <Saml20FormatException>(() => validator.ValidateAssertion(assertion), "The service is not configured to meet the given audience restrictions");
            }
コード例 #18
0
        public Saml2PSecurityTokenHandler(ISPOptions spOptions)
        {
            if (spOptions == null)
            {
                throw new ArgumentNullException(nameof(spOptions));
            }

            var audienceRestriction = new AudienceRestriction(AudienceUriMode.Always);

            audienceRestriction.AllowedAudienceUris.Add(
                new Uri(spOptions.EntityId.Id));

            Configuration = new SecurityTokenHandlerConfiguration
            {
                IssuerNameRegistry   = new ReturnRequestedIssuerNameRegistry(),
                AudienceRestriction  = audienceRestriction,
                SaveBootstrapContext = spOptions.SystemIdentityModelIdentityConfiguration.SaveBootstrapContext
            };
        }
        /// <summary>
        /// Validates the saml20Assertion's list of conditions.
        /// </summary>
        private void ValidateConditions(Assertion saml20Assertion)
        {
            bool audienceRestrictionPresent = false;

            foreach (ConditionAbstract condition in saml20Assertion.Conditions.Items)
            {
                if (condition is AudienceRestriction)
                {
                    audienceRestrictionPresent = true;
                    AudienceRestriction audienceRestriction = (AudienceRestriction)condition;
                    if (audienceRestriction.Audience == null || audienceRestriction.Audience.Count == 0)
                    {
                        throw new DKSaml20FormatException(
                                  "The DK-SAML 2.0 profile requires that an \"AudienceRestriction\" element contains the service provider's unique identifier in an \"Audience\" element.");
                    }
                }
            }

            if (!audienceRestrictionPresent)
            {
                throw new DKSaml20FormatException("The DK-SAML 2.0 profile requires that an \"AudienceRestriction\" element is present on the saml20Assertion.");
            }
        }
コード例 #20
0
        private ReadOnlyCollection <ClaimsIdentity> ValidateAssertion(string assertionXml)
        {
            ReadOnlyCollection <ClaimsIdentity> claimsIdentities = null;
            Saml2SecurityToken securityToken;
            StringReader       reader = new StringReader(assertionXml);

            using (XmlReader xmlReader = XmlReader.Create(reader))
            {
                if (!xmlReader.ReadToFollowing("saml2:Assertion"))
                {
                    throw new SecurityTokenValidationException("SAML2 Assertion not found.");
                }

                FixedSaml2SecurityTokenHandler       tokenHandler       = new FixedSaml2SecurityTokenHandler(Recipient);
                SecurityTokenHandler[]               tokenHandlers      = new SecurityTokenHandlers[] { tokenHandler };
                SecurityTokenHandlerCollection       handlerCollection  = new SecurityTokenHandlerCollection(tokenHandlers);
                ConfigurationBasedIssuerNameRegistry issuerNameRegistry = new ConfigurationBasedIssuerNameRegistry();

                foreach (TrustedIssuer issuer in TrustedIssuers)
                {
                    issuerNameRegistry.AddTrustedIssuer(issuer.CertificateThumbprint, issuer.IssuerName);
                }
                handlerCollection.Configuration.IssuerNameRegistry = issuerNameRegistry;

                AudienceRestriction restriction = new AudienceRestriction(AudienceUriMode.Always);

                foreach (Uri allowedAudience in AllowedAudiences)
                {
                    restriction.AllowedAudiencesUris.Add(allowedAudience);
                }
                handlerCollection.Configuration.AudienceRestriction = restriction;
                securityToken    = (Saml2SecurityToken)handlerCollection.ReadToken(xmlReader.ReadSubtree());
                claimsIdentities = handlerCollection.ValidateToken(securityToken);
            }
            return(claimsIdentities);
        }
コード例 #21
0
ファイル: SSOService.aspx.cs プロジェクト: HRINY/HRI-Umbraco
        // Create a SAML response with the user's local identity.
        private SAMLResponse CreateSAMLResponse()
        {
            Trace.Write("IdP", "Creating SAML response");

            SAMLResponse samlResponse = new SAMLResponse();
            samlResponse.Destination = Configuration.AssertionConsumerServiceURL;
            Issuer issuer = new Issuer(Configuration.Issuer);
            samlResponse.Issuer = issuer;
            samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null);

            SAMLAssertion samlAssertion = new SAMLAssertion();
            samlAssertion.Issuer = issuer;

            // For simplicity, a configured Salesforce user name is used.
            // NB. You must update the web.config to specify a valid Salesforce user name.
            // In a real world application you would perform some sort of local to Salesforce identity mapping.
            Subject subject = new Subject(new NameID(Configuration.SalesforceLoginID, null, null, SAMLIdentifiers.NameIdentifierFormats.Unspecified, null));
            SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer);
            SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();
            subjectConfirmationData.Recipient = Configuration.AssertionConsumerServiceURL;
            subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
            subject.SubjectConfirmations.Add(subjectConfirmation);
            samlAssertion.Subject = subject;

            Conditions conditions = new Conditions(new TimeSpan(1, 0, 0));
            AudienceRestriction audienceRestriction = new AudienceRestriction();
            audienceRestriction.Audiences.Add(new Audience(audienceURI));
            conditions.ConditionsList.Add(audienceRestriction);
            samlAssertion.Conditions = conditions;

            subjectConfirmationData.NotOnOrAfter = conditions.NotOnOrAfter;

            AuthnStatement authnStatement = new AuthnStatement();
            authnStatement.AuthnContext = new AuthnContext();
            authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Unspecified);
            samlAssertion.Statements.Add(authnStatement);

            AttributeStatement attributeStatement = new AttributeStatement();
            attributeStatement.Attributes.Add(new SAMLAttribute(AttributeNames.SSOStartPage, SAMLIdentifiers.AttributeNameFormats.Unspecified, null, CreateAbsoluteURL("~/Login.aspx")));
            attributeStatement.Attributes.Add(new SAMLAttribute(AttributeNames.LogoutURL, SAMLIdentifiers.AttributeNameFormats.Unspecified, null, CreateAbsoluteURL("~/Logout.aspx")));
            samlAssertion.Statements.Add(attributeStatement);

            samlResponse.Assertions.Add(samlAssertion);

            Trace.Write("IdP", "Created SAML response");

            return samlResponse;
        }
コード例 #22
0
ファイル: SamlResponse.cs プロジェクト: RyanHauert/fubumvc
        public void AddAudienceRestriction(string audience)
        {
            if (Conditions == null)
            {
                Conditions = new ConditionGroup();
            }

            var restriction = Conditions.Conditions.OfType<AudienceRestriction>().FirstOrDefault();
            if (restriction == null)
            {
                restriction = new AudienceRestriction();
                Conditions.Add(restriction);
            }

            restriction.Add(audience);
        }
コード例 #23
0
        private void BuildSamlRequest()
        {
            ClientScript.RegisterStartupScript(typeof(Page), "OpaqueDivider",
                                               @"
                <script language=""javascript"">
                <!--
                    var dividerID = '" + this.SamlAgentDiv.ClientID + @"';
                    var divider = document.getElementById(dividerID);

                    divider.style.visibility = 'visible';
                //-->
	            </script>"    );

            //Creating SAML response
            X509Certificate2 vendorCertificate  = GetVendorCertificate();
            X509Certificate2 selerixCertificate = GetSelerixCertificate();

            //string assertionConsumerServiceURL = "SamlResponse.aspx";
            string assertionConsumerServiceURL = "http://localhost:49000/login.aspx?Path=SAML_TEST";

            string audienceName = "whatever audience";

            SAMLResponse samlResponse = new SAMLResponse();

            samlResponse.Destination = assertionConsumerServiceURL;

            Issuer issuer = new Issuer("Vendor");

            samlResponse.Issuer = issuer;
            samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null);

            SAMLAssertion samlAssertion = new SAMLAssertion();

            samlAssertion.Issuer = issuer;

            Subject subject = null;

            //subject = new Subject(new EncryptedID(new NameID(this._EmailText.Text), selerixCertificate, new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl)));
            subject = new Subject(new NameID(this._EmailText.Text));

            SubjectConfirmation     subjectConfirmation     = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer);
            SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();

            subjectConfirmationData.Recipient           = assertionConsumerServiceURL;
            subjectConfirmationData.NotOnOrAfter        = DateTime.UtcNow.AddHours(1);
            subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;

            subject.SubjectConfirmations.Add(subjectConfirmation);
            samlAssertion.Subject = subject;

            Conditions          conditions          = new Conditions(new TimeSpan(1, 0, 0));
            AudienceRestriction audienceRestriction = new AudienceRestriction();

            audienceRestriction.Audiences.Add(new Audience(audienceName));
            conditions.ConditionsList.Add(audienceRestriction);
            samlAssertion.Conditions = conditions;

            AuthnStatement authnStatement = new AuthnStatement();

            authnStatement.AuthnContext = new AuthnContext();
            authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Unspecified);

            samlAssertion.Statements.Add(authnStatement);

            AttributeStatement attributeStatement = new AttributeStatement();

            Transmittal transmittal = BuildTransmittal();

            if (transmittal != null && !string.IsNullOrEmpty(this._FirstName.Text) && !string.IsNullOrEmpty(this._LastName.Text))
            {
                attributeStatement.Attributes.Add(new SAMLAttribute("Transmittal", SAMLIdentifiers.AttributeNameFormats.Basic, null, SerializationHelper.SerializeToString(transmittal)));
            }

            samlAssertion.Statements.Add(attributeStatement);

//          EncryptedAssertion encryptedAssertion = new EncryptedAssertion(samlAssertion, selerixCertificate, new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl));
//          samlResponse.Assertions.Add(encryptedAssertion);
            samlResponse.Assertions.Add(samlAssertion);

            //Created SAML response

            //Sending SAML response

            // Serialize the SAML response for transmission.
            XmlElement samlResponseXml = samlResponse.ToXml();

            // Sign the SAML response.
            SAMLMessageSignature.Generate(samlResponseXml, vendorCertificate.PrivateKey, vendorCertificate);

            HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
            HttpContext.Current.Response.AddHeader("Pragma", "no-cache");

            IdentityProvider.SendSAMLResponseByHTTPPost(HttpContext.Current.Response, assertionConsumerServiceURL, samlResponseXml, "");// for test purposes
        }
コード例 #24
0
        /// <summary>
        /// Returns an instance of the class with meaningful default values set.
        /// </summary>
        /// <returns>The default <see cref="Saml20AuthnRequest"/>.</returns>
        public static Saml20AuthnRequest GetDefault(Saml2Configuration config)
        {
            var result = new Saml20AuthnRequest {
                Issuer = config.ServiceProvider.Id
            };

            if (config.ServiceProvider.Endpoints.DefaultSignOnEndpoint.Binding != BindingType.NotSet)
            {
                var baseUrl = new Uri(config.ServiceProvider.Server);
                result.AssertionConsumerServiceUrl = new Uri(baseUrl, config.ServiceProvider.Endpoints.DefaultSignOnEndpoint.LocalPath).ToString();
            }

            // Binding
            switch (config.ServiceProvider.Endpoints.DefaultSignOnEndpoint.Binding)
            {
            case BindingType.Artifact:
                result.Request.ProtocolBinding = Saml20Constants.ProtocolBindings.HttpArtifact;
                break;

            case BindingType.Post:
                result.Request.ProtocolBinding = Saml20Constants.ProtocolBindings.HttpPost;
                break;

            case BindingType.PostSimpleSign:
                result.Request.ProtocolBinding = Saml20Constants.ProtocolBindings.HttpPostSimpleSign;
                break;

            case BindingType.Redirect:
                result.Request.ProtocolBinding = Saml20Constants.ProtocolBindings.HttpRedirect;
                break;

            case BindingType.Soap:
                result.Request.ProtocolBinding = Saml20Constants.ProtocolBindings.HttpSoap;
                break;
            }

            // NameIDPolicy
            if (config.ServiceProvider.NameIdFormats.Count > 0)
            {
                result.NameIdPolicy = new NameIdPolicy
                {
                    AllowCreate = false,
                    Format      = config.ServiceProvider.NameIdFormats[0].Format
                };

                if (result.NameIdPolicy.Format != Saml20Constants.NameIdentifierFormats.Entity)
                {
                    result.NameIdPolicy.SPNameQualifier = config.ServiceProvider.Id;
                }
            }

            // RequestedAuthnContext
            if (config.ServiceProvider.AuthenticationContexts.Count > 0)
            {
                result.RequestedAuthnContext = new RequestedAuthnContext();
                switch (config.ServiceProvider.AuthenticationContexts.Comparison)
                {
                case AuthenticationContextComparison.Better:
                    result.RequestedAuthnContext.Comparison          = AuthnContextComparisonType.Better;
                    result.RequestedAuthnContext.ComparisonSpecified = true;
                    break;

                case AuthenticationContextComparison.Minimum:
                    result.RequestedAuthnContext.Comparison          = AuthnContextComparisonType.Minimum;
                    result.RequestedAuthnContext.ComparisonSpecified = true;
                    break;

                case AuthenticationContextComparison.Maximum:
                    result.RequestedAuthnContext.Comparison          = AuthnContextComparisonType.Maximum;
                    result.RequestedAuthnContext.ComparisonSpecified = true;
                    break;

                case AuthenticationContextComparison.Exact:
                    result.RequestedAuthnContext.Comparison          = AuthnContextComparisonType.Exact;
                    result.RequestedAuthnContext.ComparisonSpecified = true;
                    break;

                default:
                    result.RequestedAuthnContext.ComparisonSpecified = false;
                    break;
                }

                result.RequestedAuthnContext.Items            = new string[config.ServiceProvider.AuthenticationContexts.Count];
                result.RequestedAuthnContext.ItemsElementName = new Schema.Protocol.AuthnContextType[config.ServiceProvider.AuthenticationContexts.Count];

                var count = 0;
                foreach (var authenticationContext in config.ServiceProvider.AuthenticationContexts)
                {
                    result.RequestedAuthnContext.Items[count] = authenticationContext.Context;
                    switch (authenticationContext.ReferenceType)
                    {
                    case "AuthnContextDeclRef":
                        result.RequestedAuthnContext.ItemsElementName[count] = Schema.Protocol.AuthnContextType.AuthnContextDeclRef;
                        break;

                    default:
                        result.RequestedAuthnContext.ItemsElementName[count] = Schema.Protocol.AuthnContextType.AuthnContextClassRef;
                        break;
                    }

                    count++;
                }
            }

            // Restrictions
            var audienceRestrictions = new List <ConditionAbstract>(1);
            var audienceRestriction  = new AudienceRestriction {
                Audience = new List <string>(1)
                {
                    config.ServiceProvider.Id
                }
            };

            audienceRestrictions.Add(audienceRestriction);

            result.SetConditions(audienceRestrictions);

            return(result);
        }
コード例 #25
0
        /// <summary>
        /// Validates the Assertion's conditions
        /// Audience restrictions processing rules are:
        ///  - Within a single audience restriction condition in the assertion, the service must be configured
        ///    with an audience-list that contains at least one of the restrictions in the assertion ("OR" filter)
        ///  - When multiple audience restrictions are present within the same assertion, all individual audience
        ///    restriction conditions must be met ("AND" filter)
        /// </summary>
        private void ValidateConditions(Assertion assertion)
        {
            // Conditions are not required
            if (assertion.Conditions == null)
            {
                return;
            }

            bool oneTimeUseSeen        = false;
            bool proxyRestrictionsSeen = false;

            ValidateConditionsInterval(assertion.Conditions);

            foreach (ConditionAbstract cat in assertion.Conditions.Items)
            {
                if (cat is OneTimeUse)
                {
                    if (oneTimeUseSeen)
                    {
                        throw new Saml20FormatException("Assertion contained more than one condition of type OneTimeUse");
                    }
                    oneTimeUseSeen = true;
                    continue;
                }

                if (cat is ProxyRestriction)
                {
                    if (proxyRestrictionsSeen)
                    {
                        throw new Saml20FormatException("Assertion contained more than one condition of type ProxyRestriction");
                    }
                    proxyRestrictionsSeen = true;

                    ProxyRestriction proxyRestriction = (ProxyRestriction)cat;
                    if (!String.IsNullOrEmpty(proxyRestriction.Count))
                    {
                        uint res;
                        if (!UInt32.TryParse(proxyRestriction.Count, out res))
                        {
                            throw new Saml20FormatException("Count attribute of ProxyRestriction MUST BE a non-negative integer");
                        }
                    }

                    if (proxyRestriction.Audience != null)
                    {
                        foreach (string audience in proxyRestriction.Audience)
                        {
                            if (!Uri.IsWellFormedUriString(audience, UriKind.Absolute))
                            {
                                throw new Saml20FormatException("ProxyRestriction Audience MUST BE a wellformed uri");
                            }
                        }
                    }
                }

                // AudienceRestriction processing goes here (section 2.5.1.4 of [SAML2.0std])
                if (cat is AudienceRestriction)
                {
                    // No audience restrictions? No problems...
                    AudienceRestriction audienceRestriction = (AudienceRestriction)cat;
                    if (audienceRestriction.Audience == null || audienceRestriction.Audience.Count == 0)
                    {
                        continue;
                    }

                    // If there are no allowed audience uris configured for the service, the assertion is not
                    // valid for this service
                    if (_allowedAudienceUris == null || _allowedAudienceUris.Count < 1)
                    {
                        throw new Saml20FormatException("The service is not configured to meet any audience restrictions");
                    }

                    string match = null;
                    foreach (string audience in audienceRestriction.Audience)
                    {
                        //In QuirksMode this validation is omitted
                        if (!_quirksMode)
                        {
                            // The given audience value MUST BE a valid URI
                            if (!Uri.IsWellFormedUriString(audience, UriKind.Absolute))
                            {
                                throw new Saml20FormatException("Audience element has value which is not a wellformed absolute uri");
                            }
                        }

                        match =
                            _allowedAudienceUris.Find(
                                delegate(string allowedUri) { return(allowedUri.Equals(audience)); });
                        if (match != null)
                        {
                            break;
                        }
                    }

//                    if (Trace.ShouldTrace(TraceEventType.Verbose))
//                    {
//                        string intended = "Intended uris: " + Environment.NewLine + String.Join(Environment.NewLine, audienceRestriction.Audience.ToArray());
//                        string allowed = "Allowed uris: " + Environment.NewLine + String.Join(Environment.NewLine, _allowedAudienceUris.ToArray());
//                        Trace.TraceData(TraceEventType.Verbose, Trace.CreateTraceString(GetType(), "ValidateConditions"), intended, allowed);
//                    }

                    if (match == null)
                    {
                        throw new Saml20FormatException("The service is not configured to meet the given audience restrictions");
                    }
                }
            }
        }
コード例 #26
0
        private static Assertion CreateAssertion(SamlResponseFactoryArgs args)
        {
            var assertionId  = AssertionIdFactory();
            var issueInstant = IssueInstantFactory();
            var version      = VersionFactory();
            var notOnOrAfter = issueInstant.DateTime.Add(args.TimeToBeExpired);
            var authnInstant = issueInstant.DateTime;
            var sessionIndex = string.IsNullOrEmpty(args.SessionIndex.Value)
                ? SessionIndexFactory() : args.SessionIndex.Value;

            var assertion = new Assertion
            {
                Issuer       = new NameId(),
                Id           = assertionId,
                IssueInstant = issueInstant.DateTime,
                Version      = version,
            };

            assertion.Issuer.Value = args.Issuer.Value;
            assertion.Subject      = new Subject();
            var subjectConfirmation = new SubjectConfirmation
            {
                Method = SubjectConfirmation.BearerMethod,
                SubjectConfirmationData = new SubjectConfirmationData
                {
                    NotOnOrAfter = notOnOrAfter,
                    Recipient    = args.Recipient.Value,
                    InResponseTo = args.RequestId.Value,
                },
            };

            assertion.Subject.Items = new object[]
            {
                new NameId
                {
                    Format = "urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress",
                    Value  = args.Email.Value
                },
                subjectConfirmation
            };
            assertion.Conditions = new Conditions {
                NotOnOrAfter = notOnOrAfter
            };
            var audienceRestriction = new AudienceRestriction
            {
                Audience = new List <string>(new[] { args.Audience.Value })
            };

            assertion.Conditions.Items = new List <ConditionAbstract>(new ConditionAbstract[]
            {
                audienceRestriction
            });
            AuthnStatement authnStatement;
            {
                authnStatement              = new AuthnStatement();
                assertion.Items             = new StatementAbstract[] { authnStatement };
                authnStatement.AuthnInstant = authnInstant;
                authnStatement.SessionIndex = sessionIndex;
                authnStatement.AuthnContext = new AuthnContext
                {
                    Items = new object[]
                    {
                        "urn:oasis:names:tc:SAML:2.0:ac:classes:X509"
                    },
                    ItemsElementName = new[]
                    {
                        AuthnContextType.AuthnContextClassRef
                    }
                };
            }
            AttributeStatement attributeStatement;

            {
                attributeStatement = new AttributeStatement();
                var email = new SamlAttribute
                {
                    Name           = "User.email",
                    NameFormat     = "urn:oasis:names:tc:SAML:2.0:attrname-format:basic",
                    AttributeValue = new[] { args.Email.Value }
                };
                attributeStatement.Items = new object[] { email };
            }
            assertion.Items = new StatementAbstract[] { authnStatement, attributeStatement };
            return(assertion);
        }
コード例 #27
0
        /// <summary>
        /// Assembles our basic test assertion
        /// </summary>
        /// <returns></returns>
        public static Assertion GetBasicAssertion()
        {
            Assertion assertion = new Assertion();

            {
                assertion.Issuer       = new NameID();
                assertion.ID           = "_b8977dc86cda41493fba68b32ae9291d";
                assertion.IssueInstant = DateTime.UtcNow;

                assertion.Version      = "2.0";
                assertion.Issuer.Value = GetBasicIssuer();
            }

            {
                assertion.Subject = new Subject();
                SubjectConfirmation subjectConfirmation = new SubjectConfirmation();
                subjectConfirmation.Method = SubjectConfirmation.BEARER_METHOD;
                subjectConfirmation.SubjectConfirmationData = new SubjectConfirmationData();
                subjectConfirmation.SubjectConfirmationData.NotOnOrAfter = DateTime.UtcNow.AddMinutes(1);
                subjectConfirmation.SubjectConfirmationData.Recipient    = "http://borger.dk";
                assertion.Subject.Items = new object[] { subjectConfirmation };
            }

            {
                assertion.Conditions = new Conditions();
                assertion.Conditions.NotOnOrAfter = DateTime.UtcNow.AddMinutes(1);
                AudienceRestriction audienceRestriction = new AudienceRestriction();
                audienceRestriction.Audience = GetAudiences();
                assertion.Conditions.Items   = new List <ConditionAbstract>(new ConditionAbstract[] { audienceRestriction });
            }

            AuthnStatement authnStatement;

            {
                authnStatement                               = new AuthnStatement();
                assertion.Items                              = new StatementAbstract[] { authnStatement };
                authnStatement.AuthnInstant                  = new DateTime(2008, 1, 8);
                authnStatement.SessionIndex                  = "70225885";
                authnStatement.AuthnContext                  = new AuthnContext();
                authnStatement.AuthnContext.Items            = new object[] { "urn:oasis:names:tc:SAML:2.0:ac:classes:X509", "http://www.safewhere.net/authncontext/declref" };
                authnStatement.AuthnContext.ItemsElementName = new ItemsChoiceType5[] { ItemsChoiceType5.AuthnContextClassRef, ItemsChoiceType5.AuthnContextDeclRef };
            }

            AttributeStatement attributeStatement;

            {
                attributeStatement = new AttributeStatement();
                SamlAttribute surName = new SamlAttribute();
                surName.FriendlyName   = "SurName";
                surName.Name           = "urn:oid:2.5.4.4";
                surName.NameFormat     = SamlAttribute.NAMEFORMAT_URI;
                surName.AttributeValue = new string[] { "Fry" };

                SamlAttribute commonName = new SamlAttribute();
                commonName.FriendlyName   = "CommonName";
                commonName.Name           = "urn:oid:2.5.4.3";
                commonName.NameFormat     = SamlAttribute.NAMEFORMAT_URI;
                commonName.AttributeValue = new string[] { "Philip J. Fry" };

                SamlAttribute userName = new SamlAttribute();
                userName.Name           = "urn:oid:0.9.2342.19200300.100.1.1";
                userName.NameFormat     = SamlAttribute.NAMEFORMAT_URI;
                userName.AttributeValue = new string[] { "fry" };

                SamlAttribute eMail = new SamlAttribute();
                eMail.FriendlyName   = "Email";
                eMail.Name           = "urn:oid:0.9.2342.19200300.100.1.3";
                eMail.NameFormat     = SamlAttribute.NAMEFORMAT_URI;
                eMail.AttributeValue = new string[] { "*****@*****.**" };

                attributeStatement.Items = new object[] { surName, commonName, userName, eMail };
            }

            assertion.Items = new StatementAbstract[] { authnStatement, attributeStatement };

            return(assertion);
        }
コード例 #28
0
ファイル: AssertionUtil.cs プロジェクト: eByte23/SAMLSilly
        /// <summary>
        /// Assembles our basic test assertion
        /// </summary>
        /// <returns>The <see cref="Assertion"/>.</returns>
        public static Assertion GetBasicAssertion()
        {
            var assertion = new Assertion
            {
                Issuer       = new NameId(),
                Id           = "_b8977dc86cda41493fba68b32ae9291d",
                IssueInstant = DateTime.UtcNow,
                Version      = "2.0"
            };

            assertion.Issuer.Value = GetBasicIssuer();
            assertion.Subject      = new Subject();
            var subjectConfirmation = new SubjectConfirmation
            {
                Method = SubjectConfirmation.BearerMethod,
                SubjectConfirmationData =
                    new SubjectConfirmationData
                {
                    NotOnOrAfter = new DateTime(2008, 12, 31, 12, 0, 0, 0),
                    Recipient    = "http://borger.dk"
                }
            };

            assertion.Subject.Items = new object[] { subjectConfirmation };
            assertion.Conditions    = new Conditions {
                NotOnOrAfter = new DateTime(2008, 12, 31, 12, 0, 0, 0)
            };
            var audienceRestriction = new AudienceRestriction {
                Audience = GetAudiences().Select(u => u.ToString()).ToList()
            };

            assertion.Conditions.Items = new List <ConditionAbstract>(new ConditionAbstract[] { audienceRestriction });

            AuthnStatement authnStatement;
            {
                authnStatement              = new AuthnStatement();
                assertion.Items             = new StatementAbstract[] { authnStatement };
                authnStatement.AuthnInstant = new DateTime(2008, 1, 8);
                authnStatement.SessionIndex = "70225885";
                authnStatement.AuthnContext = new AuthnContext
                {
                    Items = new object[]
                    {
                        "urn:oasis:names:tc:SAML:2.0:ac:classes:X509",
                        "http://www.safewhere.net/authncontext/declref"
                    },
                    ItemsElementName = new[]
                    {
                        AuthnContextType.AuthnContextClassRef,
                        AuthnContextType.AuthnContextDeclRef
                    }
                };
            }

            AttributeStatement attributeStatement;

            {
                attributeStatement = new AttributeStatement();
                var surName = new SamlAttribute
                {
                    FriendlyName   = "SurName",
                    Name           = "urn:oid:2.5.4.4",
                    NameFormat     = SamlAttribute.NameformatUri,
                    AttributeValue = new[] { "Fry" }
                };

                var commonName = new SamlAttribute
                {
                    FriendlyName   = "CommonName",
                    Name           = "urn:oid:2.5.4.3",
                    NameFormat     = SamlAttribute.NameformatUri,
                    AttributeValue = new[] { "Philip J. Fry" }
                };

                var userName = new SamlAttribute
                {
                    Name           = "urn:oid:0.9.2342.19200300.100.1.1",
                    NameFormat     = SamlAttribute.NameformatUri,
                    AttributeValue = new[] { "fry" }
                };

                var email = new SamlAttribute
                {
                    FriendlyName   = "Email",
                    Name           = "urn:oid:0.9.2342.19200300.100.1.3",
                    NameFormat     = SamlAttribute.NameformatUri,
                    AttributeValue = new[] { "*****@*****.**" }
                };

                attributeStatement.Items = new object[] { surName, commonName, userName, email };
            }

            assertion.Items = new StatementAbstract[] { authnStatement, attributeStatement };

            return(assertion);
        }
コード例 #29
0
ファイル: SSOService.aspx.cs プロジェクト: HRINY/HRI-Umbraco
        // Create a SAML response with the user's local identity, if any, or indicating an error.
        private SAMLResponse CreateSAMLResponse(AuthnRequest authnRequest)
        {
            Trace.Write("IdP", "Creating SAML response");

            SAMLResponse samlResponse = new SAMLResponse();
            samlResponse.Destination = authnRequest.AssertionConsumerServiceURL;
            Issuer issuer = new Issuer(CreateAbsoluteURL("~/"));
            samlResponse.Issuer = issuer;

            if (User.Identity.IsAuthenticated) {
                samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null);

                SAMLAssertion samlAssertion = new SAMLAssertion();
                samlAssertion.Issuer = issuer;

                samlAssertion.Conditions = new Conditions(new TimeSpan(0, 10, 0));
                AudienceRestriction audienceRestriction = new AudienceRestriction();
                audienceRestriction.Audiences.Add(new Audience(authnRequest.AssertionConsumerServiceURL));
                samlAssertion.Conditions.ConditionsList.Add(audienceRestriction);

                Subject subject = new Subject(new NameID(User.Identity.Name));
                SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer);
                SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();
                subjectConfirmationData.InResponseTo = authnRequest.ID;
                subjectConfirmationData.Recipient = authnRequest.AssertionConsumerServiceURL;
                subjectConfirmationData.NotBefore = samlAssertion.Conditions.NotBefore;
                subjectConfirmationData.NotOnOrAfter = samlAssertion.Conditions.NotOnOrAfter;

                subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
                subject.SubjectConfirmations.Add(subjectConfirmation);
                samlAssertion.Subject = subject;

                AuthnStatement authnStatement = new AuthnStatement();
                authnStatement.AuthnContext = new AuthnContext();
                authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Password);
                samlAssertion.Statements.Add(authnStatement);

                samlResponse.Assertions.Add(samlAssertion);
            } else {
                samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Responder, SAMLIdentifiers.SecondaryStatusCodes.AuthnFailed, "The user is not authenticated at the identity provider");
            }

            Trace.Write("IdP", "Created SAML response");

            return samlResponse;
        }
コード例 #30
0
ファイル: SignonForm.aspx.cs プロジェクト: Tom-FP/OIOSAML.Net
        private Assertion CreateAssertion(User user, string receiver, string nameIdFormat)
        {
            Assertion assertion = new Assertion();

            { // Subject element
                assertion.Subject      = new Subject();
                assertion.ID           = "id" + Guid.NewGuid().ToString("N");
                assertion.IssueInstant = DateTime.Now.AddMinutes(10);

                assertion.Issuer       = new NameID();
                assertion.Issuer.Value = IDPConfig.ServerBaseUrl;

                SubjectConfirmation subjectConfirmation = new SubjectConfirmation();
                subjectConfirmation.Method = SubjectConfirmation.BEARER_METHOD;
                subjectConfirmation.SubjectConfirmationData = new SubjectConfirmationData();
                subjectConfirmation.SubjectConfirmationData.NotOnOrAfter = DateTime.Now.AddHours(1);
                subjectConfirmation.SubjectConfirmationData.Recipient    = receiver;

                NameID nameId = new NameID();
                nameId.Format = nameIdFormat;
                if (nameIdFormat == Saml20Constants.NameIdentifierFormats.Transient)
                {
                    nameId.Value = $"https://data.gov.dk/model/core/eid/{user.Profile}/uuid/" + Guid.NewGuid();
                }
                else
                {
                    nameId.Value = $"https://data.gov.dk/model/core/eid/{user.Profile}/uuid/{user.uuid}";
                }

                assertion.Subject.Items = new object[] { nameId, subjectConfirmation };
            }

            { // Conditions element
                assertion.Conditions       = new Conditions();
                assertion.Conditions.Items = new List <ConditionAbstract>();

                assertion.Conditions.NotOnOrAfter = DateTime.Now.AddHours(1);

                AudienceRestriction audienceRestriction = new AudienceRestriction();
                audienceRestriction.Audience = new List <string>();
                audienceRestriction.Audience.Add(receiver);
                assertion.Conditions.Items.Add(audienceRestriction);
            }

            List <StatementAbstract> statements = new List <StatementAbstract>(2);

            { // AuthnStatement element
                AuthnStatement authnStatement = new AuthnStatement();
                authnStatement.AuthnInstant = DateTime.Now;
                authnStatement.SessionIndex = Convert.ToString(new Random().Next());

                authnStatement.AuthnContext = new AuthnContext();

                authnStatement.AuthnContext.Items =
                    new object[] { "urn:oasis:names:tc:SAML:2.0:ac:classes:X509" };

                // Wow! Setting the AuthnContext is .... verbose.
                authnStatement.AuthnContext.ItemsElementName =
                    new ItemsChoiceType5[] { ItemsChoiceType5.AuthnContextClassRef };

                statements.Add(authnStatement);
            }

            { // Generate attribute list.
                AttributeStatement attributeStatement = new AttributeStatement();

                List <SamlAttribute> attributes = new List <SamlAttribute>(user.Attributes.Count);
                foreach (KeyValuePair <string, string> att in user.Attributes)
                {
                    var existingAttribute = attributes.FirstOrDefault(x => x.Name == att.Key);
                    if (existingAttribute != null)
                    {
                        var attributesValues = new List <string>();
                        attributesValues.AddRange(existingAttribute.AttributeValue);
                        attributesValues.Add(att.Value);
                        existingAttribute.AttributeValue = attributesValues.ToArray();
                    }
                    else
                    {
                        SamlAttribute attribute = new SamlAttribute();
                        attribute.Name           = att.Key;
                        attribute.AttributeValue = new string[] { att.Value };
                        attribute.NameFormat     = SamlAttribute.NAMEFORMAT_URI;
                        attributes.Add(attribute);
                    }
                }


                attributeStatement.Items = attributes.ToArray();

                statements.Add(attributeStatement);
            }

            assertion.Items = statements.ToArray();

            return(assertion);
        }
コード例 #31
0
ファイル: AuthController.cs プロジェクト: Inforward/Guideport
        private static XmlElement CreateSamlResponse(string assertionConsumerServiceUrl, List <SAMLAttribute> attributes, string requestId = null, bool signAssertion = false, bool signResponse = false, bool encryptAssertion = false)
        {
            var samlResponse = new SAMLResponse {
                Destination = assertionConsumerServiceUrl
            };
            var issuer = new Issuer(SAMLConfiguration.Current.IdentityProviderConfiguration.Name);
            var issuerX509CertificateFilePath = Path.Combine(HttpRuntime.AppDomainAppPath, SAMLConfiguration.Current.IdentityProviderConfiguration.CertificateFile);
            var issuerX509Certificate         = new X509Certificate2(issuerX509CertificateFilePath, SAMLConfiguration.Current.IdentityProviderConfiguration.CertificatePassword);
            var partner       = SessionHelper.Get <string>(PartnerSpSessionKey) ?? SAMLConfiguration.Current.ServiceProviderConfiguration.Name;
            var partnerConfig = SAMLConfiguration.Current.PartnerServiceProviderConfigurations[partner];
            var partnerX509CertificateFilePath = string.Empty;
            var partnerX509Certificate         = null as X509Certificate2;

            if (partnerConfig != null)
            {
                partnerX509CertificateFilePath = Path.Combine(HttpRuntime.AppDomainAppPath, partnerConfig.CertificateFile);
                partnerX509Certificate         = new X509Certificate2(partnerX509CertificateFilePath);
                signAssertion    = partnerConfig.SignAssertion;
                signResponse     = partnerConfig.SignSAMLResponse;
                encryptAssertion = partnerConfig.EncryptAssertion;
            }

            samlResponse.Issuer       = issuer;
            samlResponse.Status       = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null);
            samlResponse.IssueInstant = DateTime.Now;
            samlResponse.InResponseTo = requestId;

            var samlAssertion = new SAMLAssertion {
                Issuer = issuer, IssueInstant = samlResponse.IssueInstant
            };

            var profileId               = attributes.Where(a => a.Name == PortalClaimTypes.ProfileId).Select(a => a.Values[0].ToString()).FirstOrDefault();
            var subject                 = new Subject(new NameID(profileId));
            var subjectConfirmation     = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer);
            var subjectConfirmationData = new SubjectConfirmationData {
                Recipient = assertionConsumerServiceUrl
            };

            subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
            subject.SubjectConfirmations.Add(subjectConfirmation);
            samlAssertion.Subject = subject;

            var conditions          = new Conditions(DateTime.Now, DateTime.Now.AddDays(1));
            var audienceRestriction = new AudienceRestriction();

            audienceRestriction.Audiences.Add(new Audience(partner));
            conditions.ConditionsList.Add(audienceRestriction);
            samlAssertion.Conditions = conditions;

            var authnStatement = new AuthnStatement {
                AuthnContext = new AuthnContext(), AuthnInstant = samlResponse.IssueInstant
            };

            authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.X509);
            samlAssertion.Statements.Add(authnStatement);

            attributes.ForEach(a =>
            {
                var attributeStatement = new AttributeStatement();

                attributeStatement.Attributes.Add(a);
                samlAssertion.Statements.Add(attributeStatement);
            });

            var samlAssertionXml = samlAssertion.ToXml();

            if (signAssertion)
            {
                SAMLAssertionSignature.Generate(samlAssertionXml, issuerX509Certificate.PrivateKey, issuerX509Certificate);
            }

            if (encryptAssertion)
            {
                var encryptedAssertion = new EncryptedAssertion(samlAssertionXml, partnerX509Certificate);

                samlResponse.Assertions.Add(encryptedAssertion.ToXml());
            }
            else
            {
                samlResponse.Assertions.Add(samlAssertionXml);
            }

            var samlResponseXml = samlResponse.ToXml();

            if (signResponse)
            {
                SAMLMessageSignature.Generate(samlResponseXml, issuerX509Certificate.PrivateKey, issuerX509Certificate);
            }

            return(samlResponseXml);
        }
コード例 #32
0
        /// <summary>
        /// Handles the Click event of the submitButton control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void submitButton_Click(object sender, EventArgs e)
        {
            Transmittal transmittal = null;
            string      employeeID  = this._EmployeeID.Text;

            if (!string.IsNullOrEmpty(this._XMLText.Text))
            {
                try
                {
                    transmittal = (Transmittal)SerializationHelper.DeserializeFromString(this._XMLText.Text, typeof(Transmittal));
                }
                catch (Exception exception)
                {
                    this._XMLText.Text = exception.Message;
                    Exception inner = exception.InnerException;

                    while (inner != null)
                    {
                        this._XMLText.Text += "\n" + inner.Message;
                        inner = inner.InnerException;
                    }

                    this._XMLText.Text = PrepareSourceCode(this._XMLText.Text);
                }
            }

            if (!string.IsNullOrEmpty(employeeID) && transmittal != null && transmittal.Applicants != null && transmittal.Applicants.Count > 0)
            {
                transmittal.Applicants[0].EmployeeIdent = employeeID;
            }

            Session["Transmittal"] = transmittal;

            //Creating SAML responce
            X509Certificate2 vendorCertificate  = GetVendorCertificate();
            X509Certificate2 selerixCertificate = GetSelerixCertificate();

            string assertionConsumerServiceURL = "SamlResponse.aspx";
            string audienceName = "whatever audience";

            SAMLResponse samlResponse = new SAMLResponse();

            samlResponse.Destination = assertionConsumerServiceURL;
            Issuer issuer = new Issuer("Vendor");

            samlResponse.Issuer = issuer;
            samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null);

            SAMLAssertion samlAssertion = new SAMLAssertion();

            samlAssertion.Issuer = issuer;

            Subject subject = null;

//          subject = new Subject(new EncryptedID(new NameID(employeeID), selerixCertificate, new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl))); //employee ID
            subject = new Subject(new NameID(employeeID)); //employee ID

            SubjectConfirmation     subjectConfirmation     = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer);
            SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();

            subjectConfirmationData.Recipient           = assertionConsumerServiceURL;
            subjectConfirmationData.NotOnOrAfter        = DateTime.UtcNow.AddHours(1);
            subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
            subject.SubjectConfirmations.Add(subjectConfirmation);

            samlAssertion.Subject = subject;

            Conditions          conditions          = new Conditions(new TimeSpan(1, 0, 0));
            AudienceRestriction audienceRestriction = new AudienceRestriction();

            audienceRestriction.Audiences.Add(new Audience(audienceName));
            conditions.ConditionsList.Add(audienceRestriction);
            samlAssertion.Conditions = conditions;

            AuthnStatement authnStatement = new AuthnStatement();

            authnStatement.AuthnContext = new AuthnContext();
            authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SAMLIdentifiers.AuthnContextClasses.Unspecified);
            samlAssertion.Statements.Add(authnStatement);

            AttributeStatement attributeStatement = new AttributeStatement();

            if (transmittal != null)
            {
                attributeStatement.Attributes.Add(new SAMLAttribute("Transmittal", SAMLIdentifiers.AttributeNameFormats.Basic, null, SerializationHelper.SerializeToString(transmittal)));

                if (transmittal.Applicants != null && transmittal.Applicants.Count > 0)
                {
                    transmittal.Applicants[0].EmployeeIdent = employeeID;
                }
            }

            //Check for Transmittal Options
            for (int i = 0; i < _TransmittalOptionsList.Items.Count; i++)
            {
                string answer = "no";

                if (_TransmittalOptionsList.Items[i].Selected)
                {
                    answer = "yes";
                }

                if (_TransmittalOptionsList.Items[i].Value == "HeaderAndFooter")
                {
                    attributeStatement.Attributes.Add(new SAMLAttribute("HeaderAndFooter", SAMLIdentifiers.AttributeNameFormats.Basic, null, answer));
                }
                else if (_TransmittalOptionsList.Items[i].Value == "Sidebar")
                {
                    attributeStatement.Attributes.Add(new SAMLAttribute("Sidebar", SAMLIdentifiers.AttributeNameFormats.Basic, null, answer));
                }
                else if (_TransmittalOptionsList.Items[i].Value == "PersonalInfo")
                {
                    attributeStatement.Attributes.Add(new SAMLAttribute("PersonalInfo", SAMLIdentifiers.AttributeNameFormats.Basic, null, answer));
                }
                else if (_TransmittalOptionsList.Items[i].Value == "Welcome")
                {
                    attributeStatement.Attributes.Add(new SAMLAttribute("Welcome", SAMLIdentifiers.AttributeNameFormats.Basic, null, answer));
                }
                else if (_TransmittalOptionsList.Items[i].Value == "Review")
                {
                    attributeStatement.Attributes.Add(new SAMLAttribute("Review", SAMLIdentifiers.AttributeNameFormats.Basic, null, answer));
                }
            }

            samlAssertion.Statements.Add(attributeStatement);

//          EncryptedAssertion encryptedAssertion = new EncryptedAssertion(samlAssertion, selerixCertificate, new EncryptionMethod(EncryptedXml.XmlEncTripleDESUrl));
//          samlResponse.Assertions.Add(encryptedAssertion);
            samlResponse.Assertions.Add(samlAssertion);

            //Created SAML response

            //Sending SAML response

            // Serialize the SAML response for transmission.
            XmlElement samlResponseXml = samlResponse.ToXml();

            // Sign the SAML response.
            SAMLMessageSignature.Generate(samlResponseXml, vendorCertificate.PrivateKey, vendorCertificate);

            HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
            HttpContext.Current.Response.AddHeader("Pragma", "no-cache");

            IdentityProvider.SendSAMLResponseByHTTPPost(HttpContext.Current.Response, assertionConsumerServiceURL, samlResponseXml, "");// for test purposes
        }