Exemple #1
1
        // Create a SAML response with the user's local identity, if any, or indicating an error.
        private SAMLResponse CreateSAMLResponse(SSOState ssoState)
        {
            Trace.Write("IdP", "Creating SAML response");

            SAMLResponse samlResponse = new SAMLResponse();
            string issuerURL = CreateAbsoluteURL("~/");
            Issuer issuer = new Issuer(issuerURL);
            samlResponse.Issuer = issuer;

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

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

                Subject subject = new Subject(new NameID(User.Identity.Name));
                SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer);
                SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();
                subjectConfirmationData.InResponseTo = ssoState.authnRequest.ID;
                subjectConfirmationData.Recipient = ssoState.assertionConsumerServiceURL;
                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);

                // Attributes may be included in the SAML assertion.
                AttributeStatement attributeStatement = new AttributeStatement();
                attributeStatement.Attributes.Add(new SAMLAttribute("Membership", SAMLIdentifiers.AttributeNameFormats.Basic, null, "Gold"));
                samlAssertion.Statements.Add(attributeStatement);

                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;
        }
Exemple #2
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(CreateAbsoluteURL("~/"));
            samlResponse.Issuer = issuer;
            samlResponse.Status = new Status(SAMLIdentifiers.PrimaryStatusCodes.Success, null);

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

            Subject subject = new Subject(new NameID(User.Identity.Name));
            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;

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

            samlResponse.Assertions.Add(samlAssertion);

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

            return samlResponse;
        }
        public void ValidateSubjectConfirmation(SubjectConfirmation subjectConfirmation)
        {
            if (subjectConfirmation == null) throw new ArgumentNullException("subjectConfirmation");

            if (!Saml2Utils.ValidateRequiredString(subjectConfirmation.Method))
                throw new Saml2FormatException("Method attribute of SubjectConfirmation MUST contain at least one non-whitespace character");

            if (!Uri.IsWellFormedUriString(subjectConfirmation.Method, UriKind.Absolute))
                throw new Saml2FormatException("SubjectConfirmation element has Method attribute which is not a wellformed absolute uri.");

            if (subjectConfirmation.Method == Saml2Constants.SubjectConfirmationMethods.HolderOfKey)
                _keyInfoValidator.ValidateKeyInfo(subjectConfirmation.SubjectConfirmationData);

            if (subjectConfirmation.Item != null)
            {
                if (subjectConfirmation.Item is NameID)
                    NameIdValidator.ValidateNameID((NameID)subjectConfirmation.Item);
                else if (subjectConfirmation.Item is EncryptedElement)
                    NameIdValidator.ValidateEncryptedID((EncryptedElement)subjectConfirmation.Item);
                else
                    throw new Saml2FormatException(string.Format("Identifier of type {0} is not supported for SubjectConfirmation", subjectConfirmation.Item.GetType()));
            }
            else if (subjectConfirmation.SubjectConfirmationData != null)
                SubjectConfirmationDataValidator.ValidateSubjectConfirmationData(subjectConfirmation.SubjectConfirmationData);
        }
Exemple #4
0
        public void ValidateSubject(Subject subject)
        {
            if (subject.Items == null || subject.Items.Length == 0)
            {
                throw new DKSaml20FormatException("The DK-SAML 2.0 Profile requires at least one \"SubjectConfirmation\" element within the \"Subject\" element.");
            }

            bool subjectConfirmationPresent = false;

            foreach (object item in subject.Items)
            {
                if (item is SubjectConfirmation)
                {
                    SubjectConfirmation subjectConfirmation = (SubjectConfirmation)item;
                    if (subjectConfirmation.Method == SubjectConfirmation.BEARER_METHOD)
                    {
                        subjectConfirmationPresent = true;
                    }

                    SubjectConfirmationValidator.ValidateSubjectConfirmation(subjectConfirmation);
                }
            }
            if (!subjectConfirmationPresent)
            {
                throw new DKSaml20FormatException("The DK-SAML 2.0 Profile requires that a bearer \"SubjectConfirmation\" element is present.");
            }
        }
Exemple #5
0
        public void ValidateSubjectConfirmation(SubjectConfirmation subjectConfirmation)
        {
            if (subjectConfirmation.Method == SubjectConfirmation.BEARER_METHOD)
            {
                if (subjectConfirmation.SubjectConfirmationData == null)
                {
                    throw new DKSaml20FormatException("The SAML profile requires that the bearer \"SubjectConfirmation\" element contains a \"SubjectConfirmationData\" element.");
                }

                if (!Saml20Utils.ValidateRequiredString(subjectConfirmation.SubjectConfirmationData.Recipient))
                {
                    throw new DKSaml20FormatException("The SAML profile requires that the \"SubjectConfirmationData\" element contains the \"Recipient\" attribute.");
                }

                if (!subjectConfirmation.SubjectConfirmationData.NotOnOrAfter.HasValue)
                {
                    throw new DKSaml20FormatException("The SAML profile requires that the \"SubjectConfirmationData\" element contains the \"NotOnOrAfter\" attribute.");
                }

                if (subjectConfirmation.SubjectConfirmationData.NotBefore.HasValue)
                {
                    throw new DKSaml20FormatException("The SAML profile disallows the use of the \"NotBefore\" attribute of the \"SubjectConfirmationData\" element.");
                }
            }
        }
Exemple #6
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);
        }
            public void ThrowsExceptionWhenSubjectConfirmationHasEmptyMethod()
            {
                // Arrange
                var subjectConfirmation = new SubjectConfirmation {
                    Method = " "
                };
                var validator = new Saml20SubjectConfirmationValidator();

                // Act
                validator.ValidateSubjectConfirmation(subjectConfirmation, false);
            }
            public void ThrowsExceptionWhenSubjectConfirmationHasWrongMethod()
            {
                // Arrange
                var subjectConfirmation = new SubjectConfirmation {
                    Method = "malformed uri"
                };
                var validator = new Saml20SubjectConfirmationValidator();

                // Act
                validator.ValidateSubjectConfirmation(subjectConfirmation);
            }
            public void ThrowsExceptionWhenSubjectConfirmationHasWrongMethod()
            {
                // Arrange
                var subjectConfirmation = new SubjectConfirmation {
                    Method = "malformed uri"
                };
                var validator = new Saml20SubjectConfirmationValidator();

                // Act
                Assert.Throws <Saml20FormatException>(() => validator.ValidateSubjectConfirmation(subjectConfirmation),
                                                      "SubjectConfirmation element has Method attribute which is not a wellformed absolute uri.");
            }
            public void ThrowsExceptionWhenSubjectConfirmationHasEmptyMethod()
            {
                // Arrange
                var subjectConfirmation = new SubjectConfirmation {
                    Method = " "
                };
                var validator = new Saml20SubjectConfirmationValidator();

                // Act
                Assert.Throws <Saml20FormatException>(() => validator.ValidateSubjectConfirmation(subjectConfirmation),
                                                      "Method attribute of SubjectConfirmation MUST contain at least one non-whitespace character");
            }
        // 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);
        }
            //ExpectedMessage = "Method attribute of SubjectConfirmation MUST contain at least one non-whitespace character")]
            public void ThrowsExceptionWhenSubjectConfirmationHasEmptyMethod()
            {
                // Arrange
                var subjectConfirmation = new SubjectConfirmation {
                    Method = " "
                };
                var validator = new Saml20SubjectConfirmationValidator();

                // Act
                Assert.Throws(typeof(Saml20FormatException), () =>
                {
                    validator.ValidateSubjectConfirmation(subjectConfirmation);
                });
            }
            public void ThrowsExceptionWhenSubjectConfirmationDataDoesNotContainKeyInfo()
            {
                // Arrange
                var subjectConfirmation = new SubjectConfirmation
                {
                    Method = Saml20Constants.SubjectConfirmationMethods.HolderOfKey,
                    SubjectConfirmationData = new SubjectConfirmationData()
                };

                var validator = new Saml20SubjectConfirmationValidator();

                // Act
                validator.ValidateSubjectConfirmation(subjectConfirmation);
            }
            public void ThrowsExceptionWhenSubjectConfirmationDataDoesNotContainKeyInfo()
            {
                // Arrange
                var subjectConfirmation = new SubjectConfirmation
                {
                    Method = Saml20Constants.SubjectConfirmationMethods.HolderOfKey,
                    SubjectConfirmationData = new SubjectConfirmationData()
                };

                var validator = new Saml20SubjectConfirmationValidator();

                // Act
                Assert.Throws <Saml20FormatException>(() => validator.ValidateSubjectConfirmation(subjectConfirmation),
                                                      "SubjectConfirmationData element MUST have at least one " + KeyInfo.ElementName + " subelement");
            }
Exemple #15
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;
        }
        // Create a SAML response with the user's local identity, if any, or indicating an error.
        private SAMLResponse CreateSAMLResponse(SSOState ssoState)
        {
            Trace.Write("IdP", "Creating SAML response");

            SAMLResponse samlResponse = new SAMLResponse();
            string       issuerURL    = CreateAbsoluteURL("~/");
            Issuer       issuer       = new Issuer(issuerURL);

            samlResponse.Issuer = issuer;

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

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

                Subject                 subject                 = new Subject(new NameID(User.Identity.Name));
                SubjectConfirmation     subjectConfirmation     = new SubjectConfirmation(SAMLIdentifiers.SubjectConfirmationMethods.Bearer);
                SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();
                subjectConfirmationData.InResponseTo        = ssoState.authnRequest.ID;
                subjectConfirmationData.Recipient           = ssoState.assertionConsumerServiceURL;
                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);

                // Attributes may be included in the SAML assertion.
                AttributeStatement attributeStatement = new AttributeStatement();
                attributeStatement.Attributes.Add(new SAMLAttribute("Membership", SAMLIdentifiers.AttributeNameFormats.Basic, null, "Gold"));
                samlAssertion.Statements.Add(attributeStatement);

                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);
        }
        public void AddConfirmation([DefaultValue("urn:oasis:names:tc:SAML:2.0:cm:bearer")] string method, Uri recipient, int minutes)
        {
            _confirmation = new SubjectConfirmation
            {
                Method = new Uri(method),
            };

            var data = new SubjectConfirmationData
            {
                NotOnOrAfter = new DateTimeOffset(_now.AddMinutes(minutes)),
                Recipient    = recipient
            };

            _confirmation.Add(data);

            _response.Subject.Add(_confirmation);
        }
        public void Subject_Element()
        {
            Assertion saml20Assertion = AssertionUtil.GetBasicAssertion();

            Assert.IsNotNull(saml20Assertion.Subject);

            Assert.That(saml20Assertion.Subject.Items.Length > 0);

            SubjectConfirmation subjectConfirmation =
                (SubjectConfirmation)Array.Find(saml20Assertion.Subject.Items, delegate(object item) { return(item is SubjectConfirmation); });

            Assert.IsNotNull(subjectConfirmation);
            string originalMethod = subjectConfirmation.Method;

            subjectConfirmation.Method = "IllegalMethod";

            TestAssertion(saml20Assertion, "SubjectConfirmation element has Method attribute which is not a wellformed absolute uri.");
            // Try a valid url.
            subjectConfirmation.Method = "http://example.com";
            TestAssertion(saml20Assertion, "The DK-SAML 2.0 Profile requires that a bearer \"SubjectConfirmation\" element is present.");

            // Restore valid settings... And verify that it is restored.
            subjectConfirmation.Method = originalMethod;
            TestAssertion(saml20Assertion, null);

            // Now, start messing with the <SubjectConfirmationData> element.
            subjectConfirmation.SubjectConfirmationData.NotOnOrAfter = null;
            TestAssertion(saml20Assertion, "The DK-SAML 2.0 Profile requires that the \"SubjectConfirmationData\" element contains the \"NotOnOrAfter\" attribute.");
            subjectConfirmation.SubjectConfirmationData.NotOnOrAfter = DateTime.UtcNow;

            subjectConfirmation.SubjectConfirmationData.NotBefore = DateTime.UtcNow.Subtract(new TimeSpan(5, 0, 0, 0));
            TestAssertion(saml20Assertion, "The DK-SAML 2.0 Profile disallows the use of the \"NotBefore\" attribute of the \"SubjectConfirmationData\" element.");

            subjectConfirmation.SubjectConfirmationData.NotBefore = null;

            string originalRecipient = subjectConfirmation.SubjectConfirmationData.Recipient;

            subjectConfirmation.SubjectConfirmationData.Recipient = null;
            TestAssertion(saml20Assertion, "The DK-SAML 2.0 Profile requires that the \"SubjectConfirmationData\" element contains the \"Recipient\" attribute.");
            subjectConfirmation.SubjectConfirmationData.Recipient = originalRecipient;

            saml20Assertion.Subject = null;
            TestAssertion(saml20Assertion, "AuthnStatement, AuthzDecisionStatement and AttributeStatement require a subject.");
        }
            public void ValidatesSubjectConfirmationData_Method_HolderOfKey_Valid()
            {
                // Arrange
                var subjectConfirmation = new SubjectConfirmation
                {
                    Method = Saml20Constants.SubjectConfirmationMethods.HolderOfKey,
                    SubjectConfirmationData = new SubjectConfirmationData()
                };
                var doc  = new XmlDocument();
                var elem = doc.CreateElement("ds", "KeyInfo", Saml20Constants.Xmldsig);

                elem.AppendChild(doc.CreateElement("lalala"));

                subjectConfirmation.SubjectConfirmationData.AnyElements = new[] { elem };

                var validator = new Saml20SubjectConfirmationValidator();

                // Act
                validator.ValidateSubjectConfirmation(subjectConfirmation);
            }
        /// <summary>
        /// Builds the SAML response.
        /// </summary>
        /// <param name="authnRequest">The AuthnRequest object.</param>
        /// <returns>A SAML Response object.</returns>
        public static ComponentPro.Saml2.Response BuildResponse(Page page, AuthnRequest authnRequest)
        {
            ComponentPro.Saml2.Response samlResponse = new ComponentPro.Saml2.Response();
            samlResponse.Destination = Global.AssertionServiceUrl;
            Issuer issuer = new Issuer(GetAbsoluteUrl(page, "~/"));

            samlResponse.Issuer = issuer;

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

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

                Subject                 subject                 = new Subject(new NameId(page.User.Identity.Name));
                SubjectConfirmation     subjectConfirmation     = new SubjectConfirmation(SamlSubjectConfirmationMethod.Bearer);
                SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();
                subjectConfirmationData.InResponseTo        = authnRequest.Id;
                subjectConfirmationData.Recipient           = Global.AssertionServiceUrl;
                subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
                subject.SubjectConfirmations.Add(subjectConfirmation);
                samlAssertion.Subject = subject;

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

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

            return(samlResponse);
        }
Exemple #21
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(CreateAbsoluteURL("~/"));

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

            SAMLAssertion samlAssertion = new SAMLAssertion();

            samlAssertion.Issuer = issuer;

            Subject                 subject                 = new Subject(new NameID(User.Identity.Name));
            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;

            AuthnStatement authnStatement = new AuthnStatement();

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

            samlResponse.Assertions.Add(samlAssertion);

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

            return(samlResponse);
        }
Exemple #22
0
        protected override Assertion GenerateAssertion()
        {
            //Create SubjectConfirmationData based on AuthLevel.
            SubjectConfirmation subjectConf = new SubjectConfirmation();

            if (AuthenticationLevel.Equals(AuthenticationLevel.UsernamePasswordAuthentication))
            {
                var subjectConfData = new SubjectConfirmationData
                {
                    Item = new UsernameToken()
                    {
                        Username = Username, Password = Password
                    }
                };
                subjectConf.SubjectConfirmationData = subjectConfData;
            }
            else if (AuthenticationLevel.Equals(AuthenticationLevel.MocesTrustedUser) || AuthenticationLevel.Equals(AuthenticationLevel.VocesTrustedSystem))
            {
                var subjectConfData = new SubjectConfirmationData
                {
                    Item = new KeyInfo
                    {
                        Item = "OCESSignature"
                    }
                };
                subjectConf.SubjectConfirmationData = subjectConfData;
                subjectConf.ConfirmationMethod      = ConfirmationMethod.urnoasisnamestcSAML20cmholderofkey;
            }

            //Create NameID based on alternative identifier
            NameID nameId = new NameID();

            if (string.IsNullOrEmpty(AlternativeIdentifier))
            {
                nameId.Format = SystemInfo.CareProvider.Type;
                nameId.Value  = SystemInfo.CareProvider.Id;
            }
            else
            {
                nameId.Format = SubjectIdentifierType.medcomother;
                nameId.Value  = AlternativeIdentifier;
            }

            var ass = new Assertion
            {
                IssueInstant = CreatedDate,
                id           = "IDCard",
                Version      = 2.0m,
                Issuer       = Issuer,
                Conditions   = new Conditions
                {
                    NotBefore    = CreatedDate,
                    NotOnOrAfter = ExpiryDate
                },
                Subject = new Subject
                {
                    NameID = nameId,
                    SubjectConfirmation = AuthenticationLevel.Equals(AuthenticationLevel.NoAuthentication) ? null : subjectConf
                },
                AttributeStatement = new[]
                {
                    new AttributeStatement
                    {
                        id        = AttributeStatementID.IDCardData,
                        Attribute = new []
                        {
                            new Attribute {
                                Name = AttributeName.sosiIDCardID, AttributeValue = IdCardId
                            },
                            new Attribute {
                                Name = AttributeName.sosiIDCardVersion, AttributeValue = Version
                            },
                            new Attribute {
                                Name = AttributeName.sosiIDCardType, AttributeValue = "system"
                            },
                            new Attribute {
                                Name = AttributeName.sosiAuthenticationLevel, AttributeValue = AuthenticationLevel.Level.ToString()
                            },
                            new Attribute {
                                Name = AttributeName.sosiOCESCertHash, AttributeValue = CertHash,
                            }
                        }
                    },
                    new AttributeStatement
                    {
                        id        = AttributeStatementID.SystemLog,
                        Attribute = new []
                        {
                            new Attribute {
                                Name = AttributeName.medcomITSystemName, AttributeValue = SystemInfo.ItSystemName
                            },
                            new Attribute
                            {
                                Name                = AttributeName.medcomCareProviderID,
                                AttributeValue      = SystemInfo.CareProvider.Id,
                                NameFormatSpecified = true,
                                NameFormat          = SystemInfo.CareProvider.Type
                            },
                            new Attribute {
                                Name = AttributeName.medcomCareProviderName, AttributeValue = SystemInfo.CareProvider.OrgName
                            },
                        }
                    }
                }
            };

            return(ass);
        }
Exemple #23
0
        public void ValidateTimeRestrictions(Assertion assertion, TimeSpan allowedClockSkew)
        {
            // Conditions are not required
            if (assertion.Conditions == null)
            {
                return;
            }

            Conditions conditions = assertion.Conditions;
            DateTime   now        = DateTime.UtcNow;

            // Negative allowed clock skew does not make sense - we are trying to relax the restriction interval, not restrict it any further
            if (allowedClockSkew < TimeSpan.Zero)
            {
                allowedClockSkew = allowedClockSkew.Negate();
            }

            // NotBefore must not be in the future
            if (!ValidateNotBefore(conditions.NotBefore, now, allowedClockSkew))
            {
                throw new Saml20FormatException("Conditions.NotBefore must not be in the future");
            }

            // NotOnOrAfter must not be in the past
            if (!ValidateNotOnOrAfter(conditions.NotOnOrAfter, now, allowedClockSkew))
            {
                throw new Saml20FormatException("Conditions.NotOnOrAfter must not be in the past");
            }

            foreach (AuthnStatement statement in assertion.GetAuthnStatements())
            {
                if (statement.SessionNotOnOrAfter != null &&
                    statement.SessionNotOnOrAfter <= now)
                {
                    throw new Saml20FormatException("AuthnStatement attribute SessionNotOnOrAfter MUST be in the future");
                }

                // TODO: Consider validating that authnStatement.AuthnInstant is in the past
            }

            if (assertion.Subject != null)
            {
                foreach (object o in assertion.Subject.Items)
                {
                    if (!(o is SubjectConfirmation))
                    {
                        continue;
                    }

                    SubjectConfirmation subjectConfirmation = (SubjectConfirmation)o;
                    if (subjectConfirmation.SubjectConfirmationData == null)
                    {
                        continue;
                    }

                    if (!ValidateNotBefore(subjectConfirmation.SubjectConfirmationData.NotBefore, now, allowedClockSkew))
                    {
                        throw new Saml20FormatException("SubjectConfirmationData.NotBefore must not be in the future");
                    }

                    if (!ValidateNotOnOrAfter(subjectConfirmation.SubjectConfirmationData.NotOnOrAfter, now, allowedClockSkew))
                    {
                        throw new Saml20FormatException("SubjectConfirmationData.NotOnOrAfter must not be in the past");
                    }
                }
            }
        }
Exemple #24
0
        /// <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);
        }
Exemple #25
0
        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);
        }
Exemple #26
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
        }
Exemple #27
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);
        }
        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
        }
Exemple #29
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.Destination = Configuration.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;

                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 = Configuration.AssertionConsumerServiceURL;
                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;
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {
                // Extract the SP target url.
                string targetUrl = Request.QueryString["spUrl"];

                // Validate it.
                if (string.IsNullOrEmpty(targetUrl))
                {
                    return;
                }

                // Create a SAML response object.
                ComponentPro.Saml2.Response samlResponse = new ComponentPro.Saml2.Response();
                // Assign the consumer service url.
                samlResponse.Destination = ConsumerServiceUrl;
                Issuer issuer = new Issuer(GetAbsoluteUrl("~/"));
                samlResponse.Issuer = issuer;
                samlResponse.Status = new Status(SamlPrimaryStatusCode.Success, null);

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

                // Use the local user's local identity.
                Subject                 subject                 = new Subject(new NameId(User.Identity.Name));
                SubjectConfirmation     subjectConfirmation     = new SubjectConfirmation(SamlSubjectConfirmationMethod.Bearer);
                SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();
                subjectConfirmationData.Recipient           = ConsumerServiceUrl;
                subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
                subject.SubjectConfirmations.Add(subjectConfirmation);
                samlAssertion.Subject = subject;

                // Create a new authentication statement.
                AuthnStatement authnStatement = new AuthnStatement();
                authnStatement.AuthnContext = new AuthnContext();
                authnStatement.AuthnContext.AuthnContextClassRef = new AuthnContextClassRef(SamlAuthenticateContext.Password);
                samlAssertion.Statements.Add(authnStatement);

                // If you need to add custom attributes, uncomment the following code
                // #region Custom Attributes
                // AttributeStatement attributeStatement = new AttributeStatement();
                // attributeStatement.Attributes.Add(new ComponentPro.Saml2.Attribute("email", SamlAttributeNameFormat.Basic, null,
                // "*****@*****.**"));
                // attributeStatement.Attributes.Add(new ComponentPro.Saml2.Attribute("FirstName", SamlAttributeNameFormat.Basic, null,
                // "John"));
                // attributeStatement.Attributes.Add(new ComponentPro.Saml2.Attribute("LastName", SamlAttributeNameFormat.Basic, null,
                // "Smith"));

                // // Insert a custom token key to the SAML response.
                // attributeStatement.Attributes.Add(new ComponentPro.Saml2.Attribute("CustomTokenForVerification", SamlAttributeNameFormat.Basic, null,
                // "YourEncryptedTokenHere"));

                // samlAssertion.Statements.Add(attributeStatement);
                // #endregion


                // Define ENCRYPTEDSAML preprocessor flag if you wish to encrypt the SAML response.
#if ENCRYPTEDSAML
                // Load the certificate for the encryption.
                // Please make sure the file is in the root directory.
                X509Certificate2 encryptingCert = new X509Certificate2(Path.Combine(HttpRuntime.AppDomainAppPath, "EncryptionX509Certificate.cer"), "password");

                // Create an encrypted SAML assertion from the SAML assertion we have created.
                EncryptedAssertion encryptedSamlAssertion = new EncryptedAssertion(samlAssertion, encryptingCert, new System.Security.Cryptography.Xml.EncryptionMethod(SamlKeyAlgorithm.TripleDesCbc));

                // Add encrypted assertion to the SAML response object.
                samlResponse.Assertions.Add(encryptedSamlAssertion);
#else
                // Add assertion to the SAML response object.
                samlResponse.Assertions.Add(samlAssertion);
#endif

                // Get the previously loaded certificate.
                X509Certificate2 x509Certificate = (X509Certificate2)Application[Global.CertKeyName];

                // Sign the SAML response with the certificate.
                samlResponse.Sign(x509Certificate);

                // Send the SAML response to the service provider.
                samlResponse.SendPostBindingForm(Response.OutputStream, ConsumerServiceUrl, targetUrl);
            }

            catch (Exception exception)
            {
                Trace.Write("IdentityProvider", "An Error occurred", exception);
            }
        }
Exemple #31
0
        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);
        }
Exemple #32
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);
        }
Exemple #33
0
        /// <summary>
        /// Processes a successful SAML response and redirect to the requested URL.
        /// </summary>
        /// <param name="page">The page object.</param>
        /// <param name="samlResponse">The SAML response object.</param>
        /// <param name="relayState">The relay state.</param>
        public static void SamlSuccessRedirect(Page page, ComponentPro.Saml2.Response samlResponse, string relayState)
        {
            // Get the previously loaded certificate.
            X509Certificate2 x509Certificate = (X509Certificate2)page.Application[Global.SpCertKey];

            Assertion samlAssertion;

            // Check assertions.
            if (samlResponse.GetAssertions().Count > 0)
            {
                // Extract the first assertion.
                samlAssertion = samlResponse.GetAssertions()[0];
            }
            else if (samlResponse.GetEncryptedAssertions().Count > 0)
            {
                // Extract the first assertion.
                samlAssertion = samlResponse.GetEncryptedAssertions()[0].Decrypt(x509Certificate.PrivateKey, null);
            }
            else
            {
                throw new ApplicationException("No assertions in response");
            }

            string userName;

            // Get the subject name identifier.
            if (samlAssertion.Subject.NameId != null)
            {
                //userName = samlAssertion.Subject.NameId.NameIdentifier;
                userName = samlAssertion.GetAttributeValueByFriendlyName("eduPersonPrincipalName");

                System.Collections.Generic.Dictionary<string, string> dict = new System.Collections.Generic.Dictionary<string, string>();

                foreach (ComponentPro.Saml2.Attribute attribute in samlAssertion.AttributeStatements[0].Attributes)
                {
                    dict.Add(attribute.FriendlyName, attribute.Values[0].ToString());
                    System.Diagnostics.Trace.WriteLine(attribute.FriendlyName + ":" + attribute.Values[0].ToString());
                }
                HttpContext.Current.Session.Add("samlAttributes", dict);
            }
            else if (samlAssertion.Subject.EncryptedId != null)
            {
                NameId nameId = samlAssertion.Subject.EncryptedId.Decrypt(x509Certificate.PrivateKey, null);
                userName = nameId.NameIdentifier;
            }
            else
            {
                throw new ApplicationException("No name in subject");
            }


            try
            {
                string aaURL = "https://idp.testshib.org:8443/idp/profile/SAML2/SOAP/AttributeQuery";
                //Testing subject
                NameId subje = new NameId(userName,null,null,SamlNameIdentifierFormat.Unspecified,aaURL);
                
                //Testing subject
                Subject subject = new Subject(new NameId(userName));
                SubjectConfirmation subjectConfirmation = new SubjectConfirmation(SamlSubjectConfirmationMethod.Bearer);
                SubjectConfirmationData subjectConfirmationData = new SubjectConfirmationData();
                subjectConfirmationData.Recipient = aaURL;
                subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
                subject.SubjectConfirmations.Add(subjectConfirmation);

                AttributeQuery attributeQuery = new AttributeQuery();
                //attributeQuery.Subject = subject;
                attributeQuery.Destination = aaURL;
                attributeQuery.Issuer = new Issuer(Global.entityId);
                attributeQuery.Attributes.Add(new ComponentPro.Saml2.Attribute() { FriendlyName = "givenName" });
                attributeQuery.Subject = new Subject(samlAssertion.Subject.NameId);
                
                
                attributeQuery.Sign(x509Certificate);
                System.Diagnostics.Trace.WriteLine("Trying to get attributes from AA");
                System.Diagnostics.Trace.WriteLine("AA query " + attributeQuery.GetXml().OuterXml);
                System.Diagnostics.Trace.WriteLine("AA Subject " + attributeQuery.Subject.ToString());

                ArtifactResponse artifactResponse = ArtifactResponse.SendSamlMessageReceiveAftifactResponse(aaURL, attributeQuery);

                Response attrResponse;
                attrResponse = new ComponentPro.Saml2.Response(artifactResponse.Message);
                System.Diagnostics.Trace.WriteLine("AA reponse " + attrResponse.GetXml().OuterXml);

            }
            catch (Exception e)
            {
                System.Diagnostics.Trace.WriteLine("Execption: " + e.ToString());
                //throw;
            }
            // Get the originally requested resource URL from the relay state.
            string resourceUrl = (string)SamlSettings.CacheProvider.Remove(relayState);
            if (resourceUrl == null)
            {
                throw new ApplicationException("Invalid relay state");
            }

            // Create a login context for the asserted identity.
            FormsAuthentication.SetAuthCookie(userName, false);
            

            // Redirect to the originally requested resource URL.
            page.Response.Redirect(resourceUrl, false);
        }