public SamlAuthenticationStatement(SamlSubject samlSubject, string authenticationMethod, DateTime authenticationInstant, string dnsAddress, string ipAddress, IEnumerable<SamlAuthorityBinding> authorityBindings) : base(samlSubject)
 {
     this.authenticationInstant = DateTime.UtcNow.ToUniversalTime();
     this.authenticationMethod = XD.SamlDictionary.UnspecifiedAuthenticationMethod.Value;
     this.authorityBindings = new ImmutableCollection<SamlAuthorityBinding>();
     if (string.IsNullOrEmpty(authenticationMethod))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("authenticationMethod", System.IdentityModel.SR.GetString("SAMLAuthenticationStatementMissingAuthenticationMethod"));
     }
     this.authenticationMethod = authenticationMethod;
     this.authenticationInstant = authenticationInstant.ToUniversalTime();
     this.dnsAddress = dnsAddress;
     this.ipAddress = ipAddress;
     if (authorityBindings != null)
     {
         foreach (SamlAuthorityBinding binding in authorityBindings)
         {
             if (binding == null)
             {
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.IdentityModel.SR.GetString("SAMLEntityCannotBeNullOrEmpty", new object[] { XD.SamlDictionary.Assertion.Value }));
             }
             this.authorityBindings.Add(binding);
         }
     }
     this.CheckObjectValidity();
 }
示例#2
0
		public void DefaultValues ()
		{
			SamlSubject a = new SamlSubject ();
			Assert.IsNull (a.NameFormat, "#1");
			Assert.IsNull (a.NameQualifier, "#2");
			Assert.IsNull (a.Name, "#3");
		}
 public SamlAuthorizationDecisionStatement(
     SamlSubject samlSubject, string resource,
     SamlAccessDecision accessDecision,
     IEnumerable <SamlAction> samlActions)
     : base(samlSubject)
 {
     if (samlActions == null)
     {
         throw new ArgumentNullException("samlActions");
     }
     if (resource == null || resource.Length == 0)
     {
         throw new SecurityTokenException("non-zero length string must be set to Resource of SAML AuthorizationDecisionStatement.");
     }
     Resource       = resource;
     AccessDecision = accessDecision;
     foreach (SamlAction a in samlActions)
     {
         if (a == null)
         {
             throw new ArgumentException("samlActions contain null item.");
         }
         actions.Add(a);
     }
 }
        public SamlAuthenticationStatement(SamlSubject samlSubject,
                                           string authenticationMethod,
                                           DateTime authenticationInstant,
                                           string dnsAddress,
                                           string ipAddress,
                                           IEnumerable <SamlAuthorityBinding> authorityBindings)
            : base(samlSubject)
        {
            if (string.IsNullOrEmpty(authenticationMethod))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("authenticationMethod", SR.GetString(SR.SAMLAuthenticationStatementMissingAuthenticationMethod));
            }

            this.authenticationMethod  = authenticationMethod;
            this.authenticationInstant = authenticationInstant.ToUniversalTime();
            this.dnsAddress            = dnsAddress;
            this.ipAddress             = ipAddress;

            if (authorityBindings != null)
            {
                foreach (SamlAuthorityBinding binding in authorityBindings)
                {
                    if (binding == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLEntityCannotBeNullOrEmpty, XD.SamlDictionary.Assertion.Value));
                    }

                    this.authorityBindings.Add(binding);
                }
            }

            CheckObjectValidity();
        }
        public SamlAuthenticationStatement(SamlSubject samlSubject,
            string authenticationMethod,
            DateTime authenticationInstant,
            string dnsAddress,
            string ipAddress,
            IEnumerable<SamlAuthorityBinding> authorityBindings)
            : base(samlSubject)
        {
            if (string.IsNullOrEmpty(authenticationMethod))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("authenticationMethod", SR.GetString(SR.SAMLAuthenticationStatementMissingAuthenticationMethod));

            this.authenticationMethod = authenticationMethod;
            this.authenticationInstant = authenticationInstant.ToUniversalTime();
            this.dnsAddress = dnsAddress;
            this.ipAddress = ipAddress;

            if (authorityBindings != null)
            {
                foreach (SamlAuthorityBinding binding in authorityBindings)
                {
                    if (binding == null)
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLEntityCannotBeNullOrEmpty, XD.SamlDictionary.Assertion.Value));

                    this.authorityBindings.Add(binding);
                }
            }

            CheckObjectValidity();
        }
        protected SamlSubjectStatement(SamlSubject samlSubject)
        {
            if (samlSubject == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSubject"));

            this.subject = samlSubject;
        }
示例#7
0
 public SamlAuthenticationStatement(SamlSubject samlSubject, string authenticationMethod, DateTime authenticationInstant, string dnsAddress, string ipAddress, IEnumerable <SamlAuthorityBinding> authorityBindings) : base(samlSubject)
 {
     this.authenticationInstant = DateTime.UtcNow.ToUniversalTime();
     this.authenticationMethod  = XD.SamlDictionary.UnspecifiedAuthenticationMethod.Value;
     this.authorityBindings     = new ImmutableCollection <SamlAuthorityBinding>();
     if (string.IsNullOrEmpty(authenticationMethod))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("authenticationMethod", System.IdentityModel.SR.GetString("SAMLAuthenticationStatementMissingAuthenticationMethod"));
     }
     this.authenticationMethod  = authenticationMethod;
     this.authenticationInstant = authenticationInstant.ToUniversalTime();
     this.dnsAddress            = dnsAddress;
     this.ipAddress             = ipAddress;
     if (authorityBindings != null)
     {
         foreach (SamlAuthorityBinding binding in authorityBindings)
         {
             if (binding == null)
             {
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.IdentityModel.SR.GetString("SAMLEntityCannotBeNullOrEmpty", new object[] { XD.SamlDictionary.Assertion.Value }));
             }
             this.authorityBindings.Add(binding);
         }
     }
     this.CheckObjectValidity();
 }
示例#8
0
 // MSDN says that it ignores IsReadOnly
 protected void SetSubject(SamlSubject samlSubject)
 {
     if (samlSubject == null)
     {
         throw new ArgumentNullException("samlSubject");
     }
     subject = samlSubject;
 }
        public override void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
            }

            if (samlSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));
            }

#pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null.
            SamlDictionary dictionary = samlSerializer.DictionaryManager.SamlDictionary;

            reader.MoveToContent();
            reader.Read();

            if (reader.IsStartElement(dictionary.Subject, dictionary.Namespace))
            {
                SamlSubject subject = new SamlSubject();
                subject.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
                base.SamlSubject = subject;
            }
            else
            {
                // SAML Subject is a required Attribute Statement clause.
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAttributeStatementMissingSubjectOnRead)));
            }

            while (reader.IsStartElement())
            {
                if (reader.IsStartElement(dictionary.Attribute, dictionary.Namespace))
                {
                    // SAML Attribute is a extensibility point. So ask the SAML serializer
                    // to load this part.
                    SamlAttribute attribute = samlSerializer.LoadAttribute(reader, keyInfoSerializer, outOfBandTokenResolver);
                    if (attribute == null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLUnableToLoadAttribute)));
                    }
                    this.attributes.Add(attribute);
                }
                else
                {
                    break;
                }
            }

            if (this.attributes.Count == 0)
            {
                // Each Attribute statement should have at least one attribute.
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAttributeStatementMissingAttributeOnRead)));
            }

            reader.MoveToContent();
            reader.ReadEndElement();
        }
示例#10
0
        protected SamlSubjectStatement(SamlSubject samlSubject)
        {
            if (samlSubject == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSubject"));
            }

            this.subject = samlSubject;
        }
 public SamlAuthorizationDecisionStatement(
     SamlSubject samlSubject, string resource,
     SamlAccessDecision accessDecision,
     IEnumerable <SamlAction> samlActions,
     SamlEvidence samlEvidence)
     : this(samlSubject, resource, accessDecision, samlActions)
 {
     evidence = samlEvidence;
 }
		public SamlAuthorizationDecisionStatement (
			SamlSubject samlSubject, string resource,
			SamlAccessDecision accessDecision,
			IEnumerable<SamlAction> samlActions,
			SamlEvidence samlEvidence)
			: this (samlSubject, resource, accessDecision, samlActions)
		{
			evidence = samlEvidence;
		}
示例#13
0
        /// <summary>
        /// Creates a SAML Token with the input parameters
        /// </summary>
        /// <param name="stsName">Name of the STS issuing the SAML Token</param>
        /// <param name="proofToken">Associated Proof Token</param>
        /// <param name="issuerToken">Associated Issuer Token</param>
        /// <param name="proofKeyEncryptionToken">Token to encrypt the proof key with</param>
        /// <param name="samlConditions">The Saml Conditions to be used in the construction of the SAML Token</param>
        /// <param name="samlAttributes">The Saml Attributes to be used in the construction of the SAML Token</param>
        /// <returns>A SAML Token</returns>
        public static SamlSecurityToken CreateSamlToken(string stsName,
                                                        BinarySecretSecurityToken proofToken,
                                                        SecurityToken issuerToken,
                                                        SecurityToken proofKeyEncryptionToken,
                                                        SamlConditions samlConditions,
                                                        IEnumerable<SamlAttribute> samlAttributes)
		{
            // Create a security token reference to the issuer certificate 
            SecurityKeyIdentifierClause skic = issuerToken.CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause>();
            SecurityKeyIdentifier issuerKeyIdentifier = new SecurityKeyIdentifier(skic);

            // Create an encrypted key clause containing the encrypted proof key
            byte[] wrappedKey = proofKeyEncryptionToken.SecurityKeys[0].EncryptKey(SecurityAlgorithms.RsaOaepKeyWrap, proofToken.GetKeyBytes());
            SecurityKeyIdentifierClause encryptingTokenClause = proofKeyEncryptionToken.CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause>();
            EncryptedKeyIdentifierClause encryptedKeyClause = new EncryptedKeyIdentifierClause(wrappedKey, SecurityAlgorithms.RsaOaepKeyWrap, new SecurityKeyIdentifier(encryptingTokenClause) );
            SecurityKeyIdentifier proofKeyIdentifier = new SecurityKeyIdentifier(encryptedKeyClause);

            // Create a comfirmationMethod for HolderOfKey
			List<string> confirmationMethods = new List<string>(1);
			confirmationMethods.Add(SamlConstants.HolderOfKey);

            // Create a SamlSubject with proof key and confirmation method from above
			SamlSubject samlSubject = new SamlSubject(null,
													  null,
													  null,
													  confirmationMethods,
													  null,
                                                      proofKeyIdentifier);

            // Create a SamlAttributeStatement from the passed in SamlAttribute collection and the SamlSubject from above
			SamlAttributeStatement samlAttributeStatement = new SamlAttributeStatement(samlSubject, samlAttributes);

            // Put the SamlAttributeStatement into a list of SamlStatements
			List<SamlStatement> samlSubjectStatements = new List<SamlStatement>();
			samlSubjectStatements.Add(samlAttributeStatement);

            // Create a SigningCredentials instance from the key associated with the issuerToken.
            SigningCredentials signingCredentials = new SigningCredentials(issuerToken.SecurityKeys[0],
                                                                           SecurityAlgorithms.RsaSha1Signature,
                                                                           SecurityAlgorithms.Sha1Digest,
                                                                           issuerKeyIdentifier);

            // Create a SamlAssertion from the list of SamlStatements created above and the passed in
            // SamlConditions.
			SamlAssertion samlAssertion = new SamlAssertion("_" + Guid.NewGuid().ToString(),
							                                stsName,
							                                DateTime.UtcNow,
							                                samlConditions,
							                                new SamlAdvice(),
							                                samlSubjectStatements
						                                	);
            // Set the SigningCredentials for the SamlAssertion
			samlAssertion.SigningCredentials = signingCredentials;

            // Create a SamlSecurityToken from the SamlAssertion and return it
			return new SamlSecurityToken(samlAssertion);
		}
示例#14
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 ());
		}
示例#15
0
 public override void WriteXml(XmlDictionaryWriter writer,
                               SamlSerializer samlSerializer,
                               SecurityTokenSerializer keyInfoTokenSerializer)
 {
     if (SamlSubject == null)
     {
         throw new SecurityTokenException("Subject is null in the AttributeStatement");
     }
     writer.WriteStartElement("saml", "AttributeStatement", SamlConstants.Namespace);
     SamlSubject.WriteXml(writer, samlSerializer, keyInfoTokenSerializer);
     foreach (SamlAttribute a in Attributes)
     {
         a.WriteXml(writer, samlSerializer, keyInfoTokenSerializer);
     }
     writer.WriteEndElement();
 }
        public SamlAttributeStatement(SamlSubject samlSubject, IEnumerable<SamlAttribute> attributes)
            : base(samlSubject)
        {
            if (attributes == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("attributes"));

            foreach (SamlAttribute attribute in attributes)
            {
                if (attribute == null)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLEntityCannotBeNullOrEmpty, XD.SamlDictionary.Attribute.Value));

                this.attributes.Add(attribute);
            }

            CheckObjectValidity();
        }
		public SamlAuthenticationStatement (SamlSubject samlSubject,
			string authenticationMethod,
			DateTime authenticationInstant,
			string dnsAddress, string ipAddress,
			IEnumerable<SamlAuthorityBinding> authorityBindings)
			: base (samlSubject)
		{
			AuthenticationMethod = authenticationMethod;
			instant = authenticationInstant;
			dns = dnsAddress;
			ip = ipAddress;
			if (authorityBindings != null)
				bindings = new List<SamlAuthorityBinding> (authorityBindings);
			else
				bindings = new List<SamlAuthorityBinding> ();
		}
 public SamlAttributeStatement(SamlSubject samlSubject, IEnumerable<SamlAttribute> attributes) : base(samlSubject)
 {
     this.attributes = new ImmutableCollection<SamlAttribute>();
     if (attributes == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("attributes"));
     }
     foreach (SamlAttribute attribute in attributes)
     {
         if (attribute == null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.IdentityModel.SR.GetString("SAMLEntityCannotBeNullOrEmpty", new object[] { XD.SamlDictionary.Attribute.Value }));
         }
         this.attributes.Add(attribute);
     }
     this.CheckObjectValidity();
 }
示例#19
0
 public SamlAttributeStatement(SamlSubject samlSubject, IEnumerable <SamlAttribute> attributes) : base(samlSubject)
 {
     this.attributes = new ImmutableCollection <SamlAttribute>();
     if (attributes == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("attributes"));
     }
     foreach (SamlAttribute attribute in attributes)
     {
         if (attribute == null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.IdentityModel.SR.GetString("SAMLEntityCannotBeNullOrEmpty", new object[] { XD.SamlDictionary.Attribute.Value }));
         }
         this.attributes.Add(attribute);
     }
     this.CheckObjectValidity();
 }
		public SamlAuthorizationDecisionStatement (
			SamlSubject samlSubject, string resource,
			SamlAccessDecision accessDecision,
			IEnumerable<SamlAction> samlActions)
			: base (samlSubject)
		{
			if (samlActions == null)
				throw new ArgumentNullException ("samlActions");
			if (resource == null || resource.Length == 0)
				throw new SecurityTokenException ("non-zero length string must be set to Resource of SAML AuthorizationDecisionStatement.");
			Resource = resource;
			AccessDecision = accessDecision;
			foreach (SamlAction a in samlActions) {
				if (a == null)
					throw new ArgumentException ("samlActions contain null item.");
				actions.Add (a);
			}
		}
示例#21
0
        public override void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
            }
            if (samlSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));
            }
            SamlDictionary samlDictionary = samlSerializer.DictionaryManager.SamlDictionary;

            reader.MoveToContent();
            reader.Read();
            if (!reader.IsStartElement(samlDictionary.Subject, samlDictionary.Namespace))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAttributeStatementMissingSubjectOnRead")));
            }
            SamlSubject subject = new SamlSubject();

            subject.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
            base.SamlSubject = subject;
            while (reader.IsStartElement())
            {
                if (!reader.IsStartElement(samlDictionary.Attribute, samlDictionary.Namespace))
                {
                    break;
                }
                SamlAttribute item = samlSerializer.LoadAttribute(reader, keyInfoSerializer, outOfBandTokenResolver);
                if (item == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLUnableToLoadAttribute")));
                }
                this.attributes.Add(item);
            }
            if (this.attributes.Count == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAttributeStatementMissingAttributeOnRead")));
            }
            reader.MoveToContent();
            reader.ReadEndElement();
        }
        public SamlAttributeStatement(SamlSubject samlSubject, IEnumerable <SamlAttribute> attributes)
            : base(samlSubject)
        {
            if (attributes == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("attributes"));
            }

            foreach (SamlAttribute attribute in attributes)
            {
                if (attribute == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.SAMLEntityCannotBeNullOrEmpty, XD.SamlDictionary.Attribute.Value));
                }

                this.attributes.Add(attribute);
            }

            CheckObjectValidity();
        }
示例#23
0
 public SamlAuthenticationStatement(SamlSubject samlSubject,
                                    string authenticationMethod,
                                    DateTime authenticationInstant,
                                    string dnsAddress, string ipAddress,
                                    IEnumerable <SamlAuthorityBinding> authorityBindings)
     : base(samlSubject)
 {
     AuthenticationMethod = authenticationMethod;
     instant = authenticationInstant;
     dns     = dnsAddress;
     ip      = ipAddress;
     if (authorityBindings != null)
     {
         bindings = new List <SamlAuthorityBinding> (authorityBindings);
     }
     else
     {
         bindings = new List <SamlAuthorityBinding> ();
     }
 }
 public SamlAuthorizationDecisionStatement(SamlSubject samlSubject, string resource, SamlAccessDecision accessDecision, IEnumerable<SamlAction> samlActions, SamlEvidence samlEvidence) : base(samlSubject)
 {
     this.actions = new ImmutableCollection<SamlAction>();
     if (samlActions == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlActions"));
     }
     foreach (SamlAction action in samlActions)
     {
         if (action == null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.IdentityModel.SR.GetString("SAMLEntityCannotBeNullOrEmpty", new object[] { XD.SamlDictionary.Action.Value }));
         }
         this.actions.Add(action);
     }
     this.evidence = samlEvidence;
     this.accessDecision = accessDecision;
     this.resource = resource;
     this.CheckObjectValidity();
 }
 public SamlAuthorizationDecisionStatement(SamlSubject samlSubject, string resource, SamlAccessDecision accessDecision, IEnumerable <SamlAction> samlActions, SamlEvidence samlEvidence) : base(samlSubject)
 {
     this.actions = new ImmutableCollection <SamlAction>();
     if (samlActions == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlActions"));
     }
     foreach (SamlAction action in samlActions)
     {
         if (action == null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(System.IdentityModel.SR.GetString("SAMLEntityCannotBeNullOrEmpty", new object[] { XD.SamlDictionary.Action.Value }));
         }
         this.actions.Add(action);
     }
     this.evidence       = samlEvidence;
     this.accessDecision = accessDecision;
     this.resource       = resource;
     this.CheckObjectValidity();
 }
示例#26
0
 /// <summary>
 ///  Populates an IList with the Attributes from the SAML Assertion.
 /// </summary>
 /// <param name="assertion">the SAML Assertion to be parsed</param>
 /// <param name="subject">the SAML Subject for which Attributes are to be retrieved</param>
 /// <returns>
 /// the IList of matching attributes, which will be an empty List if no matches
 /// are found
 /// </returns>
 public static IList<SamlAttribute> GetAttributesFor(SamlAssertion assertion,
                                                     SamlSubject subject)
 {
   IList<SamlAttribute> attributes = new List<SamlAttribute>();
   IEnumerable<SamlStatement> samlStmtEnum = assertion.Statements;
   Type targetTypeAttr = typeof(System.IdentityModel.Tokens.SamlAttributeStatement);
   foreach (Object obj in samlStmtEnum) {
     SamlStatement nextStmt = (SamlStatement) obj;
     if (nextStmt.GetType().Equals(targetTypeAttr)) {
       SamlAttributeStatement attributeStatement = (SamlAttributeStatement)nextStmt;
       if (!(subject.Equals(attributeStatement.SamlSubject)  ||
             subject.Name.Equals(attributeStatement.SamlSubject.Name)))
       {
         continue;
       }
       // Found attributes for this Subject.  Transfer them to List.
       foreach (SamlAttribute nextAttr in attributeStatement.Attributes) {
         attributes.Add(nextAttr);
       }
     }
   }
   return attributes;
 }
示例#27
0
        public override void WriteXml(XmlDictionaryWriter writer,
                                      SamlSerializer samlSerializer,
                                      SecurityTokenSerializer keyInfoTokenSerializer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }
            if (samlSerializer == null)
            {
                throw new ArgumentNullException("samlSerializer");
            }
            if (SamlSubject == null)
            {
                throw new SecurityTokenException("SAML Subject must be set to AuthenticationStatement before it is written.");
            }

            writer.WriteStartElement("saml", "AuthenticationStatement", SamlConstants.Namespace);
            writer.WriteAttributeString("AuthenticationMethod", AuthenticationMethod);
            writer.WriteAttributeString("AuthenticationInstant",
                                        AuthenticationInstant.ToString(SamlConstants.DateFormat, CultureInfo.InvariantCulture));
            SamlSubject.WriteXml(writer, samlSerializer, keyInfoTokenSerializer);
            if (DnsAddress != null || IPAddress != null)
            {
                writer.WriteStartElement("saml", "SubjectLocality", SamlConstants.Namespace);
                if (IPAddress != null)
                {
                    writer.WriteAttributeString("IPAddress", IPAddress);
                }
                if (DnsAddress != null)
                {
                    writer.WriteAttributeString("DNSAddress", DnsAddress);
                }
                writer.WriteEndElement();
            }
            writer.WriteEndElement();
        }
示例#28
0
		public void WriteXml1 ()
		{
			SamlSubject a = new SamlSubject ("myFormat", "myQualifier", "myName");

			StringWriter sw = new StringWriter ();
			using (XmlDictionaryWriter dw = CreateWriter (sw)) {
				a.WriteXml (dw, new SamlSerializer (), null);
			}
			Assert.AreEqual (String.Format ("<?xml version=\"1.0\" encoding=\"utf-16\"?><saml:Subject xmlns:saml=\"{0}\"><saml:NameIdentifier Format=\"myFormat\" NameQualifier=\"myQualifier\">myName</saml:NameIdentifier></saml:Subject>", SamlConstants.Namespace), sw.ToString ());
		}
        public override void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
            }
            if (samlSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));
            }
            SamlDictionary samlDictionary = samlSerializer.DictionaryManager.SamlDictionary;

            this.resource = reader.GetAttribute(samlDictionary.Resource, null);
            if (string.IsNullOrEmpty(this.resource))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthorizationDecisionStatementMissingResourceAttributeOnRead")));
            }
            string attribute = reader.GetAttribute(samlDictionary.Decision, null);

            if (string.IsNullOrEmpty(attribute))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthorizationDecisionStatementMissingDecisionAttributeOnRead")));
            }
            if (attribute.Equals(SamlAccessDecision.Deny.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                this.accessDecision = SamlAccessDecision.Deny;
            }
            else if (attribute.Equals(SamlAccessDecision.Permit.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                this.accessDecision = SamlAccessDecision.Permit;
            }
            else
            {
                this.accessDecision = SamlAccessDecision.Indeterminate;
            }
            reader.MoveToContent();
            reader.Read();
            if (!reader.IsStartElement(samlDictionary.Subject, samlDictionary.Namespace))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthorizationDecisionStatementMissingSubjectOnRead")));
            }
            SamlSubject subject = new SamlSubject();

            subject.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
            base.SamlSubject = subject;
            while (reader.IsStartElement())
            {
                if (reader.IsStartElement(samlDictionary.Action, samlDictionary.Namespace))
                {
                    SamlAction item = new SamlAction();
                    item.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
                    this.actions.Add(item);
                }
                else
                {
                    if (!reader.IsStartElement(samlDictionary.Evidence, samlDictionary.Namespace))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLBadSchema", new object[] { samlDictionary.AuthorizationDecisionStatement })));
                    }
                    if (this.evidence != null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthorizationDecisionHasMoreThanOneEvidence")));
                    }
                    this.evidence = new SamlEvidence();
                    this.evidence.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
                }
            }
            if (this.actions.Count == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthorizationDecisionShouldHaveOneActionOnRead")));
            }
            reader.MoveToContent();
            reader.ReadEndElement();
        }
示例#30
0
		public void WriteXmlNoFormat ()
		{
			SamlSubject a = new SamlSubject ();

			StringWriter sw = new StringWriter ();
			using (XmlDictionaryWriter dw = CreateWriter (sw)) {
				a.WriteXml (dw, new SamlSerializer (), null);
			}
		}
 public SamlAuthorizationDecisionStatement(SamlSubject samlSubject, string resource, SamlAccessDecision accessDecision, IEnumerable <SamlAction> samlActions) : this(samlSubject, resource, accessDecision, samlActions, null)
 {
 }
        public override void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
            }

            if (samlSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));
            }

#pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null.
            SamlDictionary dictionary = samlSerializer.DictionaryManager.SamlDictionary;

            string authInstance = reader.GetAttribute(dictionary.AuthenticationInstant, null);
            if (string.IsNullOrEmpty(authInstance))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAuthenticationStatementMissingAuthenticationInstanceOnRead)));
            }
            this.authenticationInstant = DateTime.ParseExact(
                authInstance, SamlConstants.AcceptedDateTimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None).ToUniversalTime();

            this.authenticationMethod = reader.GetAttribute(dictionary.AuthenticationMethod, null);
            if (string.IsNullOrEmpty(this.authenticationMethod))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAuthenticationStatementMissingAuthenticationMethodOnRead)));
            }

            reader.MoveToContent();
            reader.Read();

            if (reader.IsStartElement(dictionary.Subject, dictionary.Namespace))
            {
                SamlSubject subject = new SamlSubject();
                subject.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
                base.SamlSubject = subject;
            }
            else
            {
                // Subject is a required element for a Authentication Statement clause.
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAuthenticationStatementMissingSubject)));
            }

            if (reader.IsStartElement(dictionary.SubjectLocality, dictionary.Namespace))
            {
                this.dnsAddress = reader.GetAttribute(dictionary.SubjectLocalityDNSAddress, null);
                this.ipAddress  = reader.GetAttribute(dictionary.SubjectLocalityIPAddress, null);

                if (reader.IsEmptyElement)
                {
                    reader.MoveToContent();
                    reader.Read();
                }
                else
                {
                    reader.MoveToContent();
                    reader.Read();
                    reader.ReadEndElement();
                }
            }

            while (reader.IsStartElement())
            {
                if (reader.IsStartElement(dictionary.AuthorityBinding, dictionary.Namespace))
                {
                    SamlAuthorityBinding binding = new SamlAuthorityBinding();
                    binding.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
                    this.authorityBindings.Add(binding);
                }
                else
                {
                    // We do not understand this element.
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLBadSchema, dictionary.AuthenticationStatement)));
                }
            }

            reader.MoveToContent();
            reader.ReadEndElement();
        }
示例#33
0
        /// <summary>
        /// Creates a SAML assertion based on input parameters
        /// </summary>
        /// <param name="claims">A ClaimSet containing the claims to be placed into the SAML assertion</param>
        /// <param name="signatureKey">The SecurityKey that will be used to sign the SAML assertion</param>
        /// <param name="signatureKeyIdentifier">A key identifier for the signature key</param>
        /// <param name="proofKeyIdentifier">A key identifier for the proof key</param>
        /// <param name="algoSuite">The algorithm suite to use when performing cryptographic operations</param>
        /// <returns>A SAML assertion containing the passed in claims and proof key, signed by the provided signature key</returns>
        private static SamlAssertion CreateAssertion(ClaimSet claims, SecurityKey signatureKey, SecurityKeyIdentifier signatureKeyIdentifier, SecurityKeyIdentifier proofKeyIdentifier, SecurityAlgorithmSuite algoSuite)
        {
            List<string> confirmationMethods = new List<string>(1);
            // Create a confirmationMethod for HolderOfKey
            confirmationMethods.Add(SamlConstants.HolderOfKey);

            // Create a SamlSubject with proof key and confirmation method from above
            SamlSubject samlSubject = new SamlSubject(null,
                                                      null,
                                                      "Self",
                                                      confirmationMethods,
                                                      null,
                                                      proofKeyIdentifier);

            IList<SamlAttribute> samlAttributes = new List<SamlAttribute>();
            foreach (Claim c in claims)
            {
                if ( typeof(string) == c.Resource.GetType())
                    samlAttributes.Add(new SamlAttribute(c));
            }

            // Create a SamlAttributeStatement from the passed in SamlAttribute collection and the
            // SamlSubject from above
            SamlAttributeStatement samlAttributeStatement = new SamlAttributeStatement(samlSubject, samlAttributes);

            // Put the SamlAttributeStatement into a list of SamlStatements
            List<SamlStatement> samlSubjectStatements = new List<SamlStatement>();
            samlSubjectStatements.Add(samlAttributeStatement);

            // Create a SigningCredentials instance from the signature key
            SigningCredentials signingCredentials = new SigningCredentials(signatureKey,
                                                                           algoSuite.DefaultAsymmetricSignatureAlgorithm,
                                                                           algoSuite.DefaultDigestAlgorithm,
                                                                           signatureKeyIdentifier);

            // Create a SamlAssertion from the list of SamlStatements created above
            DateTime issueInstant = DateTime.UtcNow;

            // Create the Saml condition with allowed audience Uris
            SamlConditions conditions = new SamlConditions(issueInstant, issueInstant + new TimeSpan(10, 0, 0));
            conditions.Conditions.Add(new SamlAudienceRestrictionCondition(new Uri[] { new Uri("http://localhost:8000/servicemodelsamples/service/calc/symm"),
                                                                                       new Uri("http://localhost:8000/servicemodelsamples/service/calc/asymm") }));

            SamlAssertion samlAssertion = new SamlAssertion("_" + Guid.NewGuid().ToString(),
                                                            "Self",
                                                            issueInstant,
                                                            conditions,
                                                            new SamlAdvice(),
                                                            samlSubjectStatements
                                                            );

            // Set the SigningCredentials for the SamlAssertion
            samlAssertion.SigningCredentials = signingCredentials;

            // Return the SamlAssertion
            return samlAssertion;
        }
示例#34
0
        /// <summary>
        /// Creates a SAML token for the specified email address.
        /// </summary>
        public static UserIdentity CreateSAMLToken(string emailAddress)
        {
            // Normally this would be done by a server that is capable of verifying that
            // the user is a legimate holder of email address. Using a local certficate to
            // signed the SAML token is a short cut that would never be done in a real system.
            CertificateIdentifier userid = new CertificateIdentifier();

            userid.StoreType = CertificateStoreType.Windows;
            userid.StorePath = "LocalMachine\\My";
            userid.SubjectName = "UA Sample Client";

            X509Certificate2 certificate = userid.Find();
            X509SecurityToken signingToken = new X509SecurityToken(certificate);

            // Create list of confirmation strings
            List<string> confirmations = new List<string>();

            // Add holder-of-key string to list of confirmation strings
            confirmations.Add("urn:oasis:names:tc:SAML:1.0:cm:bearer");

            // Create SAML subject statement based on issuer member variable, confirmation string collection 
            // local variable and proof key identifier parameter
            SamlSubject subject = new SamlSubject("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress", null, emailAddress);

            // Create a list of SAML attributes
            List<SamlAttribute> attributes = new List<SamlAttribute>();
            Claim claim = Claim.CreateNameClaim(emailAddress);
            attributes.Add(new SamlAttribute(claim));

            // Create list of SAML statements
            List<SamlStatement> statements = new List<SamlStatement>();

            // Add a SAML attribute statement to the list of statements. Attribute statement is based on 
            // subject statement and SAML attributes resulting from claims
            statements.Add(new SamlAttributeStatement(subject, attributes));

            // Create a valid from/until condition
            DateTime validFrom = DateTime.UtcNow;
            DateTime validTo = DateTime.UtcNow.AddHours(12);

            SamlConditions conditions = new SamlConditions(validFrom, validTo);

            // Create the SAML assertion
            SamlAssertion assertion = new SamlAssertion(
                "_" + Guid.NewGuid().ToString(),
                signingToken.Certificate.Subject,
                validFrom,
                conditions,
                null,
                statements);

            SecurityKey signingKey = new System.IdentityModel.Tokens.RsaSecurityKey((RSA)signingToken.Certificate.PrivateKey);

            // Set the signing credentials for the SAML assertion
            assertion.SigningCredentials = new SigningCredentials(
                signingKey,
                System.IdentityModel.Tokens.SecurityAlgorithms.RsaSha1Signature,
                System.IdentityModel.Tokens.SecurityAlgorithms.Sha1Digest,
                new SecurityKeyIdentifier(signingToken.CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause>()));

            return new UserIdentity(new SamlSecurityToken(assertion));
        }
示例#35
0
		public void SetNameEmpty ()
		{
			SamlSubject a = new SamlSubject ();
			a.Name = String.Empty;
		}
        public override void ReadXml(XmlDictionaryReader reader,
                                     SamlSerializer samlSerializer,
                                     SecurityTokenSerializer keyInfoSerializer,
                                     SecurityTokenResolver outOfBandTokenResolver)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }
            if (samlSerializer == null)
            {
                throw new ArgumentNullException("samlSerializer");
            }

            string decision = reader.GetAttribute("Decision");

            switch (decision)
            {
            case "Permit":
                AccessDecision = SamlAccessDecision.Permit;
                break;

            case "Deny":
                AccessDecision = SamlAccessDecision.Deny;
                break;

            case "Indeterminate":
                AccessDecision = SamlAccessDecision.Indeterminate;
                break;

            default:
                throw new SecurityTokenException(String.Format("AccessDecision value is wrong: {0}", decision));
            }
            Resource = reader.GetAttribute("Resource");

            reader.ReadStartElement("AuthorizationDecisionStatement", SamlConstants.Namespace);

            reader.MoveToContent();
            SamlSubject = new SamlSubject();
            SamlSubject.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
            SamlActions.Clear();
            for (reader.MoveToContent();
                 reader.LocalName == "Action" &&
                 reader.NamespaceURI == SamlConstants.Namespace;
                 reader.MoveToContent())
            {
                SamlAction action = new SamlAction();
                action.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
                SamlActions.Add(action);
            }
            if (reader.LocalName == "Evidence" &&
                reader.NamespaceURI == SamlConstants.Namespace)
            {
                Evidence = new SamlEvidence();
                Evidence.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
                reader.MoveToContent();
            }
            reader.ReadEndElement();

            // verify contents
            if (SamlActions.Count == 0)
            {
                throw new SecurityTokenException("SAML AuthorizationDecisionStatement must contain at least one Action.");
            }

            if (SamlSubject == null)
            {
                throw new SecurityTokenException("SAML Subject must be set to SAML AuthorizationDecisionStatement before being written.");
            }
            if (Resource == null || Resource.Length == 0)
            {
                throw new SecurityTokenException("non-zero string must be set to Resource on SAML AuthorizationDecisionStatement.");
            }
        }
 public override void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
 {
     if (reader == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
     }
     if (samlSerializer == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));
     }
     SamlDictionary samlDictionary = samlSerializer.DictionaryManager.SamlDictionary;
     this.resource = reader.GetAttribute(samlDictionary.Resource, null);
     if (string.IsNullOrEmpty(this.resource))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthorizationDecisionStatementMissingResourceAttributeOnRead")));
     }
     string attribute = reader.GetAttribute(samlDictionary.Decision, null);
     if (string.IsNullOrEmpty(attribute))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthorizationDecisionStatementMissingDecisionAttributeOnRead")));
     }
     if (attribute.Equals(SamlAccessDecision.Deny.ToString(), StringComparison.OrdinalIgnoreCase))
     {
         this.accessDecision = SamlAccessDecision.Deny;
     }
     else if (attribute.Equals(SamlAccessDecision.Permit.ToString(), StringComparison.OrdinalIgnoreCase))
     {
         this.accessDecision = SamlAccessDecision.Permit;
     }
     else
     {
         this.accessDecision = SamlAccessDecision.Indeterminate;
     }
     reader.MoveToContent();
     reader.Read();
     if (!reader.IsStartElement(samlDictionary.Subject, samlDictionary.Namespace))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthorizationDecisionStatementMissingSubjectOnRead")));
     }
     SamlSubject subject = new SamlSubject();
     subject.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
     base.SamlSubject = subject;
     while (reader.IsStartElement())
     {
         if (reader.IsStartElement(samlDictionary.Action, samlDictionary.Namespace))
         {
             SamlAction item = new SamlAction();
             item.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
             this.actions.Add(item);
         }
         else
         {
             if (!reader.IsStartElement(samlDictionary.Evidence, samlDictionary.Namespace))
             {
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLBadSchema", new object[] { samlDictionary.AuthorizationDecisionStatement })));
             }
             if (this.evidence != null)
             {
                 throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthorizationDecisionHasMoreThanOneEvidence")));
             }
             this.evidence = new SamlEvidence();
             this.evidence.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
         }
     }
     if (this.actions.Count == 0)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthorizationDecisionShouldHaveOneActionOnRead")));
     }
     reader.MoveToContent();
     reader.ReadEndElement();
 }
示例#38
0
		public void SetFormatEmpty ()
		{
			SamlSubject a = new SamlSubject ();
			a.NameFormat = String.Empty;
		}
示例#39
0
 public SamlAttributeStatement(SamlSubject samlSubject,
                               IEnumerable <SamlAttribute> attributes)
     : base(samlSubject)
 {
     this.attributes = new List <SamlAttribute> (attributes);
 }
 public SamlAuthorizationDecisionStatement(SamlSubject samlSubject, string resource, SamlAccessDecision accessDecision, IEnumerable<SamlAction> samlActions) : this(samlSubject, resource, accessDecision, samlActions, null)
 {
 }
示例#41
0
        private SecurityToken CreateSAMLToken(DateTime validFrom, DateTime validTo, SecurityKey signingKey, SecurityKeyIdentifier signingKeyIdentifier, SecurityKeyIdentifier proofKeyIdentifier, IList<ClaimTypeRequirement> claimReqs )
        {
            // Create list of confirmation strings
            List<string> confirmations = new List<string>();

            // Add holder-of-key string to list of confirmation strings
            confirmations.Add(SamlConstants.HolderOfKey);

            // Create SAML subject statement based on issuer member variable, confirmation string collection 
            // local variable and proof key identifier parameter
            SamlSubject subject = new SamlSubject(null, null, issuer, confirmations, null, proofKeyIdentifier);

            // Create a list of SAML attributes
            List<SamlAttribute> attributes = new List<SamlAttribute>();

            // Get the claimset we want to place into the SAML assertion
            ClaimSet cs = GetClaimSet(claimReqs);

            // Iterate through the claims and add a SamlAttribute for each claim
            // Note that GetClaimSet call above returns a claimset that only contains PossessProperty claims
            foreach (Claim c in cs)
                attributes.Add(new SamlAttribute(c));

            // Create list of SAML statements
            List<SamlStatement> statements = new List<SamlStatement>();

            // Add a SAML attribute statement to the list of statements. Attribute statement is based on 
            // subject statement and SAML attributes resulting from claims
            statements.Add(new SamlAttributeStatement(subject, attributes));

            // Create a valid from/until condition
            SamlConditions conditions = new SamlConditions(validFrom, validTo);
            
            // Create the SAML assertion
            SamlAssertion assertion = new SamlAssertion("_" + Guid.NewGuid().ToString(), issuer, validFrom, conditions, null, statements);

            // Set the signing credentials for the SAML assertion
            string signatureAlgorithm = GetSignatureAlgorithm(signingKey);
            assertion.SigningCredentials = new SigningCredentials(signingKey, signatureAlgorithm, SecurityAlgorithms.Sha1Digest, signingKeyIdentifier);

            SamlSecurityToken token = new SamlSecurityToken(assertion);
            Console.WriteLine("token.SecurityKeys.Count: {0}", token.SecurityKeys.Count);
            return token;
        }
示例#42
0
		public void ReadXml1 ()
		{
			SamlSerializer ser = new SamlSerializer ();
			string xml = String.Format ("<saml:Subject xmlns:saml=\"{0}\"><saml:NameIdentifier Format=\"myFormat\" NameQualifier=\"myQualifier\">myName</saml:NameIdentifier></saml:Subject>", SamlConstants.Namespace);
			XmlDictionaryReader reader = CreateReader (xml);
			reader.MoveToContent ();

			SamlSubject s = new SamlSubject ();
			s.ReadXml (reader, ser, null, null);
			Assert.AreEqual ("myFormat", s.NameFormat, "#1");
			Assert.AreEqual ("myQualifier", s.NameQualifier, "#2");
			Assert.AreEqual ("myName", s.Name, "#3");
		}
		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 ("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);

		}
 public override void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
 {
     if (reader == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
     }
     if (samlSerializer == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));
     }
     SamlDictionary samlDictionary = samlSerializer.DictionaryManager.SamlDictionary;
     string attribute = reader.GetAttribute(samlDictionary.AuthenticationInstant, null);
     if (string.IsNullOrEmpty(attribute))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthenticationStatementMissingAuthenticationInstanceOnRead")));
     }
     this.authenticationInstant = DateTime.ParseExact(attribute, SamlConstants.AcceptedDateTimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None).ToUniversalTime();
     this.authenticationMethod = reader.GetAttribute(samlDictionary.AuthenticationMethod, null);
     if (string.IsNullOrEmpty(this.authenticationMethod))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthenticationStatementMissingAuthenticationMethodOnRead")));
     }
     reader.MoveToContent();
     reader.Read();
     if (!reader.IsStartElement(samlDictionary.Subject, samlDictionary.Namespace))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthenticationStatementMissingSubject")));
     }
     SamlSubject subject = new SamlSubject();
     subject.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
     base.SamlSubject = subject;
     if (reader.IsStartElement(samlDictionary.SubjectLocality, samlDictionary.Namespace))
     {
         this.dnsAddress = reader.GetAttribute(samlDictionary.SubjectLocalityDNSAddress, null);
         this.ipAddress = reader.GetAttribute(samlDictionary.SubjectLocalityIPAddress, null);
         if (reader.IsEmptyElement)
         {
             reader.MoveToContent();
             reader.Read();
         }
         else
         {
             reader.MoveToContent();
             reader.Read();
             reader.ReadEndElement();
         }
     }
     while (reader.IsStartElement())
     {
         if (!reader.IsStartElement(samlDictionary.AuthorityBinding, samlDictionary.Namespace))
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLBadSchema", new object[] { samlDictionary.AuthenticationStatement })));
         }
         SamlAuthorityBinding item = new SamlAuthorityBinding();
         item.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
         this.authorityBindings.Add(item);
     }
     reader.MoveToContent();
     reader.ReadEndElement();
 }
示例#45
0
 protected SamlSubjectStatement(SamlSubject samlSubject)
 {
     SetSubject(samlSubject);
 }
示例#46
0
		public void SetQualifierEmpty ()
		{
			SamlSubject a = new SamlSubject ();
			a.NameQualifier = String.Empty;
		}
示例#47
0
		public SamlAttributeStatement (SamlSubject samlSubject,
			IEnumerable<SamlAttribute> attributes)
			: base (samlSubject)
		{
			this.attributes = new List<SamlAttribute> (attributes);
		}
        public override void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
        {
            if (reader == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));

            if (samlSerializer == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));

#pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null.
            SamlDictionary dictionary = samlSerializer.DictionaryManager.SamlDictionary;

            string authInstance = reader.GetAttribute(dictionary.AuthenticationInstant, null);
            if (string.IsNullOrEmpty(authInstance))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAuthenticationStatementMissingAuthenticationInstanceOnRead)));
            this.authenticationInstant = DateTime.ParseExact(
                authInstance, SamlConstants.AcceptedDateTimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None).ToUniversalTime();

            this.authenticationMethod = reader.GetAttribute(dictionary.AuthenticationMethod, null);
            if (string.IsNullOrEmpty(this.authenticationMethod))
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAuthenticationStatementMissingAuthenticationMethodOnRead)));

            reader.MoveToContent();
            reader.Read();

            if (reader.IsStartElement(dictionary.Subject, dictionary.Namespace))
            {
                SamlSubject subject = new SamlSubject();
                subject.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
                base.SamlSubject = subject;
            }
            else
            {
                // Subject is a required element for a Authentication Statement clause.
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAuthenticationStatementMissingSubject)));
            }

            if (reader.IsStartElement(dictionary.SubjectLocality, dictionary.Namespace))
            {
                this.dnsAddress = reader.GetAttribute(dictionary.SubjectLocalityDNSAddress, null);
                this.ipAddress = reader.GetAttribute(dictionary.SubjectLocalityIPAddress, null);

                if (reader.IsEmptyElement)
                {
                    reader.MoveToContent();
                    reader.Read();
                }
                else
                {
                    reader.MoveToContent();
                    reader.Read();
                    reader.ReadEndElement();
                }
            }

            while (reader.IsStartElement())
            {
                if (reader.IsStartElement(dictionary.AuthorityBinding, dictionary.Namespace))
                {
                    SamlAuthorityBinding binding = new SamlAuthorityBinding();
                    binding.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
                    this.authorityBindings.Add(binding);
                }
                else
                {
                    // We do not understand this element.
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLBadSchema, dictionary.AuthenticationStatement)));
                }
            }

            reader.MoveToContent();
            reader.ReadEndElement();
        }
        public override void WriteXml(XmlDictionaryWriter writer,
                                      SamlSerializer samlSerializer,
                                      SecurityTokenSerializer keyInfoSerializer)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }
            if (samlSerializer == null)
            {
                throw new ArgumentNullException("samlSerializer");
            }
            if (SamlActions.Count == 0)
            {
                throw new SecurityTokenException("SAML AuthorizationDecisionStatement must contain at least one Action.");
            }

            if (SamlSubject == null)
            {
                throw new SecurityTokenException("SAML Subject must be set to SAML AuthorizationDecisionStatement before being written.");
            }
            if (Resource == null || Resource.Length == 0)
            {
                throw new SecurityTokenException("non-zero string must be set to Resource on SAML AuthorizationDecisionStatement.");
            }

            writer.WriteStartElement("saml", "AuthorizationDecisionStatement", SamlConstants.Namespace);

            writer.WriteStartAttribute("Decision");
            switch (AccessDecision)
            {
            case SamlAccessDecision.Permit:
                writer.WriteString("Permit");
                break;

            case SamlAccessDecision.Deny:
                writer.WriteString("Deny");
                break;

            case SamlAccessDecision.Indeterminate:
                writer.WriteString("Indeterminate");
                break;

            default:
                throw new ArgumentOutOfRangeException("AccessDecision value is wrong.");
            }
            writer.WriteEndAttribute();

            writer.WriteAttributeString("Resource", Resource);
            SamlSubject.WriteXml(writer, samlSerializer, keyInfoSerializer);
            foreach (SamlAction action in SamlActions)
            {
                action.WriteXml(writer, samlSerializer, keyInfoSerializer);
            }
            if (Evidence != null)
            {
                Evidence.WriteXml(writer, samlSerializer, keyInfoSerializer);
            }

            writer.WriteEndElement();
        }
示例#50
0
        public override void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
            }

            if (samlSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));
            }

#pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null.
            SamlDictionary dictionary = samlSerializer.DictionaryManager.SamlDictionary;

            this.resource = reader.GetAttribute(dictionary.Resource, null);
            if (string.IsNullOrEmpty(this.resource))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAuthorizationDecisionStatementMissingResourceAttributeOnRead)));
            }

            string decisionString = reader.GetAttribute(dictionary.Decision, null);
            if (string.IsNullOrEmpty(decisionString))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAuthorizationDecisionStatementMissingDecisionAttributeOnRead)));
            }

            if (decisionString.Equals(SamlAccessDecision.Deny.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                this.accessDecision = SamlAccessDecision.Deny;
            }
            else if (decisionString.Equals(SamlAccessDecision.Permit.ToString(), StringComparison.OrdinalIgnoreCase))
            {
                this.accessDecision = SamlAccessDecision.Permit;
            }
            else
            {
                accessDecision = SamlAccessDecision.Indeterminate;
            }

            reader.MoveToContent();
            reader.Read();

            if (reader.IsStartElement(dictionary.Subject, dictionary.Namespace))
            {
                SamlSubject subject = new SamlSubject();
                subject.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
                base.SamlSubject = subject;
            }
            else
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAuthorizationDecisionStatementMissingSubjectOnRead)));
            }

            while (reader.IsStartElement())
            {
                if (reader.IsStartElement(dictionary.Action, dictionary.Namespace))
                {
                    SamlAction action = new SamlAction();
                    action.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
                    this.actions.Add(action);
                }
                else if (reader.IsStartElement(dictionary.Evidence, dictionary.Namespace))
                {
                    if (this.evidence != null)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAuthorizationDecisionHasMoreThanOneEvidence)));
                    }

                    this.evidence = new SamlEvidence();
                    this.evidence.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLBadSchema, dictionary.AuthorizationDecisionStatement)));
                }
            }

            if (this.actions.Count == 0)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAuthorizationDecisionShouldHaveOneActionOnRead)));
            }

            reader.MoveToContent();
            reader.ReadEndElement();
        }
示例#51
0
        public override void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));
            }
            if (samlSerializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));
            }
            SamlDictionary samlDictionary = samlSerializer.DictionaryManager.SamlDictionary;
            string         attribute      = reader.GetAttribute(samlDictionary.AuthenticationInstant, null);

            if (string.IsNullOrEmpty(attribute))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthenticationStatementMissingAuthenticationInstanceOnRead")));
            }
            this.authenticationInstant = DateTime.ParseExact(attribute, SamlConstants.AcceptedDateTimeFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None).ToUniversalTime();
            this.authenticationMethod  = reader.GetAttribute(samlDictionary.AuthenticationMethod, null);
            if (string.IsNullOrEmpty(this.authenticationMethod))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthenticationStatementMissingAuthenticationMethodOnRead")));
            }
            reader.MoveToContent();
            reader.Read();
            if (!reader.IsStartElement(samlDictionary.Subject, samlDictionary.Namespace))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLAuthenticationStatementMissingSubject")));
            }
            SamlSubject subject = new SamlSubject();

            subject.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
            base.SamlSubject = subject;
            if (reader.IsStartElement(samlDictionary.SubjectLocality, samlDictionary.Namespace))
            {
                this.dnsAddress = reader.GetAttribute(samlDictionary.SubjectLocalityDNSAddress, null);
                this.ipAddress  = reader.GetAttribute(samlDictionary.SubjectLocalityIPAddress, null);
                if (reader.IsEmptyElement)
                {
                    reader.MoveToContent();
                    reader.Read();
                }
                else
                {
                    reader.MoveToContent();
                    reader.Read();
                    reader.ReadEndElement();
                }
            }
            while (reader.IsStartElement())
            {
                if (!reader.IsStartElement(samlDictionary.AuthorityBinding, samlDictionary.Namespace))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(System.IdentityModel.SR.GetString("SAMLBadSchema", new object[] { samlDictionary.AuthenticationStatement })));
                }
                SamlAuthorityBinding item = new SamlAuthorityBinding();
                item.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
                this.authorityBindings.Add(item);
            }
            reader.MoveToContent();
            reader.ReadEndElement();
        }
示例#52
0
        private SecurityToken CreateSAMLToken(DateTime validFrom, DateTime validTo, SecurityKey signingKey, SecurityKeyIdentifier signingKeyIdentifier, SecurityKeyIdentifier proofKeyIdentifier )
        {
            // Create list of confirmation strings.
            List<string> confirmations = new List<string>();

            // Add holder-of-key string to list of confirmation strings.
            confirmations.Add("urn:oasis:names:tc:SAML:1.0:cm:holder-of-key");

            // Create SAML subject statement based on issuer member variable, confirmation string collection 
            // local variable and proof key identifier parameter.
            SamlSubject subject = new SamlSubject(null, null, issuer, confirmations, null, proofKeyIdentifier);

            // Create a list of SAML attributes.
            List<SamlAttribute> attributes = new List<SamlAttribute>();

            // Get the claimset to place into the SAML assertion.
            ClaimSet cs = GetClaimSet();

            // Iterate through the claims and add a SamlAttribute for each claim.
            // Note that GetClaimSet call above returns a claimset that only contains PossessProperty claims.
            foreach (Claim c in cs)
                attributes.Add(new SamlAttribute(c));

            // Create list of SAML statements.
            List<SamlStatement> statements = new List<SamlStatement>();

            // Add a SAML attribute statement to the list of statements. An attribute statement is based on 
            // a subject statement and SAML attributes that result from claims.
            statements.Add(new SamlAttributeStatement(subject, attributes));

            // Create a valid from/until condition.
            SamlConditions conditions = new SamlConditions(validFrom, validTo);
            
            // Create the SAML assertion.
            SamlAssertion assertion = new SamlAssertion("_" + Guid.NewGuid().ToString(), issuer, validFrom, conditions, null, statements);

            // Set the signing credentials for the SAML assertion.
            string signatureAlgorithm = GetSignatureAlgorithm(signingKey);
            assertion.SigningCredentials = new SigningCredentials(signingKey, signatureAlgorithm, SecurityAlgorithms.Sha1Digest, signingKeyIdentifier);

            return new SamlSecurityToken(assertion);
        }
        public override void ReadXml(XmlDictionaryReader reader, SamlSerializer samlSerializer, SecurityTokenSerializer keyInfoSerializer, SecurityTokenResolver outOfBandTokenResolver)
        {
            if (reader == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("reader"));

            if (samlSerializer == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("samlSerializer"));

#pragma warning suppress 56506 // samlSerializer.DictionaryManager is never null.
            SamlDictionary dictionary = samlSerializer.DictionaryManager.SamlDictionary;

            reader.MoveToContent();
            reader.Read();

            if (reader.IsStartElement(dictionary.Subject, dictionary.Namespace))
            {
                SamlSubject subject = new SamlSubject();
                subject.ReadXml(reader, samlSerializer, keyInfoSerializer, outOfBandTokenResolver);
                base.SamlSubject = subject;
            }
            else
            {
                // SAML Subject is a required Attribute Statement clause.
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAttributeStatementMissingSubjectOnRead)));
            }

            while (reader.IsStartElement())
            {
                if (reader.IsStartElement(dictionary.Attribute, dictionary.Namespace))
                {
                    // SAML Attribute is a extensibility point. So ask the SAML serializer 
                    // to load this part.
                    SamlAttribute attribute = samlSerializer.LoadAttribute(reader, keyInfoSerializer, outOfBandTokenResolver);
                    if (attribute == null)
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLUnableToLoadAttribute)));
                    this.attributes.Add(attribute);
                }
                else
                {
                    break;
                }
            }

            if (this.attributes.Count == 0)
            {
                // Each Attribute statement should have at least one attribute.
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenException(SR.GetString(SR.SAMLAttributeStatementMissingAttributeOnRead)));
            }

            reader.MoveToContent();
            reader.ReadEndElement();
        }