예제 #1
0
        static void Main(string[] args)
        {
            // Here we create some SAML assertion with ID and Issuer name.
            SamlAssertion assertion = new SamlAssertion();

            assertion.AssertionId = "AssertionID";
            assertion.Issuer      = "ISSUER";
            // Create some SAML subject.
            SamlSubject samlSubject = new SamlSubject();

            samlSubject.Name = "My Subject";

            //
            // Create one SAML attribute with few values.
            SamlAttribute attr = new SamlAttribute();

            attr.Namespace = "http://daenet.eu/saml";
            attr.AttributeValues.Add("Some Value 1");
            //attr.AttributeValues.Add("Some Value 2");

            attr.Name = "My ATTR Value";

            //
            // Now create the SAML statement containing one attribute and one subject.
            SamlAttributeStatement samlAttributeStatement = new SamlAttributeStatement();

            samlAttributeStatement.Attributes.Add(attr);
            samlAttributeStatement.SamlSubject = samlSubject;

            // Append the statement to the SAML assertion.
            assertion.Statements.Add(samlAttributeStatement);
        }
예제 #2
0
        SamlSecurityToken GetSamlToken()
        {
            SamlAssertion a = new SamlAssertion();

            SamlSubject subject = new SamlSubject(
                SamlConstants.UserNameNamespace,
                "urn:myqualifier",
                "myname");
            SamlAttribute          attr      = new SamlAttribute(Claim.CreateNameClaim("myname"));
            SamlAttributeStatement statement =
                new SamlAttributeStatement(subject, new SamlAttribute [] { attr });

            a.Statements.Add(statement);
            a.Issuer = "my_hero";

            X509Certificate2          cert = new X509Certificate2(TestResourceHelper.GetFullPathOfResource("Test/Resources/test.pfx"), "mono");
            X509AsymmetricSecurityKey key  =
                new X509AsymmetricSecurityKey(cert);

            a.SigningCredentials =
                new SigningCredentials(key,
                                       SecurityAlgorithms.HmacSha1Signature,
                                       SecurityAlgorithms.Sha256Digest);
            XmlDocument doc = new XmlDocument();
            XmlWriter   w   = doc.CreateNavigator().AppendChild();

            using (XmlDictionaryWriter dw = XmlDictionaryWriter.CreateDictionaryWriter(w)) {
                a.WriteXml(dw, new SamlSerializer(), new MySecurityTokenSerializer());
            }
            Console.Error.WriteLine(doc.OuterXml);
            return(new SamlSecurityToken(a));
        }
예제 #3
0
        /// <summary>
        /// [SAML2.0std] section 2.7.3.1
        /// </summary>
        public void ValidateAttribute(SamlAttribute samlAttribute)
        {
            if (samlAttribute == null)
            {
                throw new ArgumentNullException("samlAttribute");
            }

            if (!Saml20Utils.ValidateRequiredString(samlAttribute.Name))
            {
                throw new Saml20FormatException("Name attribute of Attribute element MUST contain at least one non-whitespace character");
            }

            if (samlAttribute.AttributeValue != null)
            {
                foreach (object o in samlAttribute.AttributeValue)
                {
                    if (o == null)
                    {
                        throw new Saml20FormatException("null-AttributeValue elements are not supported");
                    }
                }
            }

            if (samlAttribute.AnyAttr != null)
            {
                AnyAttrValidator.ValidateXmlAnyAttributes(samlAttribute.AnyAttr);
            }
        }
예제 #4
0
        public static SamlAssertion CreateSamlAssertionFromClaims(IEnumerable <Claim> claims)
        {
            var subject = new SamlSubject()
            {
                Name = "Windows Group Claim"
            };
            var statement = new SamlAttributeStatement()
            {
                SamlSubject = subject
            };
            var assertion = new SamlAssertion()
            {
                AssertionId = string.Format("_{0}", Guid.NewGuid().ToString()),
                Issuer      = "System"
            };

            foreach (var claim in claims)
            {
                var attribute = new SamlAttribute(claim);
                statement.Attributes.Add(attribute);
            }

            assertion.Statements.Add(statement);
            SignSamlAssertion(assertion);
            return(assertion);
        }
예제 #5
0
        public void WriteXmlValid()
        {
            SamlAssertion a       = new SamlAssertion();
            SamlSubject   subject = new SamlSubject(
                SamlConstants.UserNameNamespace,
                "urn:myqualifier",
                "myname");
            SamlAttribute          attr      = new SamlAttribute(Claim.CreateNameClaim("myname"));
            SamlAttributeStatement statement =
                new SamlAttributeStatement(subject, new SamlAttribute [] { attr });

            a.Advice = new SamlAdvice(new string [] { "urn:testadvice1" });
            DateTime notBefore  = DateTime.SpecifyKind(new DateTime(2000, 1, 1), DateTimeKind.Utc);
            DateTime notOnAfter = DateTime.SpecifyKind(new DateTime(2006, 1, 1), DateTimeKind.Utc);

            a.Conditions = new SamlConditions(notBefore, notOnAfter);
            a.Statements.Add(statement);
            a.Issuer = "my_hero";
            StringWriter sw      = new StringWriter();
            string       id      = a.AssertionId;
            DateTime     instant = a.IssueInstant;

            using (XmlDictionaryWriter dw = CreateWriter(sw)) {
                a.WriteXml(dw, new SamlSerializer(), null);
            }
            string expected = String.Format("<?xml version=\"1.0\" encoding=\"utf-16\"?><saml:Assertion MajorVersion=\"1\" MinorVersion=\"1\" AssertionID=\"{0}\" Issuer=\"my_hero\" IssueInstant=\"{1}\" xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\"><saml:Conditions NotBefore=\"{3}\" NotOnOrAfter=\"{4}\" /><saml:Advice><saml:AssertionIDReference>urn:testadvice1</saml:AssertionIDReference></saml:Advice><saml:AttributeStatement><saml:Subject><saml:NameIdentifier Format=\"urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName\" NameQualifier=\"urn:myqualifier\">myname</saml:NameIdentifier></saml:Subject><saml:Attribute AttributeName=\"name\" AttributeNamespace=\"{2}\"><saml:AttributeValue>myname</saml:AttributeValue></saml:Attribute></saml:AttributeStatement></saml:Assertion>",
                                            id,
                                            instant.ToString("yyyy-MM-ddTHH:mm:ss.fff'Z'", CultureInfo.InvariantCulture),
                                            "http://schemas.xmlsoap.org/ws/2005/05/identity/claims",
                                            notBefore.ToString("yyyy-MM-ddTHH:mm:ss.fff'Z'", CultureInfo.InvariantCulture),
                                            notOnAfter.ToString("yyyy-MM-ddTHH:mm:ss.fff'Z'", CultureInfo.InvariantCulture));

            Assert.AreEqual(expected, sw.ToString());
        }
예제 #6
0
        public static SamlAssertion CreateSamlAssertionFromUserNameClaims(IEnumerable <Claim> claims)
        {
            var subject = new SamlSubject()
            {
                Name = "Windows Group Claim"
            };
            var statement = new SamlAttributeStatement()
            {
                SamlSubject = subject
            };
            var assertion = new SamlAssertion()
            {
                AssertionId = string.Format("_{0}", Guid.NewGuid().ToString()),
                Issuer      = "System"
            };

            foreach (var claim in claims)
            {
                var samlClaim = new Claim(claim.ClaimType, GetResourceFromSid(claim.Resource as SecurityIdentifier), claim.Right);
                var attribute = new SamlAttribute(samlClaim);
                statement.Attributes.Add(attribute);
            }

            assertion.Statements.Add(statement);
            SignSamlAssertion(assertion);
            return(assertion);
        }
        private static void Serialize(SamlAttribute samlAttribute, XmlDocument document, XmlNode root)
        {
            if (samlAttribute == null)
            {
                throw new ArgumentNullException(nameof(samlAttribute));
            }

            if (document == null)
            {
                throw new ArgumentNullException(nameof(document));
            }

            if (root == null)
            {
                throw new ArgumentNullException(nameof(root));
            }

            var samlAttributeNode = document.CreateElement(Constants.XmlPrefixes.Saml, Constants.XmlRootNames.SamlAttribute, Constants.XmlNamespaces.Saml);

            samlAttributeNode.SetAttribute(Constants.XmlAttributeNames.SamlAttributeName, samlAttribute.Name);
            samlAttributeNode.SetAttribute(Constants.XmlAttributeNames.SamlAttributeNamespace, samlAttribute.Namespace);
            var samlAttributeValueNode = document.CreateElement(Constants.XmlPrefixes.Saml, Constants.XmlRootNames.SamlAttributeValue, Constants.XmlNamespaces.Saml);

            samlAttributeValueNode.InnerText = samlAttribute.Value;
            samlAttributeNode.AppendChild(samlAttributeValueNode);
            root.AppendChild(samlAttributeNode);
        }
예제 #8
0
파일: source.cs 프로젝트: winxxp/samples
        private void ProcessSamlSecurityToken()
        {
            string proofToken              = "1";
            string issuerToken             = "2";
            string samlConditions          = "3";
            string samlSubjectNameFormat   = "4";
            string samlSubjectEmailAddress = "5";

            //<snippet5>
            // Create the list of SAML Attributes.
            List <SamlAttribute> samlAttributes = new List <SamlAttribute>();
            // Add the userAuthenticated claim.
            List <string> strList = new List <string>();

            strList.Add("true");
            SamlAttribute mySamlAttribute = new SamlAttribute("http://www.tmpuri.org",
                                                              "userAuthenticated", strList);

            samlAttributes.Add(mySamlAttribute);
            // Create the SAML token with the userAuthenticated claim. It is assumed that
            // the method CreateSamlToken() is implemented as part of STS-A.
            SamlSecurityToken samlToken = CreateSamlToken(
                proofToken,
                issuerToken,
                samlConditions,
                samlSubjectNameFormat,
                samlSubjectEmailAddress,
                samlAttributes);
            //</snippet5>
        }
예제 #9
0
 public static IEnumerable <Claim> ToClaims(this SamlAttribute value, string issuer)
 {
     if (value == null)
     {
         throw new ArgumentNullException("value");
     }
     return(value.AttributeValue.Select(v => new Claim(value.Name, v, value.NameFormat, issuer)));
 }
예제 #10
0
        //</snippet7>



        private void CreateClaim()
        {
            //<snippet8>
            Claim myClaim = new Claim(
                ClaimTypes.GivenName, "Martin", Rights.PossessProperty);
            SamlAttribute sa = new SamlAttribute(myClaim);
            //</snippet8>
        }
예제 #11
0
 public static Claim ToClaim(this SamlAttribute value, string issuer)
 {
     if (value == null)
     {
         throw new ArgumentNullException("value");
     }
     // TODO: Find the right answer to the multiple attributevalue question
     return(new Claim(value.Name, string.Join(",", value.AttributeValue), value.NameFormat, issuer));
 }
예제 #12
0
        /// <summary>
        /// Creates a SamlAttribute with the specified name.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="friendlyName">Friendly name.</param>
        /// <param name="value">The attribute value.</param>
        /// <returns></returns>
        protected static SamlAttribute Create(string name, string friendlyName, string value)
        {
            SamlAttribute att = new SamlAttribute();

            att.NameFormat     = SamlAttribute.NAMEFORMAT_URI;
            att.Name           = name;
            att.FriendlyName   = friendlyName;
            att.AttributeValue = new string[] { value };
            return(att);
        }
        private void GenerateMetadataDocument(HttpContext context)
        {
            EntityDescriptor metadata = new EntityDescriptor();

            metadata.entityID = IDPConfig.ServerBaseUrl;
            metadata.ID       = "id" + Guid.NewGuid().ToString("N");

            IDPSSODescriptor descriptor = new IDPSSODescriptor();

            metadata.Items = new object[] { descriptor };
            descriptor.protocolSupportEnumeration = new string[] { Saml20Constants.PROTOCOL };
            descriptor.KeyDescriptor = CreateKeyDescriptors();

            { // Signon endpoint
                Endpoint endpoint = new Endpoint();
                endpoint.Location = IDPConfig.ServerBaseUrl + "Signon.ashx";
                endpoint.Binding  = Saml20Constants.ProtocolBindings.HTTP_Redirect;
                descriptor.SingleSignOnService = new Endpoint[] { endpoint };
            }

            { // Logout endpoint
                Endpoint endpoint = new Endpoint();
                endpoint.Location = IDPConfig.ServerBaseUrl + "Logout.ashx";
                endpoint.Binding  = Saml20Constants.ProtocolBindings.HTTP_Redirect;
                descriptor.SingleLogoutService = new Endpoint[] { endpoint };
            }

            // Create the list of attributes offered.
            List <SamlAttribute> atts = new List <SamlAttribute>(IDPConfig.attributes.Length);

            foreach (string name in IDPConfig.attributes)
            {
                SamlAttribute att = new SamlAttribute();
                att.NameFormat = SamlAttribute.NAMEFORMAT_BASIC;
                att.Name       = name;
                atts.Add(att);
            }

            descriptor.Attributes = atts.ToArray();
            XmlDocument doc = new XmlDocument();

            doc.XmlResolver        = null;
            doc.PreserveWhitespace = true;
            doc.LoadXml(Serialization.SerializeToXmlString(metadata));

            var signatureProvider = SignatureProviderFactory.CreateFromShaHashingAlgorithmName(ShaHashingAlgorithm.SHA256);

            X509Certificate2 cert = IDPConfig.IDPCertificate;
            var id = doc.DocumentElement.GetAttribute("ID");

            signatureProvider.SignMetaData(doc, id, cert);

            context.Response.Write(doc.OuterXml);
        }
예제 #14
0
 internal void AddAttributeFromQuery(string name, SamlAttribute value)
 {
     if (!_attributes.ContainsKey(name))
     {
         _attributes.Add(name, new List <SamlAttribute>());
     }
     if (!_attributes[name].Contains(value))
     {
         _attributes[name].Add(value);
     }
 }
        /// <summary>
        /// Creates a <see cref="SamlAttribute"/> with the specified name.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="friendlyName">Friendly name.</param>
        /// <param name="value">The attribute value.</param>
        /// <returns>The <see cref="SamlAttribute"/>.</returns>
        protected static SamlAttribute Create(string name, string friendlyName, string value)
        {
            var att = new SamlAttribute
            {
                NameFormat     = SamlAttribute.NameformatUri,
                Name           = name,
                FriendlyName   = friendlyName,
                AttributeValue = new[] { value }
            };

            return(att);
        }
예제 #16
0
        public void TestMethod()
        {
            string[]      attributeValues = { "test-value" };
            SamlAttribute samlAttribute   = new SamlAttribute("urn:namespace", "attributeName", attributeValues);

            Console.WriteLine("saml attribute: " + samlAttribute);

            SamlAuthenticationStatement samlStatement = new SamlAuthenticationStatement();

            SamlAssertion samlAssertion = new SamlAssertion();

            samlAssertion.Statements.Add(samlStatement);
        }
예제 #17
0
        private static void InitializeSecurityContext(string tokenString)
        {
            tokenString = CryptographyHelper.DecryptFromLocalMachine(tokenString);
            SettingsSecureFileStore securitySettings = new SettingsSecureFileStore();
            ServiceConfiguration    configs          = securitySettings.GetConfigurations();

            if (configs != null)
            {
                SecurityToken token = Helper.DeSerializeSecurityToken(tokenString, configs.get_STSThumbprint(), configs.get_STSThumbprintName());
                ServiceHelperFactory.get_Instance().set_BaseUri(configs.get_ServiceBaseUrl());
                ClientConfiguration settings = securitySettings.GetClientSettingsFromConfigDll();
                if (settings == null)
                {
                    Program.logger.Error("Client configurations for security service not found");
                }
                if (settings != null)
                {
                    string clientIDFromToken         = string.Empty;
                    List <RequestClaim> customClaims = new List <RequestClaim>();
                    SamlSecurityToken   samlToken    = token as SamlSecurityToken;
                    if ((samlToken == null || samlToken.Assertion == null || samlToken.Assertion.Statements == null ? false : samlToken.Assertion.Statements.Count > 0))
                    {
                        SamlAttributeStatement statements = samlToken.Assertion.Statements[0] as SamlAttributeStatement;
                        if ((statements == null || statements.Attributes == null ? false : statements.Attributes.Count > 0))
                        {
                            SamlAttribute ClientId = statements.Attributes.FirstOrDefault <SamlAttribute>((SamlAttribute z) => StringUtility.EqualsIgnoreCase(z.Name, "clientid"));
                            if ((ClientId == null || ClientId.AttributeValues == null ? false : ClientId.AttributeValues.Count > 0))
                            {
                                clientIDFromToken = ClientId.AttributeValues[0];
                                customClaims.Add(new RequestClaim("http://schemas.imanami.com/ws/2014/06/identity/claims/clientId", true, clientIDFromToken));
                            }
                        }
                    }
                    settings.set_ActAsClientUrl(ServiceHelperFactory.get_Instance().get_BaseUri());
                    NetworkCredential       creds = CredentialCache.DefaultCredentials as NetworkCredential;
                    ClaimsPrincipalSelector claimsPrincipalSelector = (clientIDFromToken == string.Empty ? new ClaimsPrincipalSelector(creds, settings, null) : new ClaimsPrincipalSelector(creds, settings, customClaims));
                    claimsPrincipalSelector.GetClaimsPrincipal();
                    ClaimsPrincipal.ClaimsPrincipalSelector = new Func <ClaimsPrincipal>(claimsPrincipalSelector.GetClaimsPrincipal);
                    if (claimsPrincipalSelector.get_ClaimsPrincipal() != null)
                    {
                        claimsPrincipalSelector.get_ClaimsPrincipal().set_ActAsToken(token);
                    }
                    ServiceHelperFactory.get_Instance().set_StsClientConfiguration(settings);
                    ServiceHelperFactory.get_Instance().set_StsUserCredentials(creds);
                }
            }
            else
            {
                Program.logger.Error("Client configurations not found");
            }
        }
예제 #18
0
        private static SamlAssertion CreateSamlAssertion(string issuer, string domain, string subject, Dictionary <string, string> attributes)
        {
            // Here we create some SAML assertion with ID and Issuer name.
            SamlAssertion assertion = new SamlAssertion();

            assertion.AssertionId = "_" + Guid.NewGuid().ToString();
            assertion.Issuer      = issuer;

            //Not before, not after conditions
            assertion.Conditions = new SamlConditions(DateTime.UtcNow,
                                                      DateTime.UtcNow.AddMinutes(10));

            //
            // Create some SAML subject.
            SamlSubject samlSubject = new SamlSubject();

            samlSubject.Name          = subject;
            samlSubject.NameQualifier = subject;

            samlSubject.ConfirmationMethods.Add("urn:oasis:names:tc:SAML:1.0:cm:bearer");
            //
            // Now create the SAML statement containing one attribute and one subject.
            SamlAttributeStatement samlAttributeStatement = new SamlAttributeStatement();

            samlAttributeStatement.SamlSubject = samlSubject;
            //
            // Create userName SAML attributes.
            foreach (KeyValuePair <string, string> attribute in attributes)
            {
                SamlAttribute attr = new SamlAttribute();
                attr.Name      = attribute.Key;
                attr.Namespace = domain;
                attr.AttributeValues.Add(subject);
                samlAttributeStatement.Attributes.Add(attr);
            }
            // Append the statement to the SAML assertion.
            assertion.Statements.Add(samlAttributeStatement);

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

            SamlAuthenticationStatement samlAuthenticationStatement =
                new SamlAuthenticationStatement(samlSubject,
                                                "urn:oasis:names:tc:SAML:1.0:am:password",
                                                DateTime.UtcNow, null, ipEntry.AddressList[0].ToString(),
                                                null);

            assertion.Statements.Add(samlAuthenticationStatement);
            return(assertion);
        }
예제 #19
0
        public void CompareSamlAttribute()
        {
            TestUtilities.WriteHeader($"{this}.CompareSamlAttributes", true);
            var context        = new CompareContext($"{this}.CompareSamlAttributes");
            var samlAttribute1 = new SamlAttribute(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());
            var samlAttribute2 = new SamlAttribute(Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString());

            IdentityComparer.AreEqual(samlAttribute1, samlAttribute2, context);

            Assert.True(context.Diffs.Count(s => s == "ClaimType:") == 1);
            Assert.True(context.Diffs.Count(s => s == "Name:") == 1);
            Assert.True(context.Diffs.Count(s => s == "Namespace:") == 1);
            Assert.True(context.Diffs.Count(s => s == "Values:") == 1);
        }
        /// <summary>
        /// Adds an attribute by name using the specified name format.
        /// </summary>
        /// <param name="attrName">Name of the attribute.</param>
        /// <param name="nameFormat">The name format of the attribute.</param>
        public void AddAttribute(string attrName, Saml20NameFormat nameFormat)
        {
            if (_attributes.Any(at => at.Name == attrName && at.NameFormat == GetNameFormat(nameFormat)))
            {
                throw new InvalidOperationException(string.Format("An attribute with name \"{0}\" and name format \"{1}\" has already been added", attrName, Enum.GetName(typeof(Saml20NameFormat), nameFormat)));
            }

            var attr = new SamlAttribute
            {
                Name       = attrName,
                NameFormat = GetNameFormat(nameFormat)
            };

            _attributes.Add(attr);
        }
예제 #21
0
        public void WriteXml1()
        {
            SamlAttribute attr    = new SamlAttribute(Claim.CreateNameClaim("myname"));
            SamlSubject   subject = new SamlSubject(
                SamlConstants.UserNameNamespace,
                "urn:myqualifier",
                "myname");
            SamlAttributeStatement s = new SamlAttributeStatement(
                subject, new SamlAttribute [] { attr });
            StringWriter sw = new StringWriter();

            using (XmlDictionaryWriter dw = CreateWriter(sw)) {
                s.WriteXml(dw, new SamlSerializer(), null);
            }
            Assert.AreEqual(String.Format("<?xml version=\"1.0\" encoding=\"utf-16\"?><saml:AttributeStatement xmlns:saml=\"urn:oasis:names:tc:SAML:1.0:assertion\"><saml:Subject><saml:NameIdentifier Format=\"urn:oasis:names:tc:SAML:1.1:nameid-format:WindowsDomainQualifiedName\" NameQualifier=\"urn:myqualifier\">myname</saml:NameIdentifier></saml:Subject><saml:Attribute AttributeName=\"name\" AttributeNamespace=\"{0}\"><saml:AttributeValue>myname</saml:AttributeValue></saml:Attribute></saml:AttributeStatement>", "http://schemas.xmlsoap.org/ws/2005/05/identity/claims"), sw.ToString());
        }
예제 #22
0
        /// <summary>
        /// Adds an attribute by name using the specified name format.
        /// </summary>
        /// <param name="attrName">Name of the attribute.</param>
        /// <param name="nameFormat">The name format of the attribute.</param>
        public void AddAttribute(string attrName, Saml20NameFormat nameFormat)
        {
            List <SamlAttribute> found = _attributes.FindAll(delegate(SamlAttribute at) { return(at.Name == attrName && at.NameFormat == GetNameFormat(nameFormat)); });

            if (found.Count > 0)
            {
                throw new InvalidOperationException(
                          string.Format("An attribute with name \"{0}\" and name format \"{1}\" has already been added", attrName, Enum.GetName(typeof(Saml20NameFormat), nameFormat)));
            }

            SamlAttribute attr = new SamlAttribute();

            attr.Name       = attrName;
            attr.NameFormat = GetNameFormat(nameFormat);

            _attributes.Add(attr);
        }
예제 #23
0
        private static IEnumerable <SamlAttribute> ParseAttributes(XmlNodeList attributes)
        {
            var result = new List <SamlAttribute>();

            for (var i = 0; i < attributes.Count; i++)
            {
                var attribute     = attributes[i];
                var attributeName = attribute.SelectSingleNode("@Name", SamlXmlExtensions.NamespaceManager);
                if (attributeName == null || string.IsNullOrEmpty(attributeName.InnerText))
                {
                    throw new ParsingException("Attribute name is missing");
                }

                var attributeObject = new SamlAttribute
                {
                    Name        = attributeName.InnerText,
                    IsEncrypted = attribute.Name == "EncryptedAttribute"
                };

                var attributeNameFormat = attribute.SelectSingleNode("@NameFormat", SamlXmlExtensions.NamespaceManager);
                if (!string.IsNullOrEmpty(attributeNameFormat?.InnerText))
                {
                    attributeObject.NameFormat = attributeNameFormat.InnerText;
                }

                var attributeFriendlyName = attribute.SelectSingleNode("@FriendlyName", SamlXmlExtensions.NamespaceManager);
                if (!string.IsNullOrEmpty(attributeFriendlyName?.InnerText))
                {
                    attributeObject.FriendlyName = attributeFriendlyName.InnerText;
                }

                var attributeValues = attribute.SelectNodes($"{SamlAuthenticationDefaults.SamlAssertionNsPrefix}:AttributeValue", SamlXmlExtensions.NamespaceManager);
                for (var j = 0; j < attributeValues.Count; j++)
                {
                    var attributeValue = attributeValues[j];
                    if (!string.IsNullOrEmpty(attributeValue?.InnerText))
                    {
                        attributeObject.Values.Add(attributeValue.InnerText);
                    }
                }

                result.Add(attributeObject);
            }
            return(result);
        }
예제 #24
0
        public void ValidateAttribute(SamlAttribute samlAttribute)
        {
            // MOE: REMOVE CHECK AS ESAA DOES NOT RETURN COMPLIANT MESSAGE:
            //if (!Uri.IsWellFormedUriString(samlAttribute.Name, UriKind.Absolute))
            //    throw new DKSaml20FormatException("The DK-SAML 2.0 profile requires that an attribute's \"Name\" is an URI.");

            if (samlAttribute.AttributeValue == null)
            {
                return;
            }

            foreach (object val in samlAttribute.AttributeValue)
            {
                if (val is string)
                {
                    continue;
                }

                throw new DKSaml20FormatException("The DK-SAML 2.0 profile requires that all attribute values are of type \"xs:string\".");
            }
        }
예제 #25
0
        public void ValidateAttribute(SamlAttribute samlAttribute)
        {
            if (!Uri.IsWellFormedUriString(samlAttribute.Name, UriKind.Absolute))
            {
                throw new DKSaml20FormatException("The DK-SAML 2.0 profile requires that an attribute's \"Name\" is an URI.");
            }

            if (samlAttribute.AttributeValue == null)
            {
                return;
            }

            foreach (object val in samlAttribute.AttributeValue)
            {
                if (val is string)
                {
                    continue;
                }

                throw new DKSaml20FormatException("The DK-SAML 2.0 profile requires that all attribute values are of type \"xs:string\".");
            }
        }
예제 #26
0
파일: SAMLFactory.cs 프로젝트: dmcwee/azure
        public static SamlSecurityToken CreateSamlToken(string issuedBy, string subject, string attrNamespace, Dictionary <string, string> claims, string certThumbPrint)
        {
            SamlAssertion assertion = new SamlAssertion();

            assertion.AssertionId = string.Format("icfi_{0}", Guid.NewGuid().ToString());
            assertion.Issuer      = issuedBy;

            SamlSubject subj = new SamlSubject();

            subj.Name = subject;

            SamlAttributeStatement samlAttrStatement = new SamlAttributeStatement();

            foreach (string claimKey in claims.Keys)
            {
                SamlAttribute attr = new SamlAttribute();
                attr.Namespace = attrNamespace;
                attr.AttributeValues.Add(claims[claimKey]);
                samlAttrStatement.Attributes.Add(attr);
            }
            samlAttrStatement.SamlSubject = subj;

            assertion.Statements.Add(samlAttrStatement);

            X509Certificate2 cert = GetCertificate(certThumbPrint);

            X509AsymmetricSecurityKey signingKey = new X509AsymmetricSecurityKey(cert);

            assertion.SigningCredentials = new SigningCredentials(
                signingKey,
                cert.PublicKey.Key.SignatureAlgorithm,
                SecurityAlgorithms.Sha1Digest,
                new SecurityKeyIdentifier(new X509ThumbprintKeyIdentifierClause(cert)));

            SamlSecurityToken samlToken = new SamlSecurityToken(assertion);

            return(samlToken);
        }
예제 #27
0
        public void ConstructorNullSubject()
        {
            SamlAttribute attr = new SamlAttribute(Claim.CreateNameClaim("myname"));

            new SamlAttributeStatement(null, new SamlAttribute [] { attr });
        }
예제 #28
0
        /// <summary>
        /// Assembles our basic test assertion
        /// </summary>
        /// <returns>The <see cref="Assertion"/>.</returns>
        public static Assertion GetBasicAssertion()
        {
            var assertion = new Assertion
            {
                Issuer       = new NameId(),
                Id           = "_b8977dc86cda41493fba68b32ae9291d",
                IssueInstant = DateTime.UtcNow,
                Version      = "2.0"
            };

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

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

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

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

            AttributeStatement attributeStatement;

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

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

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

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

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

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

            return(assertion);
        }
예제 #29
0
        private Assertion CreateAssertion(User user, string receiver, string nameIdFormat)
        {
            Assertion assertion = new Assertion();

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

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

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

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

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

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

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

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

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

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

                authnStatement.AuthnContext = new AuthnContext();

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

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

                statements.Add(authnStatement);
            }

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

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


                attributeStatement.Items = attributes.ToArray();

                statements.Add(attributeStatement);
            }

            assertion.Items = statements.ToArray();

            return(assertion);
        }
예제 #30
0
        // returns subject and attributes from a WS-Fed token (Ws-Fed endpoint)
        private List <SamlAttribute> GetAttributesListFromSAML(string samlToken)
        {
            // Setup return list
            List <SamlAttribute> SamlAttribs = new List <SamlAttribute>();

            // Convert to xml for easy parsing
            XmlDocument samlXml = new XmlDocument();

            samlXml.LoadXml(samlToken);

            // Parse SAML token for subject (WS-Fed)
            try
            {
                string subject = samlXml.SelectSingleNode("/AttributeStatement/Subject/NameIdentifier").InnerText;

                SamlAttribute samlAttribSubject = new SamlAttribute()
                {
                    Name        = "Subject",
                    Value       = subject,
                    Description = "N/A"
                };
                SamlAttribs.Add(samlAttribSubject);
            }
            catch { }

            // Parse SAML token for subject (SAML)
            try
            {
                //string subject = samlXml.SelectSingleNode("/Response/Assertion/Subject/NameID").InnerText; - Failing for some reason

                XmlNodeList subject  = samlXml.GetElementsByTagName("NameID");
                string      sSubject = subject[0].InnerText;

                // Create SAML object
                SamlAttribute samlAttribSubject = new SamlAttribute()
                {
                    Name        = "Subject",
                    Value       = sSubject,
                    Description = "N/A"
                };

                // Add to list to be returned
                SamlAttribs.Add(samlAttribSubject);
            }
            catch { }

            // Parse Attribs and add to list
            try   // WS-Fed endpoint
            {
                XmlNodeList elemList = samlXml.GetElementsByTagName("Attribute");
                for (int i = 0; i < elemList.Count; i++)
                {
                    SamlAttribute samlAttrib = new SamlAttribute()
                    {
                        Name        = elemList[i].Attributes.GetNamedItem("AttributeName").Value,
                        Value       = elemList[i].InnerText,
                        Description = elemList[i].Attributes.GetNamedItem("AttributeNamespace").Value
                    };

                    // Add to list for gridview bind
                    SamlAttribs.Add(samlAttrib);
                }
            }
            catch   // SAML endpoint
            {
                XmlNodeList elemList = samlXml.GetElementsByTagName("Attribute");
                for (int i = 0; i < elemList.Count; i++)
                {
                    SamlAttribute samlAttrib = new SamlAttribute()
                    {
                        Name        = "N/A - SAML endpoint",
                        Value       = elemList[i].InnerText,
                        Description = elemList[i].Attributes.GetNamedItem("Name").Value
                    };

                    // Add to list for gridview bind
                    SamlAttribs.Add(samlAttrib);
                }
            }

            return(SamlAttribs);
        }