public void Validation ()
		{
			Authenticator a = new Authenticator (
				new SecurityTokenAuthenticator [] {
					new CustomUserNameSecurityTokenAuthenticator (UserNamePasswordValidator.None),
					new X509SecurityTokenAuthenticator (X509CertificateValidator.None),
					});
			PolicyCollection pl = a.ValidateToken (GetSamlToken ());
			Assert.AreEqual (1, pl.Count, "#1");
			IAuthorizationPolicy p = pl [0];
			Assert.AreEqual (ClaimSet.System, p.Issuer, "#2");
			TestEvaluationContext ec = new TestEvaluationContext ();
			object o = null;
			Assert.IsTrue (p.Evaluate (ec, ref o), "#3");
			Assert.AreEqual (DateTime.MaxValue.AddDays (-1), ec.ExpirationTime, "#4");
			IList<IIdentity> identities = ec.Properties ["Identities"] as IList<IIdentity>;
			Assert.IsNotNull (identities, "#5");
			Assert.AreEqual (1, identities.Count, "#6");
			IIdentity ident = identities [0];
			Assert.AreEqual (true, ident.IsAuthenticated, "#6-2");
			// it's implementation details.
			//Assert.AreEqual ("NoneUserNamePasswordValidator", ident.AuthenticationType, "#6-3");
			Assert.AreEqual ("mono", ident.Name, "#6-4");
			Assert.AreEqual (1, ec.ClaimSets.Count, "#7");

			Assert.IsTrue (p.Evaluate (ec, ref o), "#8");
			identities = ec.Properties ["Identities"] as IList<IIdentity>;
			Assert.AreEqual (2, identities.Count, "#9");
			Assert.AreEqual (2, ec.ClaimSets.Count, "#10");
		}
Ejemplo n.º 2
0
        public void Validation()
        {
            Authenticator a = new Authenticator(
                new SecurityTokenAuthenticator [] {
                new CustomUserNameSecurityTokenAuthenticator(UserNamePasswordValidator.None),
                new X509SecurityTokenAuthenticator(X509CertificateValidator.None),
            });
            PolicyCollection pl = a.ValidateToken(GetSamlToken());

            Assert.AreEqual(1, pl.Count, "#1");
            IAuthorizationPolicy p = pl [0];

            Assert.AreEqual(ClaimSet.System, p.Issuer, "#2");
            TestEvaluationContext ec = new TestEvaluationContext();
            object o = null;

            Assert.IsTrue(p.Evaluate(ec, ref o), "#3");
            Assert.AreEqual(DateTime.MaxValue.AddDays(-1), ec.ExpirationTime, "#4");
            IList <IIdentity> identities = ec.Properties ["Identities"] as IList <IIdentity>;

            Assert.IsNotNull(identities, "#5");
            Assert.AreEqual(1, identities.Count, "#6");
            IIdentity ident = identities [0];

            Assert.AreEqual(true, ident.IsAuthenticated, "#6-2");
            // it's implementation details.
            //Assert.AreEqual ("NoneUserNamePasswordValidator", ident.AuthenticationType, "#6-3");
            Assert.AreEqual("mono", ident.Name, "#6-4");
            Assert.AreEqual(1, ec.ClaimSets.Count, "#7");

            Assert.IsTrue(p.Evaluate(ec, ref o), "#8");
            identities = ec.Properties ["Identities"] as IList <IIdentity>;
            Assert.AreEqual(2, identities.Count, "#9");
            Assert.AreEqual(2, ec.ClaimSets.Count, "#10");
        }
 public override IAuthorizationPolicy CreatePolicy(ClaimSet issuer, SamlSecurityTokenAuthenticator samlAuthenticator)
 {
     if (issuer == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("issuer");
     }
     if (this.policy == null)
     {
         List<ClaimSet> list = new List<ClaimSet>();
         ClaimSet item = this.subject.ExtractSubjectKeyClaimSet(samlAuthenticator);
         if (item != null)
         {
             list.Add(item);
         }
         List<Claim> claims = new List<Claim>();
         ReadOnlyCollection<Claim> onlys = this.subject.ExtractClaims();
         for (int i = 0; i < onlys.Count; i++)
         {
             claims.Add(onlys[i]);
         }
         this.AddClaimsToList(claims);
         list.Add(new DefaultClaimSet(issuer, claims));
         this.policy = new UnconditionalPolicy(this.subject.Identity, list.AsReadOnly(), System.IdentityModel.SecurityUtils.MaxUtcDateTime);
     }
     return this.policy;
 }
        public override IAuthorizationPolicy CreatePolicy(ClaimSet issuer, SamlSecurityTokenAuthenticator samlAuthenticator)
        {
            if (issuer == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("issuer");

            // SupportingTokenAuthenticator collection can be null when the Subject does not
            // contain a key.

            if (this.policy == null)
            {
                List<ClaimSet> claimSets = new List<ClaimSet>();
                ClaimSet subjectKeyClaimset = this.subject.ExtractSubjectKeyClaimSet(samlAuthenticator);
                if (subjectKeyClaimset != null)
                    claimSets.Add(subjectKeyClaimset);

                List<Claim> claims = new List<Claim>();
                ReadOnlyCollection<Claim> subjectClaims = this.subject.ExtractClaims();
                for (int i = 0; i < subjectClaims.Count; ++i)
                {
                    claims.Add(subjectClaims[i]);
                }

                AddClaimsToList(claims);
                claimSets.Add(new DefaultClaimSet(issuer, claims));
                this.policy = new UnconditionalPolicy(this.subject.Identity, claimSets.AsReadOnly(), SecurityUtils.MaxUtcDateTime);
            }

            return this.policy;
        }
 private SamlSecurityTokenAuthenticator CreateSamlTokenAuthenticator(RecipientServiceModelSecurityTokenRequirement recipientRequirement, out SecurityTokenResolver outOfBandTokenResolver)
 {
     SamlSecurityTokenAuthenticator authenticator;
     if (recipientRequirement == null)
     {
         throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("recipientRequirement");
     }
     Collection<SecurityToken> collection = new Collection<SecurityToken>();
     if (this.parent.ServiceCertificate.Certificate != null)
     {
         collection.Add(new X509SecurityToken(this.parent.ServiceCertificate.Certificate));
     }
     List<SecurityTokenAuthenticator> supportingAuthenticators = new List<SecurityTokenAuthenticator>();
     if ((this.parent.IssuedTokenAuthentication.KnownCertificates != null) && (this.parent.IssuedTokenAuthentication.KnownCertificates.Count > 0))
     {
         for (int i = 0; i < this.parent.IssuedTokenAuthentication.KnownCertificates.Count; i++)
         {
             collection.Add(new X509SecurityToken(this.parent.IssuedTokenAuthentication.KnownCertificates[i]));
         }
     }
     X509CertificateValidator certificateValidator = this.parent.IssuedTokenAuthentication.GetCertificateValidator();
     supportingAuthenticators.Add(new X509SecurityTokenAuthenticator(certificateValidator));
     if (this.parent.IssuedTokenAuthentication.AllowUntrustedRsaIssuers)
     {
         supportingAuthenticators.Add(new RsaSecurityTokenAuthenticator());
     }
     outOfBandTokenResolver = (collection.Count > 0) ? SecurityTokenResolver.CreateDefaultSecurityTokenResolver(new ReadOnlyCollection<SecurityToken>(collection), false) : null;
     if ((recipientRequirement.SecurityBindingElement == null) || (recipientRequirement.SecurityBindingElement.LocalServiceSettings == null))
     {
         authenticator = new SamlSecurityTokenAuthenticator(supportingAuthenticators);
     }
     else
     {
         authenticator = new SamlSecurityTokenAuthenticator(supportingAuthenticators, recipientRequirement.SecurityBindingElement.LocalServiceSettings.MaxClockSkew);
     }
     authenticator.AudienceUriMode = this.parent.IssuedTokenAuthentication.AudienceUriMode;
     IList<string> allowedAudienceUris = authenticator.AllowedAudienceUris;
     if (this.parent.IssuedTokenAuthentication.AllowedAudienceUris != null)
     {
         for (int j = 0; j < this.parent.IssuedTokenAuthentication.AllowedAudienceUris.Count; j++)
         {
             allowedAudienceUris.Add(this.parent.IssuedTokenAuthentication.AllowedAudienceUris[j]);
         }
     }
     if (recipientRequirement.ListenUri != null)
     {
         allowedAudienceUris.Add(recipientRequirement.ListenUri.AbsoluteUri);
     }
     return authenticator;
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Token Constructor
        /// </summary>
        /// <param name="xmlToken">Encrypted xml token</param>
        public Token(String xmlToken)
        {
            byte[] decryptedData = decryptToken(xmlToken);

            XmlReader reader = new XmlTextReader(new StreamReader(new MemoryStream(decryptedData), Encoding.UTF8));
            m_token = (SamlSecurityToken)WSSecurityTokenSerializer.DefaultInstance.ReadToken(reader, null);

            SamlSecurityTokenAuthenticator authenticator = new SamlSecurityTokenAuthenticator(new List<SecurityTokenAuthenticator>(
                                                            new SecurityTokenAuthenticator[]{
                                                                new RsaSecurityTokenAuthenticator(),
                                                                new X509SecurityTokenAuthenticator() }), MaximumTokenSkew);

            if (authenticator.CanValidateToken(m_token))
            {
                ReadOnlyCollection<IAuthorizationPolicy> policies = authenticator.ValidateToken(m_token);
                m_authorizationContext = AuthorizationContext.CreateDefaultAuthorizationContext(policies);
                FindIdentityClaims();
            }
            else
            {
                throw new Exception("Unable to validate the token.");
            }
        }
 public abstract IAuthorizationPolicy CreatePolicy(ClaimSet issuer, SamlSecurityTokenAuthenticator samlAuthenticator);
 public virtual ClaimSet ExtractSubjectKeyClaimSet(SamlSecurityTokenAuthenticator samlAuthenticator)
 {
     if ((this.subjectKeyClaimset == null) && (this.securityKeyIdentifier != null))
     {
         if (samlAuthenticator == null)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("samlAuthenticator");
         }
         if (this.subjectToken != null)
         {
             this.subjectKeyClaimset = samlAuthenticator.ResolveClaimSet(this.subjectToken);
             this.identity = samlAuthenticator.ResolveIdentity(this.subjectToken);
             if ((this.identity == null) && (this.subjectKeyClaimset != null))
             {
                 Claim claim = null;
                 foreach (Claim claim2 in this.subjectKeyClaimset.FindClaims(null, Rights.Identity))
                 {
                     claim = claim2;
                     break;
                 }
                 if (claim != null)
                 {
                     this.identity = System.IdentityModel.SecurityUtils.CreateIdentity(claim.Resource.ToString(), base.GetType().Name);
                 }
             }
         }
         if (this.subjectKeyClaimset == null)
         {
             this.subjectKeyClaimset = samlAuthenticator.ResolveClaimSet(this.securityKeyIdentifier);
             this.identity = samlAuthenticator.ResolveIdentity(this.securityKeyIdentifier);
         }
     }
     return this.subjectKeyClaimset;
 }
Ejemplo n.º 9
0
		/// <summary>
		/// Token Authentication.  Translates the decrypted data into a AuthContext.
		/// </summary>
		/// <param name="reader">The token XML reader.</param>
		/// <param name="audience">The audience that the token must be scoped for.
		/// Use <c>null</c> to indicate any audience is acceptable.</param>
		/// <returns>
		/// The authorization context carried by the token.
		/// </returns>
		internal static AuthorizationContext AuthenticateToken(XmlReader reader, Uri audience) {
			Contract.Ensures(Contract.Result<AuthorizationContext>() != null);

			// Extensibility Point:
			// in order to accept different token types, you would need to add additional 
			// code to create an authenticationcontext from the security token. 
			// This code only supports SamlSecurityToken objects.
			SamlSecurityToken token = WSSecurityTokenSerializer.DefaultInstance.ReadToken(reader, null) as SamlSecurityToken;

			if (null == token) {
				throw new InformationCardException("Unable to read security token");
			}

			if (null != token.SecurityKeys && token.SecurityKeys.Count > 0) {
				throw new InformationCardException("Token Security Keys Exist");
			}

			if (audience == null) {
				Logger.InfoCard.Warn("SAML token Audience checking will be skipped.");
			} else {
				if (token.Assertion.Conditions != null &&
					token.Assertion.Conditions.Conditions != null) {
					foreach (SamlCondition condition in token.Assertion.Conditions.Conditions) {
						SamlAudienceRestrictionCondition audienceCondition = condition as SamlAudienceRestrictionCondition;

						if (audienceCondition != null) {
							Logger.InfoCard.DebugFormat("SAML token audience(s): {0}", audienceCondition.Audiences.ToStringDeferred());
							bool match = audienceCondition.Audiences.Contains(audience);

							if (!match && Logger.InfoCard.IsErrorEnabled) {
								Logger.InfoCard.ErrorFormat("Expected SAML token audience of {0} but found {1}.", audience.AbsoluteUri, audienceCondition.Audiences.Select(aud => aud.AbsoluteUri).ToStringDeferred());
							}

							// The token is invalid if any condition is not valid. 
							// An audience restriction condition is valid if any audience 
							// matches the Relying Party.
							InfoCardErrorUtilities.VerifyInfoCard(match, InfoCardStrings.AudienceMismatch);
						}
					}
				}
			}
			var samlAuthenticator = new SamlSecurityTokenAuthenticator(
				new List<SecurityTokenAuthenticator>(
					new SecurityTokenAuthenticator[] {
						new RsaSecurityTokenAuthenticator(),
						new X509SecurityTokenAuthenticator(),
				}),
				MaximumClockSkew);

			return AuthorizationContext.CreateDefaultAuthorizationContext(samlAuthenticator.ValidateToken(token));
		}
Ejemplo n.º 10
0
        private void ParseToken(string xmlToken, X509Certificate2 cert)
        {
            int skew = 300; // default to 5 minutes
            string tokenskew = System.Configuration.ConfigurationManager.AppSettings["MaximumClockSkew"];
            if (!string.IsNullOrEmpty(tokenskew))
                skew = Int32.Parse(tokenskew);

            XmlReader tokenReader = new XmlTextReader(new StringReader(xmlToken));
            EncryptedData enc = new EncryptedData();

            enc.TokenSerializer = WSSecurityTokenSerializer.DefaultInstance;

            enc.ReadFrom(tokenReader);

            List<SecurityToken> tokens = new List<SecurityToken>();
            SecurityToken encryptingToken = new X509SecurityToken(cert);
            tokens.Add(encryptingToken);

            SecurityTokenResolver tokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(tokens.AsReadOnly(), false);
            SymmetricSecurityKey encryptingCrypto;

            // an error here usually means that you have selected the wrong key.
            encryptingCrypto = (SymmetricSecurityKey)tokenResolver.ResolveSecurityKey(enc.KeyIdentifier[0]);

            SymmetricAlgorithm algorithm = encryptingCrypto.GetSymmetricAlgorithm(enc.EncryptionMethod);

            byte[] decryptedData = enc.GetDecryptedBuffer(algorithm);

            SecurityTokenSerializer tokenSerializer = WSSecurityTokenSerializer.DefaultInstance;
            XmlReader reader = new XmlTextReader(new StreamReader(new MemoryStream(decryptedData), Encoding.UTF8));

            m_token = (SamlSecurityToken)tokenSerializer.ReadToken(reader, tokenResolver);

            SamlSecurityTokenAuthenticator authenticator = new SamlSecurityTokenAuthenticator(new List<SecurityTokenAuthenticator>(
                                                            new SecurityTokenAuthenticator[]{
                                                                new RsaSecurityTokenAuthenticator(),
                                                                new X509SecurityTokenAuthenticator() }), new TimeSpan(0, 0, skew));

            if (authenticator.CanValidateToken(m_token))
            {
                ReadOnlyCollection<IAuthorizationPolicy> policies = authenticator.ValidateToken(m_token);
                m_authorizationContext = AuthorizationContext.CreateDefaultAuthorizationContext(policies);
                m_identityClaims = FindIdentityClaims(m_authorizationContext);
            }
            else
            {
                throw new Exception("Unable to validate the token.");
            }
        }
        SamlSecurityTokenAuthenticator CreateSamlTokenAuthenticator(RecipientServiceModelSecurityTokenRequirement recipientRequirement, out SecurityTokenResolver outOfBandTokenResolver)
        {
            if (recipientRequirement == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("recipientRequirement");

            Collection<SecurityToken> outOfBandTokens = new Collection<SecurityToken>();
            if (parent.ServiceCertificate.Certificate != null)
            {
                outOfBandTokens.Add(new X509SecurityToken(parent.ServiceCertificate.Certificate));
            }
            List<SecurityTokenAuthenticator> supportingAuthenticators = new List<SecurityTokenAuthenticator>();
            if ((parent.IssuedTokenAuthentication.KnownCertificates != null) && (parent.IssuedTokenAuthentication.KnownCertificates.Count > 0))
            {
                for (int i = 0; i < parent.IssuedTokenAuthentication.KnownCertificates.Count; ++i)
                {
                    outOfBandTokens.Add(new X509SecurityToken(parent.IssuedTokenAuthentication.KnownCertificates[i]));
                }
            }

            X509CertificateValidator validator = parent.IssuedTokenAuthentication.GetCertificateValidator();
            supportingAuthenticators.Add(new X509SecurityTokenAuthenticator(validator));

            if (parent.IssuedTokenAuthentication.AllowUntrustedRsaIssuers)
            {
                supportingAuthenticators.Add(new RsaSecurityTokenAuthenticator());
            }

            outOfBandTokenResolver = (outOfBandTokens.Count > 0) ? SecurityTokenResolver.CreateDefaultSecurityTokenResolver(new ReadOnlyCollection<SecurityToken>(outOfBandTokens), false) : null;

            SamlSecurityTokenAuthenticator ssta;

            if ((recipientRequirement.SecurityBindingElement == null) || (recipientRequirement.SecurityBindingElement.LocalServiceSettings == null))
            {
                ssta = new SamlSecurityTokenAuthenticator(supportingAuthenticators);
            }
            else
            {
                ssta = new SamlSecurityTokenAuthenticator(supportingAuthenticators, recipientRequirement.SecurityBindingElement.LocalServiceSettings.MaxClockSkew);
            }

            // set audience uri restrictions
            ssta.AudienceUriMode = parent.IssuedTokenAuthentication.AudienceUriMode;
            IList<string> allowedAudienceUris = ssta.AllowedAudienceUris;
            if (parent.IssuedTokenAuthentication.AllowedAudienceUris != null)
            {
                for (int i = 0; i < parent.IssuedTokenAuthentication.AllowedAudienceUris.Count; i++)
                    allowedAudienceUris.Add(parent.IssuedTokenAuthentication.AllowedAudienceUris[i]);
            }

            if (recipientRequirement.ListenUri != null)
            {
                allowedAudienceUris.Add(recipientRequirement.ListenUri.AbsoluteUri);
            }

            return ssta;
        }
Ejemplo n.º 12
0
		public virtual ClaimSet ExtractSubjectKeyClaimSet (
			SamlSecurityTokenAuthenticator samlAuthenticator)
		{
			throw new NotImplementedException ();
		}
Ejemplo n.º 13
0
		public override IAuthorizationPolicy CreatePolicy (
			ClaimSet issuer, SamlSecurityTokenAuthenticator samlAuthenticator)
		{
			throw new NotImplementedException ();
		}
Ejemplo n.º 14
0
        /// <summary>
        /// Token Authentication. Translates the decrypted data into a AuthContext
        /// 
        /// This method makes a strong assumption that the decrypted token in in UTF-8 format.
        /// </summary>
        /// <param name="decryptedTokenData">Decrypted token</param>
        public static AuthorizationContext AuthenticateToken(byte[] decryptedTokenData)
        {
            string t = Encoding.UTF8.GetString(decryptedTokenData);
            XmlReader reader = new XmlTextReader(new StreamReader(new MemoryStream(decryptedTokenData), Encoding.UTF8));

            // Extensibility Point:
            // in order to accept different token types, you would need to add additional
            // code to create an authenticationcontext from the security token.
            // This code only supports SamlSecurityToken objects.
            SamlSecurityToken token = WSSecurityTokenSerializer.DefaultInstance.ReadToken(reader, null) as SamlSecurityToken;

            if( null == token )
                throw new InformationCardException("Unable to read security token");

            if (null != token.SecurityKeys && token.SecurityKeys.Count > 0)
                throw new InformationCardException("Token Security Keys Exist");

            if (null != _audience &&
                 null != token.Assertion.Conditions &&
                 null != token.Assertion.Conditions.Conditions)
            {
                foreach (SamlCondition condition in token.Assertion.Conditions.Conditions)
                {
                    SamlAudienceRestrictionCondition audienceCondition = condition as SamlAudienceRestrictionCondition;

                    if (null != audienceCondition)
                    {
                        bool match = false;

                        foreach (Uri audience in audienceCondition.Audiences)
                        {
                            match = audience.Equals(_audience);
                            if (match) break;
                        }

                        //
                        // The token is invalid if any condition is not valid.
                        // An audience restriction condition is valid if any audience
                        // matches the Relying Party.
                        //
                        if (!match)
                        {
                            throw new InformationCardException("The token is invalid: The audience restrictions does not match the Relying Party.");
                        }
                    }
                }
            }
            /*SamlSecurityTokenAuthenticator SamlAuthenticator = new SamlSecurityTokenAuthenticator(new List<SecurityTokenAuthenticator>(
                                            new SecurityTokenAuthenticator[]{
                                                new RsaSecurityTokenAuthenticator(),
                                                new X509SecurityTokenAuthenticator() }), MaximumTokenSkew);*/
            SamlSecurityTokenAuthenticator SamlAuthenticator = new SamlSecurityTokenAuthenticator(new List<SecurityTokenAuthenticator>(
                                            new SecurityTokenAuthenticator[]{
                                                new RsaSecurityTokenAuthenticator(),
                                                new X509SecurityTokenAuthenticator(X509CertificateValidator.None) }), MaximumTokenSkew);

            return AuthorizationContext.CreateDefaultAuthorizationContext(SamlAuthenticator.ValidateToken(token));
        }
Ejemplo n.º 15
0
			public SamlAuthorizationPolicy (SamlSecurityTokenAuthenticator authenticator, SamlSecurityToken token)
				: base (new UniqueId ().ToString ())
			{
				this.authenticator = authenticator;
				this.token = token;
			}