Example #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;
        }
Example #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;
        }
Example #3
0
            public void ValidatesSubjectConfirmationDataTimeIntervalSettings()
            {
                // TODO: Split this up
                // Arrange
                var validator = new Saml20SubjectConfirmationDataValidator();

                var subjectConfirmationData = new SubjectConfirmationData();

                subjectConfirmationData.NotBefore    = new DateTime(2008, 01, 30, 17, 13, 0, 500, DateTimeKind.Utc);
                subjectConfirmationData.NotOnOrAfter = subjectConfirmationData.NotBefore.Value.AddHours(1);

                validator.ValidateSubjectConfirmationData(subjectConfirmationData);

                subjectConfirmationData.NotBefore = null;
                validator.ValidateSubjectConfirmationData(subjectConfirmationData);

                // DateTime validation wrt DateTime.UtcNow is NOT done by the validators
                // so a future-NotBefore must be valid
                subjectConfirmationData.NotBefore    = subjectConfirmationData.NotOnOrAfter;
                subjectConfirmationData.NotOnOrAfter = null;
                validator.ValidateSubjectConfirmationData(subjectConfirmationData);

                subjectConfirmationData.NotBefore = null;

                // Act
                validator.ValidateSubjectConfirmationData(subjectConfirmationData);
            }
        /// <summary>
        /// [SAML2.0std] section 2.4.1.2
        /// </summary>
        /// <param name="subjectConfirmationData"></param>
        public void ValidateSubjectConfirmationData(SubjectConfirmationData subjectConfirmationData)
        {
            // If present it must be anyUri
            if (subjectConfirmationData.Recipient != null)
            {
                if (!Uri.IsWellFormedUriString(subjectConfirmationData.Recipient, UriKind.Absolute))
                {
                    throw new Saml2FormatException("Recipient of SubjectConfirmationData must be a wellformed absolute URI.");
                }
            }

            // NotBefore MUST BE striclty less than NotOnOrAfter if they are both set
            if (subjectConfirmationData.NotBefore != null && subjectConfirmationData.NotBefore.HasValue &&
                subjectConfirmationData.NotOnOrAfter != null && subjectConfirmationData.NotOnOrAfter.HasValue)
            {
                if (!(subjectConfirmationData.NotBefore < subjectConfirmationData.NotOnOrAfter))
                {
                    throw new Saml2FormatException(String.Format("NotBefore {0} MUST BE less than NotOnOrAfter {1} on SubjectConfirmationData", Saml2Utils.ToUTCString(subjectConfirmationData.NotBefore.Value), Saml2Utils.ToUTCString(subjectConfirmationData.NotOnOrAfter.Value)));
                }
            }

            // Make sure the extension-attributes are namespace-qualified and do not use reserved namespaces
            if (subjectConfirmationData.AnyAttr != null)
            {
                _anyAttrValidator.ValidateXmlAnyAttributes(subjectConfirmationData.AnyAttr);
            }

            // Standards-defined extension type which has stricter rules than it's base type
            if (subjectConfirmationData is KeyInfoConfirmationData)
            {
                _keyInfoValidator.ValidateKeyInfo(subjectConfirmationData);
            }
        }
Example #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);
        }
            public void ThrowsExceptionWhenSubjectConfirmationDataRecipientIsInvalid()
            {
                // Arrange
                var subjectConfirmationData = new SubjectConfirmationData {
                    Recipient = "malformed uri"
                };
                var validator = new Saml20SubjectConfirmationDataValidator();

                // Act
                validator.ValidateSubjectConfirmationData(subjectConfirmationData);
            }
Example #7
0
            public void ValidatesSubjectConfirmationDataRecipient()
            {
                // Arrange
                var subjectConfirmationData = new SubjectConfirmationData {
                    Recipient = "urn:wellformed.uri:ok"
                };
                var validator = new Saml20SubjectConfirmationDataValidator();

                // Act
                validator.ValidateSubjectConfirmationData(subjectConfirmationData);
            }
Example #8
0
 public override XElement ToXml()
 {
     return(new XElement(
                NA.saml + "SubjectConfirmation",
                new XElement(NA.saml + "ConfirmationMethod", SamlIDs.HolderOfKey), //specielt for DGWS
                //BaseID == null ? null : BaseID.ToXml(),
                NameID == null ? null : NameID.ToXml(),
                //EncryptedID == null ? null : EncryptedID.ToXml(),
                SubjectConfirmationData == null ? null : SubjectConfirmationData.ToXml()
                ));
 }
Example #9
0
            public void ThrowsExceptionWhenSubjectConfirmationDataRecipientIsInvalid()
            {
                // Arrange
                var subjectConfirmationData = new SubjectConfirmationData {
                    Recipient = "malformed uri"
                };
                var validator = new Saml20SubjectConfirmationDataValidator();

                // Act
                Assert.Throws <Saml20FormatException>(() => validator.ValidateSubjectConfirmationData(subjectConfirmationData),
                                                      "Recipient of SubjectConfirmationData must be a wellformed absolute URI.");
            }
        // 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);
        }
            public void ThrowsExceptionWhenSubjectConfirmationDataTimeIntervalIsInvalid()
            {
                // Arrange
                var subjectConfirmationData = new SubjectConfirmationData();

                subjectConfirmationData.NotBefore    = new DateTime(2008, 01, 30, 17, 13, 0, 500, DateTimeKind.Utc);
                subjectConfirmationData.NotOnOrAfter = subjectConfirmationData.NotBefore.Value.AddHours(-1);

                var validator = new Saml20SubjectConfirmationDataValidator();

                // Act
                validator.ValidateSubjectConfirmationData(subjectConfirmationData);
            }
Example #12
0
            //ExpectedMessage = "Recipient of SubjectConfirmationData must be a wellformed absolute URI.")]
            public void ThrowsExceptionWhenSubjectConfirmationDataRecipientIsEmpty()
            {
                // Arrange
                var subjectConfirmationData = new SubjectConfirmationData {
                    Recipient = " "
                };
                var validator = new Saml20SubjectConfirmationDataValidator();

                // Act
                Assert.Throws(typeof(Saml20FormatException), () => {
                    validator.ValidateSubjectConfirmationData(subjectConfirmationData);
                });
            }
Example #13
0
            public void ThrowsExceptionWhenSubjectConfirmationDataTimeIntervalIsInvalid()
            {
                // Arrange
                var subjectConfirmationData = new SubjectConfirmationData();

                subjectConfirmationData.NotBefore    = new DateTime(2008, 01, 30, 17, 13, 0, 500, DateTimeKind.Utc);
                subjectConfirmationData.NotOnOrAfter = subjectConfirmationData.NotBefore.Value.AddHours(-1);

                var validator = new Saml20SubjectConfirmationDataValidator();

                // Act
                Assert.Throws <Saml20FormatException>(() => validator.ValidateSubjectConfirmationData(subjectConfirmationData),
                                                      "NotBefore 2008-01-30T17:13:00.5Z MUST BE less than NotOnOrAfter 2008-01-30T16:13:00.5Z on SubjectConfirmationData");
            }
Example #14
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);
        }
Example #16
0
        public XElement Serialize()
        {
            var result = new XElement(Constants.XMLNamespaces.SAML + "SubjectConfirmation",
                                      new XElement(Constants.XMLNamespaces.SAML + "ConfirmationMethod", ConfirmationMethod));

            if (SubjectConfirmationData != null)
            {
                result.Add(SubjectConfirmationData.Serialize());
            }

            if (KeyInfo != null)
            {
                result.Add(KeyInfo.Serialize(false));
            }

            return(result);
        }
        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);
        }
        /// <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);
        }
Example #19
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);
        }
Example #20
0
        /// <summary>
        /// Validates the presence and correctness of a <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#"/> among the any-xml-elements of a SubjectConfirmationData
        /// </summary>
        /// <param name="subjectConfirmationData">The subject confirmation data.</param>
        public void ValidateKeyInfo(SubjectConfirmationData subjectConfirmationData)
        {
            if (subjectConfirmationData == null)
            {
                throw new Saml20FormatException("SubjectConfirmationData cannot be null when KeyInfo subelements are required");
            }

            if (subjectConfirmationData.AnyElements == null)
            {
                throw new Saml20FormatException(string.Format("SubjectConfirmationData element MUST have at least one {0} subelement", KeyInfo.ElementName));
            }

            var keyInfoFound = false;

            foreach (var element in subjectConfirmationData.AnyElements)
            {
                if (element.NamespaceURI != Saml20Constants.Xmldsig || element.LocalName != KeyInfo.ElementName)
                {
                    continue;
                }

                keyInfoFound = true;

                // A KeyInfo element MUST identify a cryptographic key
                if (!element.HasChildNodes)
                {
                    throw new Saml20FormatException(string.Format("{0} subelement of SubjectConfirmationData MUST NOT be empty", KeyInfo.ElementName));
                }
            }

            // There MUST BE at least one <ds:KeyInfo> element present (from the arbitrary elements list on SubjectConfirmationData
            if (!keyInfoFound)
            {
                throw new Saml20FormatException(string.Format("SubjectConfirmationData element MUST contain at least one {0} in namespace {1}", KeyInfo.ElementName, Saml20Constants.Xmldsig));
            }
        }
Example #21
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);
        }
Example #22
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);
        }
Example #23
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;
        }
        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
        }
Example #25
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);
        }
Example #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
        }
        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);
            }
        }