/// <summary>
        /// Overrides the base class. Validates the given issuer token. For a incoming SAML token
        /// the issuer token is the Certificate that signed the SAML token.
        /// </summary>
        /// <param name="securityToken">Issuer token to be validated.</param>
        /// <returns>Friendly name representing the Issuer.</returns>
        public override string GetIssuerName(SecurityToken securityToken)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("IdpAds.IdpAdsIssuerNameRegistry.GetIssuerName",
                "MyTraceSource", SourceLevels.Information);

            //TraceSource ts = new TraceSource("System.ServiceModel");

            X509SecurityToken x509Token = securityToken as X509SecurityToken;
            if (x509Token != null)
            {
                // Warning: This sample does a simple compare of the Issuer Certificate
                // to a subject name. This is not appropriate for production use. 
                // Check your validation policy and authenticate issuers based off the policy.

                string commonName = x509Token.Certificate.GetNameInfo(X509NameType.SimpleName, false);

                ts.TraceInformation("Certificate CN: " + commonName);

                // TODO: Why this is different in the 
                if (CertificateUtil.ValidateCertificate(StoreName.TrustedPeople, StoreLocation.LocalMachine, x509Token.Certificate))
                {
                    ts.TraceInformation("Certificate VALID");

                    return x509Token.Certificate.SubjectName.Name;
                }
            }

            ts.TraceInformation("Untrusted issuer");

            throw new SecurityTokenException("Untrusted issuer.");
        }
        /// <summary>
        /// Overrides the base class. Validates the given issuer token. For a incoming SAML token
        /// the issuer token is the Certificate that signed the SAML token.
        /// </summary>
        /// <param name="securityToken">Issuer token to be validated.</param>
        /// <returns>Friendly name representing the Issuer.</returns>
        public override string GetIssuerName(SecurityToken securityToken)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("IdentityProviderSts.IdentityProviderIssuerNameRegistry.GetIssuerName",
                "MyTraceSource", SourceLevels.Information);

            X509SecurityToken x509Token = securityToken as X509SecurityToken;
            if (x509Token != null)
            {
                // Warning: This sample does a simple compare of the Issuer Certificate
                // to a subject name. This is not appropriate for production use. 
                // Check your validation policy and authenticate issuers based off the policy.
                
                string commonName = x509Token.Certificate.GetNameInfo(X509NameType.SimpleName, false);

                ts.TraceInformation("Certificate CN: " + commonName);

                //if (String.Equals(x509Token.Certificate.SubjectName.Name, "O=CA for Ref GFIPM, [email protected], C=US, S=GA, CN=Reference GFIPM Federation") ||
                //    String.Equals(x509Token.Certificate.SubjectName.Name, "O=CISA, C=US, S=GA, CN=cisaidp.swbs.gtri.gatech.edu"))
                //if (String.Equals(x509Token.Certificate.SubjectName.Name, "O=CISA, C=US, S=GA, CN=cisaidp.swbs.gtri.gatech.edu"))
                if (String.Equals(commonName.ToUpper(), "HA50IDP"))
                {
                    return x509Token.Certificate.SubjectName.Name;
                }
            }

            ts.TraceInformation("Untrusted issuer");

            throw new SecurityTokenException("Untrusted issuer.");
        }
        /// <summary>
        /// Overrides the base class. Validates the given issuer token. For a incoming SAML token
        /// the issuer token is the Certificate that signed the SAML token.
        /// </summary>
        /// <param name="securityToken">Issuer token to be validated.</param>
        /// <returns>Friendly name representing the Issuer.</returns>
        public override string GetIssuerName(SecurityToken securityToken)
        {
            Common.CustomTextTraceSource ts = new Common.CustomTextTraceSource("CommercialVehicleCollisionWebservice.WspTrustedIssuerNameRegistry.GetIssuerName",
                "MyTraceSource", SourceLevels.Information);

            
            X509SecurityToken x509Token = securityToken as X509SecurityToken;
            if (x509Token != null)
            {
                // Warning: This sample does a simple compare of the Issuer Certificate
                // to a subject name. This is not appropriate for production use. 
                // Check your validation policy and authenticate issuers based off the policy.

                ts.TraceInformation("IssuerName: " + x509Token.Certificate.SubjectName.Name);

                string commonName = x509Token.Certificate.GetNameInfo(X509NameType.SimpleName, false);
                ts.TraceInformation("CommonName: " + commonName);

                if (CertificateUtil.ValidateCertificate(StoreName.TrustedPeople, StoreLocation.LocalMachine, x509Token.Certificate))
                {
                    ts.TraceInformation("Certificate is valid");

                    return x509Token.Certificate.SubjectName.Name;
                }
                else
                {
                    ts.TraceInformation("Certificate is NOT VALID");
                }
            }

            throw new SecurityTokenException("Untrusted issuer.");            
        }
        /// <summary>
        /// Loads the policies from policies store
        /// </summary>
        void LoadAuthorizationPolicies()
        {
            Expression<Func<AuthorizationContext, bool>> policyExpression;

            CustomTextTraceSource ts = new CustomTextTraceSource("WebServiceProviderHost.WspServiceAuthorizationManager.LoadAuthorizationPolicies",
                "MyTraceSource", SourceLevels.Information);

            IEnumerable<XElement> nodes = GetWspAuthorizationPolicy();

            ts.TraceInformation("IEnumerable<XElement> Node Count: {0}", nodes.Count() );

            foreach (XElement xElem in nodes)
            {
                // Initialize the policy store
                XmlDictionaryReader reader = XmlDictionaryReader.CreateDictionaryReader(new XmlTextReader(new StringReader(xElem.ToString())));
                reader.MoveToContent();

                string action = reader.GetAttribute("action");

                ts.TraceInformation("Node Action: {0}", action);

                policyExpression = _policyReader.ReadPolicy(reader);

                // Compile the policy expression into a function
                Func<AuthorizationContext, bool> policy = policyExpression.Compile();
                                
                // Insert the policy function into the policy cache
                _policies[action] = policy;
            }
        }
        //private HttpTransportBindingElement _httpTransportBindingElement = null;

        public WspCustomSecuredBinding( bool enableStrTransform)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("Common.WspCustomSecuredBinding.WspCustomSecuredBinding",
               "MyTraceSource", System.Diagnostics.SourceLevels.Information);

            ts.TraceInformation("enableStrTransform = " + enableStrTransform.ToString());

            this._enableStrTransform = enableStrTransform;

            Initialize();
        }
Exemplo n.º 6
0
        private static void logClaimsIdentity(IClaimsIdentity ci, CustomTextTraceSource ts)
        {
            ts.TraceInformation("claimsIdentity: " + ci.Name);
            foreach (Claim c in ci.Claims)
            {
                ts.TraceInformation("Claim: <{0}, {1}>", c.ClaimType, c.Value);
            }

            // delegate
            if ( ci.Actor != null )
            {
                ts.TraceInformation("\nDelegate:");
                logClaimsIdentity(ci.Actor, ts);
            }
        }
        void WriteMessageToLog(string methodName, Message msg)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("WebServiceProvider.WspServiceAuthorizationManager." + methodName,
                "MyTraceSource", SourceLevels.Information);

            if (msg != null)
            {
                ts.TraceInformation("Message:");
                ts.TraceInformation(msg.ToString());
            }
            else
            {
                ts.TraceInformation("Message == NULL");
            }
        }
        void LogMessage(string methodName, Message msg)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("Common.CustomMessageInspector." + methodName,
                "MyTraceSource", SourceLevels.Information);

            if (msg != null)
            {
                ts.TraceInformation("Message:");
                ts.TraceInformation(msg.ToString());
            }
            else
            {
                ts.TraceInformation("Message is NULL");
            }
        }
Exemplo n.º 9
0
        public getDocumentResponse getDocument(getDocumentRequest request)
        {

            Common.CustomTextTraceSource ts = new Common.CustomTextTraceSource("WebServiceConsumer.WebServiceConsumer.getDocument",
                "MyTraceSource", SourceLevels.Information);

            ICommercialVehicleCollisionPortTypeChannel channel = GetClientProxyChannel();
            try
            {            
                // Use the 'client' variable to call operations on the service.
                getDocumentResponse resp = channel.getDocument(request);

                channel.Close();

                return resp;
            }
            catch (FaultException)
            {
                channel.Abort();
                throw;
            }
            catch (CommunicationException)
            {
                channel.Abort();
                throw;
            }
            catch (TimeoutException)
            {
                channel.Abort();
                throw;
            }
            catch (Exception e)
            {
                ts.TraceInformation("Exception: " + e.Message);
                if (e.InnerException != null)
                {
                    ts.TraceInformation("InnerException: " + e.InnerException.Message);
                }

                channel.Abort();

                throw;
            }
        }
Exemplo n.º 10
0
        public static void LogClaimsIdentity(IClaimsIdentity ci, string fromMethod)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource(fromMethod, "MyTraceSource", System.Diagnostics.SourceLevels.Information);

            try
            {
                ts.TraceInformation("Method {0}", fromMethod);

                logClaimsIdentity(ci, ts);
            }
            catch (Exception e)
            {
                ts.TraceInformation("Exception:" + e.Message);
                if (e.InnerException != null)
                {
                    ts.TraceInformation("\tInnerException:" + e.InnerException.Message);
                }
            }
       }
Exemplo n.º 11
0
        public static void LogClaimsPrincipal(IClaimsPrincipal cp, string fromMethod)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource(fromMethod, "MyTraceSource", System.Diagnostics.SourceLevels.Information);

            try
            {
                ts.TraceEvent(TraceEventType.Information, 1, "Number of Identities for Main Principal {0} is {1} ", cp.Identity.Name, cp.Identities.Count);

                logPrincipal(cp, ts);         
            }
            catch (Exception e)
            {
                ts.TraceInformation("Exception:" + e.Message);
                if (e.InnerException != null)
                {
                    ts.TraceInformation("\tInnerException:" + e.InnerException.Message);
                }
            }
        }
Exemplo n.º 12
0
        public List<Claim> GetClaims(string userIdentity)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("IdpSts.UserAttributeStoreMgr.GetClaims",
                "MyTraceSource", SourceLevels.Information);

            var root = GetUserAttributes();

            IEnumerable<XElement> entry =
                from e1 in root.Elements("User")
                where (string)e1.Attribute("userName") == userIdentity
                select e1;

            ts.TraceInformation("User Count: " + entry.Count());

            if (entry.Count() != 0)
            {
                IEnumerable<XElement> entry2 =
                from e2 in entry.Elements("Attribute")
                select e2;

                ts.TraceInformation("User Attributes Count: " + entry2.Count());

                List<Claim> userClaims = new List<Claim>();

                foreach (XElement claimElem in entry2)
                {
                    Claim claim = CreateClaim(claimElem.Attribute("URI").Value, claimElem.Attribute("Value").Value, 
                        claimElem.Attribute("claimPropertyURI").Value, claimElem.Attribute("claimProperty").Value);

                    userClaims.Add(claim);
                }

                return userClaims;
            }

            return null;
        }
        public override void Validate(X509Certificate2 certificate)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("Common.CustomX509CertificateValidator.Validate",
                "MyTraceSource", SourceLevels.Information);

            // Check that there is a certificate.
            if (certificate == null)
            {
                ts.TraceInformation("null certificate");
                throw new ArgumentNullException("certificate");
            }

            if (CertificateUtil.ValidateCertificate(StoreName.TrustedPeople, StoreLocation.LocalMachine, certificate))
            {
                ts.TraceInformation("Certificate <" + certificate.SubjectName.Name + "> is trusted.");
                return;
            }

        
            // Only accept self-issued certificates
            ts.TraceInformation("Certificate <" + certificate.SubjectName.Name + "> is not trusted.");

            throw new Exception("Certificate <" + certificate.SubjectName.Name + "> is not trusted.");
        }
        private IEnumerable<XElement> GetWspAuthorizationPolicy()
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("WebServiceProviderHost.WspServiceAuthorizationManager.GetWspAuthorizationPolicy",
               "MyTraceSource", SourceLevels.Information);

            try
            {
                Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("WebServiceProviderHost.WspAuthorizationPolicyStore.xml");

                XElement root = XElement.Load(stream);

                return root.Elements();
            }
            catch (Exception e)
            {
                ts.TraceInformation("Error: " + e.Message);
                if (e.InnerException != null)
                {
                    ts.TraceInformation("\tInner Error: " + e.InnerException.Message);
                }

                throw;
            }
        }
        void SerializeTokenToStream(Saml2SecurityToken saml2Token, CustomTextTraceSource ts, string section)
        {
            // serialize the token
            ts.TraceInformation(section);

            if (saml2Token.Assertion.Issuer != null)
            {
                ts.TraceInformation("\tIssuer: " + saml2Token.Assertion.Issuer.Value);
            }
            else
            {
                ts.TraceInformation("Saml 2 Assertion Issuer: NULL");
            }

            if (saml2Token.Assertion.Issuer != null)
            {
                ts.TraceInformation("\tSigningCredentials: " + saml2Token.Assertion.SigningCredentials.ToString());
            }
            else
            {
                ts.TraceInformation("Saml 2 Assertion SigningCredentials: NULL");
            }

            if (saml2Token.Assertion.Subject != null)
            {
                if (saml2Token.Assertion.Subject.NameId != null)
                {
                    ts.TraceInformation("\tSubject NameId: " + saml2Token.Assertion.Subject.NameId.Value);
                }
                else
                {
                    ts.TraceInformation("\tSubject NameId: NULL");
                }
            }
            else
            {
                ts.TraceInformation("Saml 2 Assertion Subject: NULL");
            }

            ts.TraceInformation("Saml Token:\n");

            ts.TraceInformation(TokenToString(saml2Token));

        }
        // Looks like this is called for HOK tokens, so why it is called for the SV token?????
        // This is called by ReadToken and this will be needed in order to support other confirmation methods
        protected override ReadOnlyCollection<SecurityKey> ResolveSecurityKeys(Saml2Assertion assertion, SecurityTokenResolver resolver)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("CommercialVehicleCollisionWebservice.CustomSaml2SecurityTokenHandler.ResolveSecurityKeys",
                   "MyTraceSource", SourceLevels.Information);

            // In model 2, the SAML assertion is , by design, always using the 
            // sender-vouches confirmation method so we always return an empty collection
            return new ReadOnlyCollection<SecurityKey>(new SecurityKey[0]);

            #region Modify to include Holder-of-Key and Bearer
            //Saml2Subject subject = assertion.Subject;
            //if (subject == null)
            //{
            //    throw new SecurityTokenException("null Saml2Subject");
            //}
            //if (subject.SubjectConfirmations.Count == 0)
            //{
            //    throw new SecurityTokenException("Empty SubjectConfirmations");
            //}
            //if (subject.SubjectConfirmations.Count > 1)
            //{
            //    throw new SecurityTokenException("More than 1 SubjectConfirmations");
            //}

            //Saml2SubjectConfirmation confirmation = subject.SubjectConfirmations[0];

            //// enable sender-vouches confirmation method 
            //if (Saml2Constants.ConfirmationMethods.Bearer == confirmation.Method || Saml2Constants.ConfirmationMethods.SenderVouches == confirmation.Method)
            //{
            //    if ((confirmation.SubjectConfirmationData != null) && (confirmation.SubjectConfirmationData.KeyIdentifiers.Count != 0))
            //    {
            //        throw DiagnosticUtil.ExceptionUtil.ThrowHelperError(new SecurityTokenException("A Saml2SecurityToken cannot be created from the Saml2Assertion because it specifies the Bearer confirmation method but identifies keys in the SubjectConfirmationData."));
            //    }
            //    return Common.EmptyReadOnlyCollection<SecurityKey>.Instance;
            //}
            ////if (!(Saml2Constants.ConfirmationMethods.HolderOfKey == confirmation.Method))
            ////{
            ////    throw DiagnosticUtil.ExceptionUtil.ThrowHelperError(new SecurityTokenException(SR.GetString("ID4136", new object[] { confirmation.Method })));
            ////}
            ////if ((confirmation.SubjectConfirmationData == null) || (confirmation.SubjectConfirmationData.KeyIdentifiers.Count == 0))
            ////{
            ////    throw DiagnosticUtil.ExceptionUtil.ThrowHelperError(new SecurityTokenException(SR.GetString("ID4134", new object[0])));
            ////}
            //List<SecurityKey> list = new List<SecurityKey>();

            //if (confirmation.SubjectConfirmationData != null)
            //{
            //    foreach (SecurityKeyIdentifier identifier in confirmation.SubjectConfirmationData.KeyIdentifiers)
            //    {
            //        SecurityKey key = null;
            //        foreach (SecurityKeyIdentifierClause clause in identifier)
            //        {
            //            if ((resolver != null) && resolver.TryResolveSecurityKey(clause, out key))
            //            {
            //                list.Add(key);
            //                break;
            //            }
            //        }
            //        if (key == null)
            //        {
            //            if (identifier.CanCreateKey)
            //            {
            //                key = identifier.CreateKey();
            //                list.Add(key);
            //                continue;
            //            }
            //            list.Add(new SecurityKeyElement(identifier, resolver));
            //        }
            //    }
            //}

            //return list.AsReadOnly();
            #endregion
        }
Exemplo n.º 17
0
        /// <summary>
        /// Read the claim node
        /// </summary>
        /// <param name="rdr">XmlDictionaryReader of the policy Xml</param>
        /// <returns>A LINQ expression created from the claim node</returns>
        private Expression<Func<IClaimsPrincipal, bool>> ReadClaim(XmlDictionaryReader reader)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("CommercialVehicleCollisionWebservice.PolicyReader.ReadClaim",
                "MyTraceSource", SourceLevels.Information);

            string claimType = reader.GetAttribute("claimType");
            string claimValue = reader.GetAttribute("claimValue");
            string claimValueType = reader.GetAttribute("claimValueType");
            string claimValueOperation = reader.GetAttribute("claimValueOperation");

            ts.TraceInformation("Claim: <{0}, {1}, {2}, {3}>", claimType, claimValue, claimValueType, claimValueOperation);

            Expression<Func<IClaimsPrincipal, bool>> hasClaim = null;

            if (claimValueType == "Date" && claimValueOperation == "LessThanOrEqual")
            {
                hasClaim = (icp) => ClaimLessThanOrEqual(icp, claimType, claimValue, claimValueType);
            }
            else
            {
                hasClaim = (icp) => ClaimEquals(icp, claimType, claimValue);
            }

            reader.Read();

            return hasClaim;
        }
        private DelegationRestrictionType ReadDelegates(XmlReader reader)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("CommercialVehicleCollisionWebservice.CustomSaml2SecurityTokenHandler.ReadDelegates",
                "MyTraceSource", SourceLevels.Information);

            DelegationRestrictionType delegate2 = null;

            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }
            bool requireDeclaration = false;
            if (reader.IsStartElement("Condition", "urn:oasis:names:tc:SAML:2.0:assertion"))
            {
                reader.Read();
                requireDeclaration = true;
            }
            else if (!reader.IsStartElement("Delegate", "urn:oasis:names:tc:SAML:2.0:conditions:delegation"))
            {
                reader.ReadStartElement("Delegate", "urn:oasis:names:tc:SAML:2.0:conditions:delegation");
            }

            try
            {
                XmlUtil.ValidateXsiType(reader, "DelegationRestrictionType", "urn:oasis:names:tc:SAML:2.0:conditions:delegation", requireDeclaration);

                if (reader.IsEmptyElement)
                {
                    string errorMsg = string.Format("The given element ('{0}','{1}') is empty.", reader.LocalName, reader.NamespaceURI);
                    throw DiagnosticUtil.ThrowHelperXml(reader, errorMsg);
                }

                List<DelegateType> delegates = new List<DelegateType>();

                ts.TraceInformation("Before while (reader.IsStartElement(Delegate, urn:oasis:names:tc:SAML:2.0:conditions:delegation)" );
                ts.TraceInformation("\treader: " + reader.Name);

                while (reader.IsStartElement("Delegate", "urn:oasis:names:tc:SAML:2.0:conditions:delegation"))
                {
                    ts.TraceInformation("Inside while (reader.IsStartElement(Delegate, urn:oasis:names:tc:SAML:2.0:conditions:delegation)");
                    ts.TraceInformation("\treader: " + reader.Name);

                    DelegateType delegateType = new DelegateType();

                    string attribute = reader.GetAttribute("DelegationInstant");
                    if (!string.IsNullOrEmpty(attribute))
                    {
                        delegateType.DelegationInstant = XmlConvert.ToDateTime(attribute, DateTimeFormats.Accepted);
                    }
                                        
                    reader.Read();
                    ts.TraceInformation("After reader.Read()");
                    ts.TraceInformation("\treader: " + reader.Name);

                    if (!reader.IsStartElement("NameID", "urn:oasis:names:tc:SAML:2.0:assertion"))
                    {
                        ts.TraceInformation("Inside !reader.IsStartElement(NameID, urn:oasis:names:tc:SAML:2.0:assertion)");
                        ts.TraceInformation("\treader: " + reader.Name);

                        reader.ReadStartElement("NameID", "urn:oasis:names:tc:SAML:2.0:assertion");
                    }

                    delegateType.Item = ReadSimpleUriElement(reader, UriKind.RelativeOrAbsolute, true);

                    ts.TraceInformation("Delegate NameID: " + delegateType.Item.ToString());


                    delegates.Add(delegateType);

                    reader.ReadEndElement();
                }

                DelegationRestrictionType delegate1 = new DelegationRestrictionType();
                delegate1.Delegate = delegates.ToArray();

                delegate2 = delegate1;
            }
            catch (Exception exception)
            {
                Exception exception2 = DiagnosticUtil.TryWrapReadException(reader, exception);
                if (exception2 == null)
                {
                    throw;
                }

                throw exception2;
            }

            return delegate2;
        }
        protected override Saml2Conditions ReadConditions(XmlReader reader)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("CommercialVehicleCollisionWebservice.CustomSaml2SecurityTokenHandler.ReadConditions",
                  "MyTraceSource", SourceLevels.Information);

            Saml2Conditions conditions2 = null;

            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }
            if (!reader.IsStartElement("Conditions", "urn:oasis:names:tc:SAML:2.0:assertion"))
            {
                reader.ReadStartElement("Conditions", "urn:oasis:names:tc:SAML:2.0:assertion");
            }
            try
            {
                Saml2ConditionsDelegateWrapper conditions = new Saml2ConditionsDelegateWrapper();
                bool isEmptyElement = reader.IsEmptyElement;

                XmlUtil.ValidateXsiType(reader, "ConditionsType", "urn:oasis:names:tc:SAML:2.0:assertion", false);
                string attribute = reader.GetAttribute("NotBefore");
                if (!string.IsNullOrEmpty(attribute))
                {
                    conditions.NotBefore = new DateTime?(XmlConvert.ToDateTime(attribute, DateTimeFormats.Accepted));
                }
                attribute = reader.GetAttribute("NotOnOrAfter");
                if (!string.IsNullOrEmpty(attribute))
                {
                    conditions.NotOnOrAfter = new DateTime?(XmlConvert.ToDateTime(attribute, DateTimeFormats.Accepted));
                }

                reader.ReadStartElement();
                if (!isEmptyElement)
                {
                    while (reader.IsStartElement())
                    {
                        if (reader.IsStartElement("Condition", "urn:oasis:names:tc:SAML:2.0:assertion"))
                        {
                            XmlQualifiedName xsiType = XmlUtil.GetXsiType(reader);

                            if ((null == xsiType) || XmlUtil.EqualsQName(xsiType, "ConditionAbstractType", "urn:oasis:names:tc:SAML:2.0:assertion"))
                            {
                                string errorMsg = string.Format("An abstract element was encountered which does not specify its concrete type. "
                                    + "Element name: '{0}' Element namespace: '{1}'", reader.LocalName, reader.NamespaceURI);
                                throw DiagnosticUtil.ThrowHelperXml(reader, errorMsg);
                            }

                            reader.ReadStartElement("Condition", "urn:oasis:names:tc:SAML:2.0:assertion");

                            conditions.Delegates = ReadDelegates(reader);

                            reader.ReadEndElement();

                            /////////////////////////////////

                            // Need to investigate why this is disabled!!!!!
                            // This looks like it is invalid here

                            //if (EqualsQName(xsiType, "AudienceRestrictionType", "urn:oasis:names:tc:SAML:2.0:assertion"))
                            //{
                            //    conditions.AudienceRestrictions.Add(this.ReadAudienceRestriction(reader));
                            //}
                            //else if (EqualsQName(xsiType, "OneTimeUseType", "urn:oasis:names:tc:SAML:2.0:assertion"))
                            //{
                            //    if (conditions.OneTimeUse)
                            //    {
                            //        throw new InvalidOperationException("ID4115: OneTimeUse");
                            //    }
                            //    ReadEmptyContentElement(reader);
                            //    conditions.OneTimeUse = true;
                            //}
                            //else
                            //{
                            //    if (!EqualsQName(xsiType, "ProxyRestrictionType", "urn:oasis:names:tc:SAML:2.0:assertion"))
                            //    {
                            //        throw new InvalidOperationException("ID4113");
                            //    }
                            //    if (conditions.ProxyRestriction != null)
                            //    {
                            //        throw new InvalidOperationException("ID4115: ProxyRestriction");
                            //    }
                            //    conditions.ProxyRestriction = this.ReadProxyRestriction(reader);
                            //}
                            ////////////////////////////////////
                        }
                        else if (reader.IsStartElement("AudienceRestriction", "urn:oasis:names:tc:SAML:2.0:assertion"))
                        {
                            XmlQualifiedName xsiType = XmlUtil.GetXsiType(reader);

                            conditions.AudienceRestrictions.Add(this.ReadAudienceRestriction(reader));
                        }
                        else
                        {
                            //if (reader.IsStartElement("OneTimeUse", "urn:oasis:names:tc:SAML:2.0:assertion"))
                            //{
                            //    if (conditions.OneTimeUse)
                            //    {
                            //        throw DiagnosticUtil.ExceptionUtil.ThrowHelperXml(reader, "A <saml:Conditions> element contained more than one OneTimeUse condition.");
                            //    }
                            //    ReadEmptyContentElement(reader);
                            //    conditions.OneTimeUse = true;
                            //    continue;
                            //}
                            if (!reader.IsStartElement("ProxyRestriction", "urn:oasis:names:tc:SAML:2.0:assertion"))
                            {
                                break;
                            }
                            if (conditions.ProxyRestriction != null)
                            {
                                throw DiagnosticUtil.ThrowHelperXml(reader, "A <saml:Conditions> element contained more than one ProxyRestriction condition.");
                            }
                            conditions.ProxyRestriction = this.ReadProxyRestriction(reader);
                        }
                    }

                    reader.ReadEndElement();
                }
                conditions2 = conditions;
            }
            catch (Exception exception)
            {
                Exception exception2 = DiagnosticUtil.TryWrapReadException(reader, exception);
                if (exception2 == null)
                {
                    throw;
                }

                throw exception2;
            }

            return conditions2;
        }
        // This is actually augmenting the claims in the subject. At the WSP, this should not return any claims!
        //public override ClaimsIdentityCollection ValidateToken(SecurityToken token)
        //{
        //    CustomTextTraceSource ts = new CustomTextTraceSource("CommercialVehicleCollisionWebservice.CustomSaml2SecurityTokenHandler.ValidateToken",
        //           "MyTraceSource", SourceLevels.Information);

        //    ClaimsIdentityCollection ret = null;


        //    SerializeTokenToStream(token as Saml2SecurityToken, ts, "ValidateToken");


        //    IClaimsIdentity claimsIdentity = null;

        //    if (token == null)
        //    {
        //        throw new ArgumentNullException("token");
        //    }
            
        //    Saml2SecurityToken token2 = token as Saml2SecurityToken;
        //    if (token2 == null)
        //    {
        //        throw new ArgumentNullException("null Saml2SecurityToken");
        //    }

        //    if (base.Configuration == null)
        //    {
        //        throw new InvalidOperationException("null Configuration");
        //    }
        //    Saml2Assertion assertion = token2.Assertion;

        //    //bool shouldEnforceAudienceRestriction = this.SamlSecurityTokenRequirement.ShouldEnforceAudienceRestriction(
        //    //    base.Configuration.AudienceRestriction.AudienceMode, token2);

        //    this.ValidateConditions(assertion.Conditions,
        //        this.SamlSecurityTokenRequirement.ShouldEnforceAudienceRestriction(base.Configuration.AudienceRestriction.AudienceMode, token2));

        //    //Saml2SubjectConfirmation confirmation = assertion.Subject.SubjectConfirmations[0];

        //    // certificate that signed the assertion internally!
        //    X509SecurityToken issuerToken = token2.IssuerToken as X509SecurityToken;
        //    if (issuerToken != null)
        //    {
        //        // Here we validate the Issuer certificate
        //        this.CertificateValidator.Validate(issuerToken.Certificate);
        //    }

        //    claimsIdentity = this.CreateClaims(token2);

        //    if (base.Configuration.DetectReplayedTokens)
        //    {
        //        this.DetectReplayedTokens(token2);
        //    }

        //    // This will be needed if chaining WSP/WSC 
        //    if (base.Configuration.SaveBootstrapTokens)
        //    {
        //        claimsIdentity.BootstrapToken = token;
        //    }

        //    // Debug
        //    ClaimsIdentityCollection ids = new ClaimsIdentityCollection();
        //    ids.Add(claimsIdentity);
        //    IClaimsPrincipal p = new ClaimsPrincipal(ids);
        //    ClaimsUtil.LogClaimsPrincipal(p, "CommercialVehicleCollisionWebservice.CustomSaml2SecurityTokenHandler.ValidateToken)");
                
        //    ret = new ClaimsIdentityCollection(new IClaimsIdentity[] { claimsIdentity });

        //    return ret;
        //}
        #endregion

        protected void ValidateDelegates(DelegationRestrictionType delegation)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("CommercialVehicleCollisionWebservice.CustomSaml2SecurityTokenHandler.ValidateDelegates",
               "MyTraceSource", SourceLevels.Information);

            // get all intermediaries IDs 
            List<string> wscEndityIds = new List<string>();

            foreach (DelegateType wscDelegate in delegation.Delegate)
            {
                ts.TraceInformation("Delegate NameID: " + wscDelegate.Item.ToString());

                wscEndityIds.Add(wscDelegate.Item.ToString());
            }

            // Here we verify that all the entityIDs are part of the trust fabric
            if (!_trustFabric.Contains(wscEndityIds))
            {
                throw new InvalidSecurityException("Not all of the intermediaries in the delegation chain are present in the Trust Fabric.");
            }
        }
        // Pass thru the claims of the original user
        protected override IClaimsIdentity CreateClaims(Saml2SecurityToken samlToken)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("CommercialVehicleCollisionWebservice.CustomSaml2SecurityTokenHandler.CreateClaims",
                "MyTraceSource", SourceLevels.Information);

            // process subject in base 
            IClaimsIdentity subject = base.CreateClaims(samlToken);

            Saml2Assertion assertion = samlToken.Assertion;

            // process Condition/Delegation 
           
            // TODO: Refactor to a function ProcessDelegation()
            ts.TraceInformation("assertion.Conditions Type: " + assertion.Conditions.GetType().Name);

            if (assertion.Conditions is Saml2ConditionsDelegateWrapper)
            {
                Saml2ConditionsDelegateWrapper delegateData = assertion.Conditions as Saml2ConditionsDelegateWrapper;

                // Iterate over the Condition delegate elements
                // Check if there are delegates within an incoming assertion
                IClaimsIdentity currentSubject = subject;

                if (delegateData != null && delegateData.Delegates != null)
                {
                    // Add the delegates in the DelegationRestrictionType
                    ts.TraceInformation("Number of Delegates: " + delegateData.Delegates.Delegate.Length);
                    for (int i = 0; i < delegateData.Delegates.Delegate.Length; i++)
                    {
                        DelegateType del = delegateData.Delegates.Delegate[i];

                        if (del != null)
                        {
                            string nameId = del.Item.ToString();

                            var claims = new List<Claim>();
                            claims.Add(new Claim(ClaimTypes.Name, nameId));
                            claims.Add(new Claim(ClaimTypes.AuthenticationInstant, XmlConvert.ToString(del.DelegationInstant, DateTimeFormats.Generated)));

                            // now add to current subject
                            currentSubject.Actor = new ClaimsIdentity(claims);

                            currentSubject = currentSubject.Actor;
                        }
                    }
                }
            }

            return subject;
        }
        //Claim CreateClaim(string claimType, string claimValue, string claimProperty, string claimPropertyValue)
        //{
        //    var claim = new Claim(claimType, claimValue);
        //    claim.Properties[claimProperty] = claimPropertyValue;

        //    return claim;
        //}


        protected override void ValidateRequest(RequestSecurityToken request)
        {
            if (request == null)
            {
                throw new InvalidRequestException("The request is null");
            }

            CustomTextTraceSource ts = new CustomTextTraceSource("IdpSts.CustomSecurityTokenService.ValidateRequest",
                "MyTraceSource", SourceLevels.Information);


            ts.TraceInformation("request.RequestType: " + request.RequestType);
            ts.TraceInformation("request.TokenType: " + request.TokenType);
            ts.TraceInformation("request.KeyType: " + request.KeyType);
            ts.TraceInformation("request.KeySizeInBits: " + request.KeySizeInBits);

            if (request.SecondaryParameters != null)
            {
                ts.TraceInformation("request.SecondaryParameters.TokenType: " + request.SecondaryParameters.TokenType);
                ts.TraceInformation("request.SecondaryParameters.KeyType: " + request.SecondaryParameters.KeyType);



                // default to bearer key type
                request.TokenType = string.IsNullOrEmpty(request.TokenType) ? request.SecondaryParameters.TokenType : request.TokenType;

                // default to bearer key type
                request.KeyType = string.IsNullOrEmpty(request.KeyType) ? request.SecondaryParameters.KeyType : request.KeyType;

                if (StringComparer.Ordinal.Equals(request.KeyType, "http://schemas.microsoft.com/idfx/keytype/bearer"))
                {
                    if (request.KeySizeInBits.HasValue)
                    {
                        if (request.KeySizeInBits.Value > 0)
                        {
                            string errorMsg = string.Format("The request has a KeySize '{0}' that is greater than 0, which, when specified in the request is the required value for sender-vouches assertions.",
                                request.KeySizeInBits.Value);
                            throw new InvalidRequestException(errorMsg);
                        }
                    }
                    else
                    {
                        // the key size for an assertion with Sender-vouches confirmation must be 0
                        request.KeySizeInBits = new int?(0);
                    }

                    //ts.TraceInformation("KeySizeInBits: " + request.KeySizeInBits.Value.ToString());
                }
            }

            ts.TraceInformation("request.TokenType: " + request.TokenType);
            ts.TraceInformation("request.KeyType: " + request.KeyType);
            ts.TraceInformation("request.KeySizeInBits: " + request.KeySizeInBits);

            base.ValidateRequest(request);
        }
        public override RequestSecurityTokenResponse Issue(IClaimsPrincipal principal, RequestSecurityToken request)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("IdpSts.CustomSecurityTokenService.Issue",
                "MyTraceSource", SourceLevels.Information);


            RequestSecurityTokenResponse rstr = base.Issue(principal, request);

            return rstr;
        }
  void LogMessage(string methodName, Message msg)
  {
      CustomTextTraceSource ts = new CustomTextTraceSource("CommercialVehicleCollisionWebservice.CustomDispatchMessageInspector." + methodName,
                      "MyTraceSource", SourceLevels.Information);
      
      if (msg != null)
      {
          ts.TraceInformation("Message:");
          //request.CreateBufferedCopy(int.MaxValue)
          ts.TraceInformation(msg.ToString());
          //file.WriteLine(msg.CreateBufferedCopy(int.MaxValue).ToString());
      }
      else
      {
          ts.TraceInformation("Message == NULL");
      }
 }
        /// <summary>
        /// This method returns the configuration for the token issuance request. The configuration
        /// is represented by the Scope class. In our case, we are only capable of issuing a token for a
        /// single RP identity represented by the EncryptingCertificateName.
        /// </summary>
        /// <param name="principal">The caller's principal.</param>
        /// <param name="request">The incoming RST.</param>
        /// <returns>The scope information to be used for the token issuance.</returns>
        protected override Scope GetScope(IClaimsPrincipal principal, RequestSecurityToken request)
        {
            // TEMP
            //ClaimsUtil.LogClaimsPrincipal(principal, "IdpSts.CustomSecurityTokenService.GetScope");
            CustomTextTraceSource ts = new CustomTextTraceSource("IdpSts.CustomSecurityTokenService.GetScope",
                "MyTraceSource", SourceLevels.Information);

            ValidateAppliesTo(request.AppliesTo);
            
            X509Certificate2 signingCert = CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine,
                WebConfigurationManager.AppSettings["SigningCertificateName"]);

            if (signingCert != null)
            {
                ts.TraceInformation("signingCert: " + signingCert.SubjectName);
                ts.TraceInformation("\tthumbPrint: " + signingCert.Thumbprint);
            }
            else
            {
                ts.TraceInformation("signingCert: NULL");
            }

            //SecurityKeyIdentifier signingSki = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { 
            //        new X509SecurityToken(signingCert).CreateKeyIdentifierClause<X509SubjectKeyIdentifierClause>() });

            SecurityKeyIdentifier signingSki = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { 
                new X509SecurityToken(signingCert).CreateKeyIdentifierClause<X509RawDataKeyIdentifierClause>() });

            X509SigningCredentials signingCredentialss = new X509SigningCredentials(signingCert, signingSki);

            Scope scope = new Scope(request.AppliesTo.Uri.OriginalString, signingCredentialss);


            //string encryptingCertificateName = "";
            string encryptingCertificateName = WebConfigurationManager.AppSettings["EncryptingCertificateName"];
            if (!string.IsNullOrEmpty(encryptingCertificateName))
            {
                // Important note on setting the encrypting credentials.
                // In a production deployment, you would need to select a certificate that is specific to the RP that is requesting the token.
                // You can examine the 'request' to obtain information to determine the certificate to use. (AppliesTo)

                // Original SV
                //scope.EncryptingCredentials = new X509EncryptingCredentials(CertificateUtil.GetCertificateByCommonName(StoreName.TrustedPeople,
                //    StoreLocation.LocalMachine, request.AppliesTo.Uri.Host));

                // New HoK
                X509Certificate2 cert = CertificateUtil.GetCertificate(StoreName.TrustedPeople,
                    StoreLocation.LocalMachine, encryptingCertificateName);
                var ski = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] 
                    { 
                        //new X509SecurityToken(cert).CreateKeyIdentifierClause<X509SubjectKeyIdentifierClause>()
                        new X509SecurityToken(cert).CreateKeyIdentifierClause<X509ThumbprintKeyIdentifierClause>()
                    }
                );
                X509EncryptingCredentials encryptingCredentials = new X509EncryptingCredentials(cert, ski);

                scope.EncryptingCredentials = encryptingCredentials;
            }
            else
            {
                // If there is no encryption certificate specified, the STS will not perform encryption.
                // This will succeed for tokens that are created without keys (BearerTokens) or asymmetric keys.  Symmetric keys are
                // required to be 'wrapped' and the STS will throw.
                scope.TokenEncryptionRequired = false;

                // Symmetric keys are required to be 'wrapped' or the STS will throw, uncomment the code below to turn off proof key encryption.
                // Turning off proof key encryption is not secure and should not be used in a deployment scenario.

                scope.SymmetricKeyEncryptionRequired = false;
            }

            //ts.TraceInformation("request.RequestType: " + request.RequestType);
            //ts.TraceInformation("request.TokenType: " + request.TokenType);
            //ts.TraceInformation("request.KeyType: " + request.KeyType);
            //ts.TraceInformation("request.KeySizeInBits: " + request.KeySizeInBits);

            //ts.TraceInformation("request.SecondaryParameters.TokenType: " + request.SecondaryParameters.TokenType);
            //ts.TraceInformation("request.SecondaryParameters.KeyType: " + request.SecondaryParameters.KeyType);

            //ts.TraceInformation("Principal Name: " + principal.Identity.Name);

            //if (request.SecondaryParameters != null)
            //{
            //    if (!string.IsNullOrEmpty(request.SecondaryParameters.TokenType))
            //    {
            //        if (string.IsNullOrEmpty(request.TokenType))
            //        {
            //            request.TokenType = request.SecondaryParameters.TokenType;
            //        }
            //    }

            //    if (!string.IsNullOrEmpty(request.SecondaryParameters.KeyType))
            //    {
            //        if (string.IsNullOrEmpty(request.KeyType))
            //        {
            //            request.TokenType = request.SecondaryParameters.KeyType;
            //        }
            //    }

            //    if (StringComparer.Ordinal.Equals(request.KeyType, "http://schemas.microsoft.com/idfx/keytype/bearer"))
            //    {
            //        if (request.KeySizeInBits.HasValue)
            //        {
            //            if (request.KeySizeInBits.Value > 0)
            //            {
            //                string errorMsg = string.Format("The request has a KeySize '{0}' that is greater than 0, which, when specified in the request is the required value for sender-vouches assertions.",
            //                    request.KeySizeInBits.Value);
            //                ts.TraceInformation(errorMsg);

            //                request.KeySizeInBits = new int?(0);
            //            }
            //        }
            //        else
            //        {
            //            // the key size for an assertion with Sender-vouches confirmation must be 0
            //            request.KeySizeInBits = new int?(0);
            //        }

            //        ts.TraceInformation("KeySizeInBits: " + request.KeySizeInBits.Value.ToString());
            //    }
            //}

            //if ((StringComparer.Ordinal.Equals(request.KeyType, "http://schemas.microsoft.com/idfx/keytype/bearer") && request.KeySizeInBits.HasValue) && (request.KeySizeInBits.Value != 0))
            //{
            //    ts.TraceInformation("Still Have problems with KeySize!!!");
            //}


            return scope;
        }
Exemplo n.º 26
0
        static bool ServiceCertificateValidator(object sender, X509Certificate cert, X509Chain chain,
            System.Net.Security.SslPolicyErrors error)
        {
            X509Certificate2 x509Cert = cert as X509Certificate2;

            CustomTextTraceSource ts = new CustomTextTraceSource("ClientTest.Program.ServiceCertificateValidator",
              "MyTraceSource", SourceLevels.Information);
            
            ts.TraceInformation("Subject Name: " + x509Cert.SubjectName.Name);
            ts.TraceInformation("error: " + error.ToString());

            // Check if there were any errors
            if (error == System.Net.Security.SslPolicyErrors.None)
            {
                return true;
            }
           
            return ValidateCertificate(x509Cert);
        }
        // Code to be added.
        public override bool CheckAccess(EndpointIdentity identity, AuthorizationContext authContext)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("Common.CustomIdentityVerifier.CheckAccess",
                "MyTraceSource", SourceLevels.Information);

            bool returnvalue = false;

            try
            {
                foreach (ClaimSet claimset in authContext.ClaimSets)
                {
                    foreach (Claim claim in claimset)
                    {
                        ts.TraceInformation("claim.ClaimType: " + claim.ClaimType);
                        ts.TraceInformation("\tclaim.Right: " + claim.Right);
                        ts.TraceInformation("\t\tclaim.Resource: " + claim.Resource.ToString());
                                            
                        if (claim.ClaimType == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/x500distinguishedname")
                        {
                            X500DistinguishedName name = (X500DistinguishedName)claim.Resource;
                            ts.TraceInformation("X500DistinguishedName: " + name.Name);
                        
                            // TODO:  The identity of the CURE Idp will fail here; is it valid to check the this 
                            // certificate against the TruestedPeople store???
                            
                            //if ("[email protected], CN=HA50WSP, O=Hawaii Five0, L=Honolulu, S=Hawaii, C=US" == name.Name ||
                            //    "[email protected], CN=HA50IDP, O=Hawaii Five0, L=Dallas, S=GA, C=US" == name.Name)
                            //{
                            //    ts.TraceInformation("\tClaim Type: {0}", claim.ClaimType);
                            //    ts.TraceInformation("\tRight: {0}", claim.Right);
                            //    ts.TraceInformation("\tResource: {0}", claim.Resource);
                            //    returnvalue = true;
                            //}
                        }

                        if (claim.ClaimType == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/thumbprint")
                        {
                            //ts.TraceInformation("Thumbprint: " + claim.Resource);

                            //string myString = System.Text.Encoding.ASCII.GetString((byte[])claim.Resource);
                            string myString = Base64Util.EncodeTo64((byte[])claim.Resource);
                            ts.TraceInformation("myString: " + myString);                            

                            string x509HexThumbprint = Base64Util.FromBase64ToHex(myString);
                            
                            //string x509HexThumbprint = Base64Util.FromBase64ToHex(Base64Util.DecodeFrom64((byte[])claim.Resource));

                            ts.TraceInformation("Thumbprint: " + x509HexThumbprint);
                            ts.TraceInformation("\tClaim Type: {0}", claim.ClaimType);
                            ts.TraceInformation("\tRight: {0}", claim.Right);

                            // TODO:  The identity of the CURE Idp will fail here; is it valid to check the this 
                            // certificate against the TruestedPeople store???


                            X509Certificate2 cert = CertificateUtil.GetCertificateByThumbprint(StoreName.TrustedPeople, StoreLocation.LocalMachine, myString);

                            if (cert != null)
                            {                                
                                ts.TraceInformation("Certificate: {0}", cert.Subject);
                                returnvalue = true;
                            }
                        }
                    }

                }
            }
            catch (Exception e)
            {
                ts.TraceInformation("Exception: " + e.Message);
                if (e.InnerException != null)
                {
                    ts.TraceInformation("InnerException: " + e.InnerException.Message);
                }
            }

            return returnvalue;
        }
        public override bool TryGetIdentity(EndpointAddress reference, out EndpointIdentity identity)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("Common.CustomIdentityVerifier.TryGetIdentity",
                            "MyTraceSource", SourceLevels.Information);

            ts.TraceInformation("Reference:  " + reference.Uri.ToString());
            ts.TraceInformation("Claim Type: " + reference.Identity.IdentityClaim.ClaimType);
            ts.TraceInformation("Identity:  " + reference.Identity.ToString());

            return IdentityVerifier.CreateDefault().TryGetIdentity(reference, out identity);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Read the And Node
        /// </summary>
        /// <param name="rdr">XmlDictionaryReader of the policy Xml</param>
        /// <param name="subject">IClaimsPrincipal subject</param>
        /// <returns>A LINQ expression created from the And node</returns>
        private Expression<Func<IClaimsPrincipal, bool>> ReadAnd(XmlDictionaryReader reader, ParameterExpression subject)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("CommercialVehicleCollisionWebservice.PolicyReader.ReadAnd",
                "MyTraceSource", SourceLevels.Information);

            reader.Read();

            ts.TraceInformation("Reader Element: " + reader.Name);

            ts.TraceInformation("ParameterExpression Subject: " + subject.Name);

            BinaryExpression lambda1 = Expression.AndAlso(
                    Expression.Invoke(ReadNode(reader, subject), subject),
                    Expression.Invoke(ReadNode(reader, subject), subject));

            reader.ReadEndElement();

            Expression<Func<IClaimsPrincipal, bool>> lambda2 = Expression.Lambda<Func<IClaimsPrincipal, bool>>(lambda1, subject);
            return lambda2;
        }
        public override ClaimsIdentityCollection ValidateToken(SecurityToken token)
        {
            CustomTextTraceSource ts = new CustomTextTraceSource("IdpSts.CustomUserNameSecurityTokenHandler.ValidateToken",
              "MyTraceSource", SourceLevels.Information);

            //StackTracer.TraceStack(ts);

            UserNameSecurityToken usernameToken = token as UserNameSecurityToken;
            if (usernameToken == null)
            {
                throw new ArgumentException("usernameToken", "The security token is not a valid username security token.");
            }

            // will throw if fails
            UsernameCredentialStore.AuthenticateUser(usernameToken.UserName, usernameToken.Password);
            
            ClaimsIdentityCollection identities = new ClaimsIdentityCollection();

            IClaimsIdentity claimsIdentity = new ClaimsIdentity("CustomUserNameSecurityTokenHandler");
            claimsIdentity.Claims.Add(new Claim(System.IdentityModel.Claims.ClaimTypes.Name, usernameToken.UserName));

            identities.Add(claimsIdentity);

            return identities;                      
        }