/// <summary>
        /// Subject of the assertion is the bearer of the assertion
        /// </summary>
        /// <param name="notBefore">A time instant before which the subject cannot be confirmed.</param>
        /// <param name="notOnAfter">A time instant at which the subject can no longer be confirmed.</param>
        /// <param name="recipient">URI specifying the entity or location to which an attesting entity can present the assertion.</param>
        /// <param name="inResponseTo">The ID of a SAML protocol message in response to which an attesting entity can present the assertion.</param>
        /// <returns></returns>
        public SubjectBuilder AddSubjectConfirmationBearer(DateTime?notBefore, DateTime?notOnAfter, string recipient = null, string inResponseTo = null)
        {
            var data = new SubjectConfirmationDataType
            {
                InResponseTo = inResponseTo,
                Recipient    = recipient
            };

            if (notBefore != null)
            {
                data.NotBefore          = notBefore.Value;
                data.NotBeforeSpecified = true;
            }

            if (notOnAfter != null)
            {
                data.NotOnOrAfter          = notOnAfter.Value;
                data.NotOnOrAfterSpecified = true;
            }

            var subjectConfirmation = new SubjectConfirmationType
            {
                Method = Constants.ConfirmationMethodIdentifiers.Bearer,
                SubjectConfirmationData = data
            };

            AddSubjectConfirmation(subjectConfirmation);
            return(this);
        }
Ejemplo n.º 2
0
        private static void ValidateSubjectConfirmation(SubjectConfirmationType subjectConfirmation, ServiceProviderModel serviceProvider)
        {
            if (subjectConfirmation == null)
            {
                throw new ArgumentNullException(nameof(subjectConfirmation));
            }

            if (subjectConfirmation.Method == Saml2Constants.SubjectConfirmationMethods.HolderOfKey)
            {
                ValidateKeyInfo(subjectConfirmation.SubjectConfirmationData, serviceProvider);
            }
        }
        /// <summary>
        /// The SAML issuer uses its certificate to produce a holder-of-key SAML assertion.
        /// The relying party consumes the assertion, confirming the attesting entity by comparing the X.509 data in the assertion with the X.509 data in its possession.
        /// </summary>
        /// <param name="certificate"></param>
        /// <returns></returns>
        public SubjectBuilder AddSubjectConfirmationHolderOfKey(X509Certificate2 certificate)
        {
            var subjectConfirmation = new SubjectConfirmationType
            {
                Method = Constants.ConfirmationMethodIdentifiers.HolderOfKey,
                SubjectConfirmationData = new KeyInfoConfirmationDataType
                {
                    KeyInfo = KeyInfoBuilder.Build(certificate)
                }
            };

            AddSubjectConfirmation(subjectConfirmation);
            return(this);
        }
Ejemplo n.º 4
0
    private void CreateSAMLResponse()
    {
        FormsIdentity id = null;

        if (HttpContext.Current.User != null)
        {
            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                if (HttpContext.Current.User.Identity is FormsIdentity)
                {
                    id = (FormsIdentity)HttpContext.Current.User.Identity;
                }
            }
        }

        DateTime notBefore    = (id != null ? id.Ticket.IssueDate.ToUniversalTime() : DateTime.UtcNow);
        DateTime notOnOrAfter = (id != null ? id.Ticket.Expiration.ToUniversalTime() : DateTime.UtcNow.AddMinutes(30));

        IDProvider config = IDProvider.GetConfig();

        SAMLResponse.Status                  = new StatusType();
        SAMLResponse.Status.StatusCode       = new StatusCodeType();
        SAMLResponse.Status.StatusCode.Value = SAMLUtility.StatusCodes.Success;

        AssertionType assert = new AssertionType();

        assert.ID           = SAMLUtility.GenerateID();
        assert.IssueInstant = DateTime.UtcNow.AddMinutes(10);

        assert.Issuer       = new NameIDType();
        assert.Issuer.Value = config.id;

        SubjectConfirmationType subjectConfirmation = new SubjectConfirmationType();

        subjectConfirmation.Method = "urn:oasis:names:tc:SAML:2.0:cm:bearer";
        subjectConfirmation.SubjectConfirmationData              = new SubjectConfirmationDataType();
        subjectConfirmation.SubjectConfirmationData.Recipient    = SAMLRequest.Issuer;
        subjectConfirmation.SubjectConfirmationData.InResponseTo = SAMLRequest.Request.ID;
        subjectConfirmation.SubjectConfirmationData.NotOnOrAfter = notOnOrAfter;

        NameIDType nameID = new NameIDType();

        nameID.Format = SAMLUtility.NameIdentifierFormats.Transient;
        nameID.Value  = (id != null ? id.Name : UtilBO.FormatNameFormsAuthentication(this.__SessionWEB.__UsuarioWEB.Usuario));

        assert.Subject       = new SubjectType();
        assert.Subject.Items = new object[] { subjectConfirmation, nameID };

        assert.Conditions                       = new ConditionsType();
        assert.Conditions.NotBefore             = notBefore;
        assert.Conditions.NotOnOrAfter          = notOnOrAfter;
        assert.Conditions.NotBeforeSpecified    = true;
        assert.Conditions.NotOnOrAfterSpecified = true;

        AudienceRestrictionType audienceRestriction = new AudienceRestrictionType();

        audienceRestriction.Audience = new string[] { SAMLRequest.Issuer };
        assert.Conditions.Items      = new ConditionAbstractType[] { audienceRestriction };

        AuthnStatementType authnStatement = new AuthnStatementType();

        authnStatement.AuthnInstant = DateTime.UtcNow;
        authnStatement.SessionIndex = SAMLUtility.GenerateID();

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

        authnStatement.AuthnContext.ItemsElementName =
            new ItemsChoiceType5[] { ItemsChoiceType5.AuthnContextClassRef };

        StatementAbstractType[] statementAbstract = new StatementAbstractType[] { authnStatement };
        assert.Items       = statementAbstract;
        SAMLResponse.Items = new object[] { assert };

        string xmlResponse = SAMLUtility.SerializeToXmlString(SAMLResponse);

        XmlDocument doc = new XmlDocument();

        doc.LoadXml(xmlResponse);
        XmlSignatureUtils.SignDocument(doc, assert.ID);
        SAMLResponse = SAMLUtility.DeserializeFromXmlString <ResponseType>(doc.InnerXml);

        HttpPostBinding binding = new HttpPostBinding(SAMLResponse, HttpUtility.UrlDecode(Request[HttpBindingConstants.RelayState]));

        binding.SendResponse(this.Context, HttpUtility.UrlDecode(SAMLRequest.AssertionConsumerServiceURL), SAMLTypeSSO.signon);
    }
Ejemplo n.º 5
0
        /// <summary>
        /// Creates a Version 1.1 Saml Assertion
        /// </summary>
        /// <param name="issuer">Issuer</param>
        /// <param name="subject">Subject</param>
        /// <param name="attributes">Attributes</param>
        /// <returns>returns a Version 1.1 Saml Assertion</returns>
        private static AssertionType CreateSamlAssertion(string issuer, string recipient, string domain, string subject, Dictionary <string, string> attributes)
        {
            // Here we create some SAML assertion with ID and Issuer name.
            AssertionType assertion = new AssertionType();

            assertion.ID = "_" + Guid.NewGuid().ToString();

            NameIDType issuerForAssertion = new NameIDType();

            issuerForAssertion.Value = issuer.Trim();

            assertion.Issuer  = issuerForAssertion;
            assertion.Version = "2.0";

            assertion.IssueInstant = System.DateTime.UtcNow;

            //Not before, not after conditions
            ConditionsType conditions = new ConditionsType();

            conditions.NotBefore             = DateTime.UtcNow;
            conditions.NotBeforeSpecified    = true;
            conditions.NotOnOrAfter          = DateTime.UtcNow.AddMinutes(5);
            conditions.NotOnOrAfterSpecified = true;

            AudienceRestrictionType audienceRestriction = new AudienceRestrictionType();

            audienceRestriction.Audience = new string[] { domain.Trim() };

            conditions.Items = new ConditionAbstractType[] { audienceRestriction };

            //Name Identifier to be used in Saml Subject
            NameIDType nameIdentifier = new NameIDType();

            nameIdentifier.NameQualifier = domain.Trim();
            nameIdentifier.Value         = subject.Trim();

            SubjectConfirmationType     subjectConfirmation     = new SubjectConfirmationType();
            SubjectConfirmationDataType subjectConfirmationData = new SubjectConfirmationDataType();

            subjectConfirmation.Method = "urn:oasis:names:tc:SAML:2.0:cm:bearer";
            subjectConfirmation.SubjectConfirmationData = subjectConfirmationData;
            //
            // Create some SAML subject.
            SubjectType samlSubject = new SubjectType();

            AttributeStatementType attrStatement = new AttributeStatementType();
            AuthnStatementType     authStatement = new AuthnStatementType();

            authStatement.AuthnInstant = DateTime.UtcNow;
            AuthnContextType context = new AuthnContextType();

            context.ItemsElementName   = new ItemsChoiceType5[] { ItemsChoiceType5.AuthnContextClassRef };
            context.Items              = new object[] { "AuthnContextClassRef" };
            authStatement.AuthnContext = context;

            samlSubject.Items = new object[] { nameIdentifier, subjectConfirmation };

            assertion.Subject = samlSubject;

            IPHostEntry ipEntry =
                Dns.GetHostEntry(System.Environment.MachineName);

            SubjectLocalityType subjectLocality = new SubjectLocalityType();

            subjectLocality.Address = ipEntry.AddressList[0].ToString();

            attrStatement.Items = new AttributeType[attributes.Count];
            int i = 0;

            // Create userName SAML attributes.
            foreach (KeyValuePair <string, string> attribute in attributes)
            {
                AttributeType attr = new AttributeType();
                attr.Name              = attribute.Key;
                attr.NameFormat        = "urn:oasis:names:tc:SAML:2.0:attrname-format:basic";
                attr.AttributeValue    = new object[] { attribute.Value };
                attrStatement.Items[i] = attr;
                i++;
            }
            assertion.Conditions = conditions;

            assertion.Items = new StatementAbstractType[] { authStatement, attrStatement };

            return(assertion);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Creates a SAML 2.0 Assertion Segment for a Response
        /// Simple implmenetation assuming a list of string key and value pairs
        /// </summary>
        /// <param name="Issuer"></param>
        /// <param name="AssertionExpirationMinutes"></param>
        /// <param name="Audience"></param>
        /// <param name="Subject"></param>
        /// <param name="Recipient"></param>
        /// <param name="Attributes">Dictionary of string key, string value pairs</param>
        /// <returns>Assertion to sign and include in Response</returns>
        private static AssertionType CreateSAML20Assertion(string Issuer,
                                                           int AssertionExpirationMinutes,
                                                           string Audience,
                                                           string Subject,
                                                           string Recipient,
                                                           Dictionary <string, string> Attributes)
        {
            AssertionType NewAssertion = new AssertionType()
            {
                Version      = "2.0",
                IssueInstant = DateTime.Now,//DateTime.UtcNow,
                ID           = "_" + System.Guid.NewGuid().ToString()
            };

            // Create Issuer
            NewAssertion.Issuer = new NameIDType()
            {
                Value = Issuer.Trim()
            };

            // Create Assertion Subject
            SubjectType subject = new SubjectType();
            NameIDType  subjectNameIdentifier = new NameIDType()
            {
                Value = Subject.Trim(), Format = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"
            };
            SubjectConfirmationType subjectConfirmation = new SubjectConfirmationType()
            {
                Method = "urn:oasis:names:tc:SAML:2.0:cm:bearer", SubjectConfirmationData = new SubjectConfirmationDataType()
                {
                    NotOnOrAfter = DateTime.Now.AddMinutes(AssertionExpirationMinutes), Recipient = Recipient
                }
            };                                                                                                                                                                                                                                                                                           //{ NotOnOrAfter = DateTime.UtcNow.AddMinutes(AssertionExpirationMinutes), Recipient = Recipient } };

            subject.Items        = new object[] { subjectNameIdentifier, subjectConfirmation };
            NewAssertion.Subject = subject;

            // Create Assertion Conditions
            ConditionsType conditions = new ConditionsType();

            conditions.NotBefore             = DateTime.Now;                                        //DateTime.UtcNow;
            conditions.NotBeforeSpecified    = true;
            conditions.NotOnOrAfter          = DateTime.Now.AddMinutes(AssertionExpirationMinutes); //DateTime.UtcNow.AddMinutes(AssertionExpirationMinutes);
            conditions.NotOnOrAfterSpecified = true;
            conditions.Items = new ConditionAbstractType[] { new AudienceRestrictionType()
                                                             {
                                                                 Audience = new string[] { Audience.Trim() }
                                                             } };
            NewAssertion.Conditions = conditions;

            // Add AuthnStatement and Attributes as Items
            AuthnStatementType authStatement = new AuthnStatementType()
            {
                AuthnInstant = DateTime.Now, SessionIndex = NewAssertion.ID
            };                                                                                                                           //{ AuthnInstant = DateTime.UtcNow, SessionIndex = NewAssertion.ID };
            AuthnContextType context = new AuthnContextType();

            context.ItemsElementName   = new ItemsChoiceType5[] { ItemsChoiceType5.AuthnContextClassRef };
            context.Items              = new object[] { "urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified" };
            authStatement.AuthnContext = context;

            AttributeStatementType attributeStatement = new AttributeStatementType();

            attributeStatement.Items = new AttributeType[Attributes.Count];
            int i = 0;

            foreach (KeyValuePair <string, string> attribute in Attributes)
            {
                attributeStatement.Items[i] = new AttributeType()
                {
                    Name           = attribute.Key,
                    AttributeValue = new object[] { attribute.Value },
                    NameFormat     = "urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
                };
                i++;
            }

            NewAssertion.Items = new StatementAbstractType[] { authStatement, attributeStatement };

            return(NewAssertion);
        }
Ejemplo n.º 7
0
        private static AssertionType CreateSamlAssertion(AuthnRequestType samlAuthRequest, string username)
        {
            var assertion = new AssertionType
            {
                Version      = "2.0",
                IssueInstant = DateTime.UtcNow,
                ID           = "_" + Guid.NewGuid(),
                Issuer       = new NameIDType()
                {
                    Value = $"{_context.Request.Scheme}://{_context.Request.Host}{_context.Request.PathBase}"
                }
            };

            //Assertion Subject
            var subject = new SubjectType();
            var subjectNameIdentifier = new NameIDType()
            {
                Value = username, Format = Saml2Constants.NameIdentifierFormats.Unspecified
            };
            var subjectConfirmation = new SubjectConfirmationType()
            {
                Method = Saml2Constants.SubjectConfirmationMethods.HolderOfKey,
                SubjectConfirmationData = new SubjectConfirmationDataType()
                {
                    NotOnOrAfter = DateTime.UtcNow.AddMinutes(ASSERTION_TIMEOUT_IN_MINUTES),
                    Recipient    = samlAuthRequest.AssertionConsumerServiceURL,
                    InResponseTo = samlAuthRequest.ID
                }
            };

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

            //Assertion Conditions
            var conditions = new ConditionsType
            {
                NotBefore             = DateTime.UtcNow,
                NotBeforeSpecified    = true,
                NotOnOrAfter          = DateTime.UtcNow.AddMinutes(ASSERTION_TIMEOUT_IN_MINUTES),
                NotOnOrAfterSpecified = true,
                //TODO: samlAuthRequest.Issuer.Value should be replaced with
                Items = new ConditionAbstractType[] { new AudienceRestrictionType()
                                                      {
                                                          Audience = new string[] { samlAuthRequest.Issuer.Value }
                                                      } }
            };

            assertion.Conditions = conditions;

            //Assertion AuthnStatement
            var authStatement = new AuthnStatementType()
            {
                AuthnInstant = DateTime.UtcNow, SessionIndex = assertion.ID
            };
            var context = new AuthnContextType();

            context.ItemsElementName   = new[] { ItemsChoiceType5.AuthnContextClassRef };
            context.Items              = new object[] { "urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified" };
            authStatement.AuthnContext = context;

            //Assertion AttributeStatement
            var attributeStatement = new AttributeStatementType();

            attributeStatement.Items = new AttributeType[]
            {
                //Add as many attributes as you want here, these are the user details that service provider wants, we can customise the attributes required
                // on the basis of service provider that requires this assertion
                new AttributeType {
                    Name = "username", AttributeValue = username, NameFormat = "urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
                }
            };
            assertion.Items = new StatementAbstractType[] { authStatement, attributeStatement };

            return(assertion);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Creates a SAML 2.0 Assertion Segment for a Response
        /// Simple implmenetation assuming a list of string key and value pairs
        /// </summary>
        /// <param name="issuer"></param>
        /// <param name="assertionExpirationMinutes"></param>
        /// <param name="audience"></param>
        /// <param name="subject"></param>
        /// <param name="recipient"></param>
        /// <param name="attributes">Dictionary of string key, string value pairs</param>
        /// <returns>Assertion to sign and include in Response</returns>
        private static AssertionType CreateSaml20Assertion(string issuer,
                                                           int assertionExpirationMinutes,
                                                           string audience,
                                                           string subject,
                                                           string recipient,
                                                           Dictionary <string, string> attributes)
        {
            AssertionType newAssertion = new AssertionType
            {
                Version      = "2.0",
                IssueInstant = DateTime.UtcNow,
                ID           = "_" + Guid.NewGuid(),
                Issuer       = new NameIDType {
                    Value = issuer.Trim()
                }
            };

            // Create Issuer

            // Create Assertion Subject
            SubjectType subjectType           = new SubjectType();
            NameIDType  subjectNameIdentifier = new NameIDType {
                Value = subject.Trim(), Format = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"
            };
            SubjectConfirmationType subjectConfirmation = new SubjectConfirmationType {
                Method = "urn:oasis:names:tc:SAML:2.0:cm:bearer", SubjectConfirmationData = new SubjectConfirmationDataType {
                    NotOnOrAfter = DateTime.UtcNow.AddMinutes(assertionExpirationMinutes), Recipient = recipient
                }
            };

            subjectType.Items    = new object[] { subjectNameIdentifier, subjectConfirmation };
            newAssertion.Subject = subjectType;

            // Create Assertion Conditions
            ConditionsType conditions = new ConditionsType
            {
                NotBefore             = DateTime.UtcNow,
                NotBeforeSpecified    = true,
                NotOnOrAfter          = DateTime.UtcNow.AddMinutes(assertionExpirationMinutes),
                NotOnOrAfterSpecified = true,
                Items = new ConditionAbstractType[] { new AudienceRestrictionType {
                                                          Audience = new[] { audience.Trim() }
                                                      } }
            };

            newAssertion.Conditions = conditions;

            // Add AuthnStatement and Attributes as Items
            AuthnStatementType authStatement = new AuthnStatementType {
                AuthnInstant = DateTime.UtcNow, SessionIndex = newAssertion.ID
            };
            AuthnContextType context = new AuthnContextType
            {
                ItemsElementName = new[] { ItemsChoiceType5.AuthnContextClassRef },
                Items            = new object[] { "urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified" }
            };

            authStatement.AuthnContext = context;

            AttributeStatementType attributeStatement = new AttributeStatementType
            {
                Items = new object[attributes.Count]
            };
            int i = 0;

            foreach (KeyValuePair <string, string> attribute in attributes)
            {
                attributeStatement.Items[i] = new AttributeType
                {
                    Name           = attribute.Key,
                    AttributeValue = new object[] { attribute.Value },
                    NameFormat     = "urn:oasis:names:tc:SAML:2.0:attrname-format:basic"
                };
                i++;
            }

            newAssertion.Items = new StatementAbstractType[] { authStatement, attributeStatement };

            return(newAssertion);
        }
Ejemplo n.º 9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private XmlDocument GenerateResponseMetadata(SAMLContext context, string id)
        {
            DateTime      now    = DateTime.UtcNow;
            MemoryStream  stream = new MemoryStream();
            StreamReader  reader;
            XmlTextReader xmlReader;

            ResponseType response = new ResponseType();

            response.ID           = id;
            response.InResponseTo = context.RequestID;
            response.Version      = SAMLConstants.SAML_VERSION;
            response.IssueInstant = now;

            response.Destination   = context.AssertionConsumer;
            response.Consent       = SAMLConstants.CONSENT;
            response.Issuer        = new NameIDType();
            response.Issuer.Value  = thisIssuer;
            response.Issuer.Format = SAMLConstants.ThisIssuerFormat;

            response.Status                  = new StatusType();
            response.Status.StatusCode       = new StatusCodeType();
            response.Status.StatusCode.Value = SAMLConstants.StatusCode.statusCode[context.StatusCode];
            if (context.StatusCode != SAMLConstants.StatusCode.SUCCESS)
            {
                response.Status.StatusCode.StatusCode       = new StatusCodeType();
                response.Status.StatusCode.StatusCode.Value =
                    SAMLConstants.StatusCode.statusCode[context.SubStatusCode];
                response.Status.StatusMessage = context.StatusMessage;
            }

            AssertionType assertion = new AssertionType();

            assertion.ID           = "_" + Guid.NewGuid().ToString();
            assertion.Version      = SAMLConstants.SAML_VERSION;
            assertion.IssueInstant = now;

            assertion.Issuer        = new NameIDType();
            assertion.Issuer.Value  = thisIssuer;
            assertion.Issuer.Format = SAMLConstants.ThisIssuerFormat;

            assertion.Subject = new SubjectType();
            NameIDType nameId = new NameIDType();

            nameId.Format = "urn:oasis:names:tc:SAML:1.1:nameid- format:unspecified";
            //nameId.NameQualifier = "http://C-PEPS.gov.xx";
            nameId.Value = "urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified";

            SubjectConfirmationType subjectConfirmation = new SubjectConfirmationType();

            subjectConfirmation.Method = "urn:oasis:names:tc:SAML:2.0:cm:bearer";
            subjectConfirmation.SubjectConfirmationData              = new SubjectConfirmationDataType();
            subjectConfirmation.SubjectConfirmationData.Address      = context.SubjectAddress;
            subjectConfirmation.SubjectConfirmationData.InResponseTo = context.RequestID;
            //subjectConfirmation.SubjectConfirmationData.NotBeforeString = "2010-02-03T17:06:18.099Z";
            subjectConfirmation.SubjectConfirmationData.NotOnOrAfterString =
                String.Format("{0:yyyy-MM-ddTHH:mm:ssZ}", now.AddMinutes(validTimeframe));
            subjectConfirmation.SubjectConfirmationData.Recipient = context.Issuer;
            assertion.Subject.Items = new object[] { nameId, subjectConfirmation };

            assertion.Conditions = new ConditionsType();
            assertion.Conditions.NotBeforeString    = String.Format("{0:yyyy-MM-ddTHH:mm:ssZ}", now);
            assertion.Conditions.NotOnOrAfterString =
                String.Format("{0:yyyy-MM-ddTHH:mm:ssZ}", now.AddMinutes(validTimeframe));

            AudienceRestrictionType audience = new AudienceRestrictionType();

            audience.Audience          = new string[] { context.Issuer }; // FIXME
            assertion.Conditions.Items = new ConditionAbstractType[] { audience, new OneTimeUseType() };

            AuthnStatementType authnStatement = new AuthnStatementType();

            authnStatement.AuthnInstant = now;
            authnStatement.AuthnContext = new AuthnContextType();

            List <AttributeElement> attributes = context.GetAttributes();

            object[]      attributesDescription = new AttributeType[attributes.Count];
            AttributeType attr;
            XmlAttribute  statusAttr;
            int           i = 0;

            foreach (AttributeElement element in attributes)
            {
                attr            = new AttributeType();
                attr.Name       = element.AttrName;
                attr.NameFormat = element.NameFormat;
                if (context.StatusCode == SAMLConstants.StatusCode.SUCCESS)
                {
                    if (element.AttrStatus == SAMLConstants.AttributeStatus.AVAILABLE &&
                        element.AttrValue != null)
                    {
                        attr.AttributeValue = new object[] { element.AttrValue }
                    }
                    ;
                    if (element.AttrStatus >= 0)
                    {
                        statusAttr = new XmlDocument().
                                     CreateAttribute(SAMLConstants.ATTRIBUTE_STATUS_STR, SAMLConstants.NS_STORK_ASSER);
                        statusAttr.Value = element.Status;
                        attr.AnyAttr     = new XmlAttribute[] { statusAttr };
                    }
                }
                attributesDescription[i++] = attr;
            }

            AttributeStatementType attributeStatement = new AttributeStatementType();

            attributeStatement.Items = attributesDescription;
            assertion.Items          = new StatementAbstractType[] { authnStatement, attributeStatement };
            response.Items           = new object[] { assertion };

            stream = new MemoryStream();
            Serialize(response, stream);

            reader = new StreamReader(stream);
            stream.Seek(0, SeekOrigin.Begin);
            xmlReader = new XmlTextReader(new StringReader(reader.ReadToEnd()));
            return(Deserialize <XmlDocument>(xmlReader));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Creates a Version 1.1 Saml Assertion
        /// </summary>
        /// <param name="issuer">Issuer</param>
        /// <param name="subject">Subject</param>
        /// <param name="attributes">Attributes</param>
        /// <returns>returns a Version 1.1 Saml Assertoion</returns>
        private static AssertionType CreateSaml11Assertion(string issuer, string domain, string subject, Dictionary <string, string> attributes)
        {
            // Create some SAML assertion with ID and Issuer name.
            AssertionType assertion = new AssertionType();

            assertion.AssertionID  = "_" + Guid.NewGuid().ToString();
            assertion.Issuer       = issuer.Trim();
            assertion.MajorVersion = "1";
            assertion.MinorVersion = "1";
            assertion.IssueInstant = System.DateTime.UtcNow;

            //Not before, not after conditions
            ConditionsType conditions = new ConditionsType();

            conditions.NotBefore             = DateTime.UtcNow;
            conditions.NotBeforeSpecified    = true;
            conditions.NotOnOrAfter          = DateTime.UtcNow.AddMinutes(10);
            conditions.NotOnOrAfterSpecified = true;
            //Name Identifier to be used in Saml Subject
            NameIdentifierType nameIdentifier = new NameIdentifierType();

            nameIdentifier.NameQualifier = domain.Trim();
            nameIdentifier.Value         = subject.Trim();

            SubjectConfirmationType subjectConfirmation = new SubjectConfirmationType();

            subjectConfirmation.ConfirmationMethod = new string[] { "urn:oasis:names:tc:SAML:1.0:cm:bearer" };
            //
            // Create some SAML subject.
            SubjectType samlSubject = new SubjectType();

            AttributeStatementType      attrStatement = new AttributeStatementType();
            AuthenticationStatementType authStatement = new AuthenticationStatementType();

            authStatement.AuthenticationMethod  = "urn:oasis:names:tc:SAML:1.0:am:password";
            authStatement.AuthenticationInstant = System.DateTime.UtcNow;

            samlSubject.Items = new object[] { nameIdentifier, subjectConfirmation };

            attrStatement.Subject = samlSubject;
            authStatement.Subject = samlSubject;

            IPHostEntry ipEntry =
                Dns.GetHostEntry(System.Environment.MachineName);

            SubjectLocalityType subjectLocality = new SubjectLocalityType();

            subjectLocality.IPAddress = ipEntry.AddressList[0].ToString();

            authStatement.SubjectLocality = subjectLocality;

            attrStatement.Attribute = new AttributeType[attributes.Count];
            int i = 0;

            // Create userName SAML attributes.
            foreach (KeyValuePair <string, string> attribute in attributes)
            {
                AttributeType attr = new AttributeType();
                attr.AttributeName         = attribute.Key;
                attr.AttributeNamespace    = domain;
                attr.AttributeValue        = new object[] { attribute.Value };
                attrStatement.Attribute[i] = attr;
                i++;
            }
            assertion.Conditions = conditions;

            assertion.Items = new StatementAbstractType[] { authStatement, attrStatement };

            return(assertion);
        }