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");
		}
Пример #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");
        }
Пример #3
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.");
            }
        }
Пример #4
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));
		}
        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.");
            }
        }
Пример #6
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));
        }