private void CallBegin(bool completedSynchronously)
        {
            IAsyncResult result    = null;
            Exception    exception = null;

            try
            {
                CardSpacePolicyElement[] elementArray;
                SecurityTokenManager     clientCredentialsTokenManager = this.credentials.CreateSecurityTokenManager();
                this.requiresInfoCard = InfoCardHelper.IsInfocardRequired(this.binding, this.credentials, clientCredentialsTokenManager, this.proxy.RemoteAddress, out elementArray, out this.relyingPartyIssuer);
                MessageSecurityVersion    bindingSecurityVersionOrDefault = InfoCardHelper.GetBindingSecurityVersionOrDefault(this.binding);
                WSSecurityTokenSerializer defaultInstance = WSSecurityTokenSerializer.DefaultInstance;
                result = this.credentials.GetInfoCardTokenCallback.BeginInvoke(this.requiresInfoCard, elementArray, clientCredentialsTokenManager.CreateSecurityTokenSerializer(bindingSecurityVersionOrDefault.SecurityTokenVersion), callback, this);
            }
            catch (Exception exception2)
            {
                if (Fx.IsFatal(exception2))
                {
                    throw;
                }
                exception = exception2;
            }
            if (exception == null)
            {
                if (!result.CompletedSynchronously)
                {
                    return;
                }
                this.CallEnd(result, out exception);
            }
            if (exception == null)
            {
                this.CallComplete(completedSynchronously, null);
            }
        }
        /// <summary>
        /// Creates the security token
        /// </summary>
        /// <param name="timeout">Maximum amount of time the method is supposed to take. Ignored in this implementation.</param>
        /// <returns>A SecurityToken that corresponds to the SAML assertion and proof key specified at construction time</returns>
        protected override SecurityToken GetTokenCore(TimeSpan timeout)
        {
            // Create a SamlSecurityToken from the provided assertion.
            SamlSecurityToken samlToken = new SamlSecurityToken(assertion);

            // Create a SecurityTokenSerializer that is used to serialize the SamlSecurityToken
            WSSecurityTokenSerializer ser = new WSSecurityTokenSerializer();

            // Create a memory stream to write the serialized token into
            // Use an initial size of 64Kb
            MemoryStream s = new MemoryStream(UInt16.MaxValue);

            // Create an XmlWriter over the stream
            XmlWriter xw = XmlWriter.Create(s);

            // Write the SamlSecurityToken into the stream
            ser.WriteToken(xw, samlToken);

            // Seek back to the beginning of the stream
            s.Seek(0, SeekOrigin.Begin);

            // Load the serialized token into a DOM
            XmlDocument dom = new XmlDocument();
            dom.Load(s);

            // Create a KeyIdentifierClause for the SamlSecurityToken
            SamlAssertionKeyIdentifierClause samlKeyIdentifierClause = samlToken.CreateKeyIdentifierClause<SamlAssertionKeyIdentifierClause>();

            // Return a GenericXmlToken from the XML for the SamlSecurityToken, the proof token, the valid from
            // and valid until times from the assertion and the key identifier clause created above
            return new GenericXmlSecurityToken(dom.DocumentElement, proofToken, assertion.Conditions.NotBefore, assertion.Conditions.NotOnOrAfter, samlKeyIdentifierClause, samlKeyIdentifierClause, null);
        }
Exemplo n.º 3
0
 protected WSSecureConversation(WSSecurityTokenSerializer tokenSerializer, int maxKeyDerivationOffset, int maxKeyDerivationLabelLength, int maxKeyDerivationNonceLength)
 {
     if (tokenSerializer == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenSerializer");
     }
     this.tokenSerializer = tokenSerializer;
     this.derivedKeyEntry = new WSSecureConversation.DerivedKeyTokenEntry(this, maxKeyDerivationOffset, maxKeyDerivationLabelLength, maxKeyDerivationNonceLength);
 }
Exemplo n.º 4
0
 public WSSecureConversationFeb2005(WSSecurityTokenSerializer tokenSerializer, SecurityStateEncoder securityStateEncoder, IEnumerable <Type> knownTypes,
                                    int maxKeyDerivationOffset, int maxKeyDerivationLabelLength, int maxKeyDerivationNonceLength)
     : base(tokenSerializer, maxKeyDerivationOffset, maxKeyDerivationLabelLength, maxKeyDerivationNonceLength)
 {
     if (securityStateEncoder != null)
     {
         throw ExceptionHelper.PlatformNotSupported();
     }
 }
 protected WSSecureConversation(WSSecurityTokenSerializer tokenSerializer, int maxKeyDerivationOffset, int maxKeyDerivationLabelLength, int maxKeyDerivationNonceLength)
 {
     if (tokenSerializer == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenSerializer");
     }
     this.tokenSerializer = tokenSerializer;
     this.derivedKeyEntry = new DerivedKeyTokenEntry(this, maxKeyDerivationOffset, maxKeyDerivationLabelLength, maxKeyDerivationNonceLength);
 }
            protected BinaryTokenEntry(WSSecurityTokenSerializer tokenSerializer, string[] valueTypeUris)
            {
                if (valueTypeUris == null)
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("valueTypeUris");

                this.tokenSerializer = tokenSerializer;
                this.valueTypeUris = new string[valueTypeUris.GetLength(0)];
                for (int i = 0; i < this.valueTypeUris.GetLength(0); ++i)
                    this.valueTypeUris[i] = valueTypeUris[i];
            }
            protected BinaryTokenEntry(WSSecurityTokenSerializer tokenSerializer, string[] valueTypeUris)
            {
                if (valueTypeUris == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(valueTypeUris));
                }

                _tokenSerializer = tokenSerializer;
                _valueTypeUris   = new string[valueTypeUris.GetLength(0)];
                for (int i = 0; i < _valueTypeUris.GetLength(0); ++i)
                {
                    _valueTypeUris[i] = valueTypeUris[i];
                }
            }
Exemplo n.º 8
0
        public WSSecureConversationDec2005(WSSecurityTokenSerializer tokenSerializer, SecurityStateEncoder securityStateEncoder, IEnumerable <Type> knownTypes, int maxKeyDerivationOffset, int maxKeyDerivationLabelLength, int maxKeyDerivationNonceLength)
            : base(tokenSerializer, maxKeyDerivationOffset, maxKeyDerivationLabelLength, maxKeyDerivationNonceLength)
        {
#if FEATURE_CORECLR
            throw new NotImplementedException("DataProtectionSecurityStateEncoder not supported in .NET Core");
#else
            this.securityStateEncoder = securityStateEncoder == null ? (SecurityStateEncoder) new DataProtectionSecurityStateEncoder() : securityStateEncoder;
            this.knownClaimTypes      = (IList <Type>) new List <Type>();
            if (knownTypes == null)
            {
                return;
            }
            foreach (Type knownType in knownTypes)
            {
                this.knownClaimTypes.Add(knownType);
            }
#endif
        }
Exemplo n.º 9
0
 public WSSecureConversationDec2005(WSSecurityTokenSerializer tokenSerializer, SecurityStateEncoder securityStateEncoder, IEnumerable <Type> knownTypes, int maxKeyDerivationOffset, int maxKeyDerivationLabelLength, int maxKeyDerivationNonceLength) : base(tokenSerializer, maxKeyDerivationOffset, maxKeyDerivationLabelLength, maxKeyDerivationNonceLength)
 {
     if (securityStateEncoder != null)
     {
         this.securityStateEncoder = securityStateEncoder;
     }
     else
     {
         this.securityStateEncoder = new DataProtectionSecurityStateEncoder();
     }
     this.knownClaimTypes = new List <Type>();
     if (knownTypes != null)
     {
         foreach (Type type in knownTypes)
         {
             this.knownClaimTypes.Add(type);
         }
     }
 }
Exemplo n.º 10
0
        public WSSecureConversationFeb2005(WSSecurityTokenSerializer tokenSerializer, SecurityStateEncoder securityStateEncoder, IEnumerable <Type> knownTypes,
                                           int maxKeyDerivationOffset, int maxKeyDerivationLabelLength, int maxKeyDerivationNonceLength)
            : base(tokenSerializer, maxKeyDerivationOffset, maxKeyDerivationLabelLength, maxKeyDerivationNonceLength)
        {
            if (securityStateEncoder != null)
            {
                _securityStateEncoder = securityStateEncoder;
            }

            _knownClaimTypes = new List <Type>();
            if (knownTypes != null)
            {
                // Clone this collection.
                foreach (Type knownType in knownTypes)
                {
                    _knownClaimTypes.Add(knownType);
                }
            }
        }
 public WSSecureConversationDec2005(WSSecurityTokenSerializer tokenSerializer, SecurityStateEncoder securityStateEncoder, IEnumerable<Type> knownTypes, int maxKeyDerivationOffset, int maxKeyDerivationLabelLength, int maxKeyDerivationNonceLength) : base(tokenSerializer, maxKeyDerivationOffset, maxKeyDerivationLabelLength, maxKeyDerivationNonceLength)
 {
     if (securityStateEncoder != null)
     {
         this.securityStateEncoder = securityStateEncoder;
     }
     else
     {
         this.securityStateEncoder = new DataProtectionSecurityStateEncoder();
     }
     this.knownClaimTypes = new List<Type>();
     if (knownTypes != null)
     {
         foreach (Type type in knownTypes)
         {
             this.knownClaimTypes.Add(type);
         }
     }
 }
        void CallBegin(bool completedSynchronously)
        {
            IAsyncResult result    = null;
            Exception    exception = null;

            try
            {
                CardSpacePolicyElement[] chain;
                SecurityTokenManager     tokenManager = credentials.CreateSecurityTokenManager();
                requiresInfoCard = InfoCardHelper.IsInfocardRequired(binding, credentials, tokenManager, proxy.RemoteAddress, out chain, out relyingPartyIssuer);
                MessageSecurityVersion    bindingSecurityVersion = InfoCardHelper.GetBindingSecurityVersionOrDefault(binding);
                WSSecurityTokenSerializer tokenSerializer        = WSSecurityTokenSerializer.DefaultInstance;
                result = credentials.GetInfoCardTokenCallback.BeginInvoke(requiresInfoCard, chain, tokenManager.CreateSecurityTokenSerializer(bindingSecurityVersion.SecurityTokenVersion), callback, this);
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                exception = e;
            }
            if (exception == null)
            {
                if (!result.CompletedSynchronously)
                {
                    return;
                }

                this.CallEnd(result, out exception);
            }
            if (exception != null)
            {
                return;
            }


            this.CallComplete(completedSynchronously, null);
        }
Exemplo n.º 13
0
        public WSSecureConversationDec2005(WSSecurityTokenSerializer tokenSerializer, SecurityStateEncoder securityStateEncoder, IEnumerable <Type> knownTypes,
                                           int maxKeyDerivationOffset, int maxKeyDerivationLabelLength, int maxKeyDerivationNonceLength)
            : base(tokenSerializer, maxKeyDerivationOffset, maxKeyDerivationLabelLength, maxKeyDerivationNonceLength)
        {
            if (securityStateEncoder != null)
            {
                _securityStateEncoder = securityStateEncoder;
            }
            else
            {
                //throw new PlatformNotSupportedException();
                //this.securityStateEncoder = new DataProtectionSecurityStateEncoder();
            }

            _knownClaimTypes = new List <Type>();
            if (knownTypes != null)
            {
                // Clone this collection.
                foreach (Type knownType in knownTypes)
                {
                    _knownClaimTypes.Add(knownType);
                }
            }
        }
 public WSSecurityXXX2005(WSSecurityTokenSerializer tokenSerializer, SamlSerializer samlSerializer)
     : base(tokenSerializer, samlSerializer)
 {
 }
 public WrappedKeyTokenEntry(WSSecurityTokenSerializer tokenSerializer)
     : base(tokenSerializer)
 {
 }
Exemplo n.º 16
0
 public KeyInfoEntry(WSSecurityTokenSerializer tokenSerializer)
 {
     this.tokenSerializer = tokenSerializer;
 }
 public XmlEncApr2001(WSSecurityTokenSerializer tokenSerializer)
 {
     this.tokenSerializer = tokenSerializer;
 }
Exemplo n.º 18
0
        // Since the issued token is an endorsing token it will not be used for identity checks
        // hence we do not need to persist the authorization policies that represent the target service.
        static void SerializeCachedToken(Stream stream, Uri target, Uri issuer, GenericXmlSecurityToken token)
        {
            XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);
            writer.WriteStartElement("Entry");
            writer.WriteElementString("Target", target.AbsoluteUri);
            writer.WriteElementString("Issuer", (issuer == null) ? "" : issuer.AbsoluteUri);

            writer.WriteStartElement("Token");
            writer.WriteStartElement("XML");
            token.TokenXml.WriteTo(writer);
            writer.WriteEndElement();
            SymmetricSecurityKey key = (SymmetricSecurityKey)(token.SecurityKeys[0]);
            writer.WriteElementString("Key", Convert.ToBase64String(key.GetSymmetricKey()));
            writer.WriteElementString("Id", token.Id);
            writer.WriteElementString("ValidFrom", Convert.ToString(token.ValidFrom));
            writer.WriteElementString("ValidTo", Convert.ToString(token.ValidTo));
            WSSecurityTokenSerializer serializer = new WSSecurityTokenSerializer();
            writer.WriteStartElement("InternalTokenReference");
            serializer.WriteKeyIdentifierClause(writer, token.InternalTokenReference);
            writer.WriteEndElement();
            writer.WriteStartElement("ExternalTokenReference");
            serializer.WriteKeyIdentifierClause(writer, token.ExternalTokenReference);
            writer.WriteEndElement();

            writer.WriteEndElement(); // token
            writer.WriteEndElement(); // entry

            writer.Flush();
            stream.Flush();
        }
Exemplo n.º 19
0
 public WSSecurityXXX2005(WSSecurityTokenSerializer tokenSerializer, SamlSerializer samlSerializer)
     : base(tokenSerializer, samlSerializer)
 {
 }
Exemplo n.º 20
0
 public UserNamePasswordTokenEntry(WSSecurityTokenSerializer tokenSerializer)
 {
     _tokenSerializer = tokenSerializer;
 }
 protected BinaryTokenEntry(WSSecurityTokenSerializer tokenSerializer, string valueTypeUri)
 {
     this.tokenSerializer = tokenSerializer;
     this.valueTypeUris = new string[1];
     this.valueTypeUris[0] = valueTypeUri;
 }
Exemplo n.º 22
0
        /// <summary cref="IUserIdentity.GetIdentityToken" />
        public UserIdentityToken GetIdentityToken()
        {
            // check for anonymous.
            if (m_token == null)
            {
                AnonymousIdentityToken token = new AnonymousIdentityToken();
                token.PolicyId = m_policyId;
                return token;
            }

            // return a user name token.
            UserNameSecurityToken usernameToken = m_token as UserNameSecurityToken;

            if (usernameToken != null)
            {
                UserNameIdentityToken token = new UserNameIdentityToken();
                token.PolicyId = m_policyId;
                token.UserName = usernameToken.UserName;
                token.DecryptedPassword = usernameToken.Password;
                return token;
            }

            // return an X509 token.
            X509SecurityToken x509Token = m_token as X509SecurityToken;

            if (x509Token != null)
            {
                X509IdentityToken token = new X509IdentityToken();
                token.PolicyId = m_policyId;
                token.CertificateData = x509Token.Certificate.GetRawCertData();
                token.Certificate = x509Token.Certificate;
                return token;
            }
            
            // handle SAML token.
            SamlSecurityToken samlToken = m_token as SamlSecurityToken;

            if (samlToken != null)
            {
                MemoryStream ostrm = new MemoryStream();      
                XmlTextWriter writer = new XmlTextWriter(ostrm, new UTF8Encoding());   
 
                try
                {
                    SamlSerializer serializer = new SamlSerializer();
                    serializer.WriteToken(samlToken, writer, WSSecurityTokenSerializer.DefaultInstance);
                }
                finally
                {
                    writer.Close();
                }

                IssuedIdentityToken wssToken = new IssuedIdentityToken();
                wssToken.PolicyId = m_policyId;
                wssToken.DecryptedTokenData = ostrm.ToArray();

                return wssToken;
            }

            // return a WSS token by default.
            if (m_token != null)
            {
                MemoryStream ostrm = new MemoryStream();
                XmlWriter writer = new XmlTextWriter(ostrm, new UTF8Encoding());

                try
                {
                    WSSecurityTokenSerializer serializer = new WSSecurityTokenSerializer();
                    serializer.WriteToken(writer, m_token);
                }
                finally
                {
                    writer.Close();
                }

                IssuedIdentityToken wssToken = new IssuedIdentityToken();
                wssToken.PolicyId = m_policyId;
                wssToken.DecryptedTokenData = ostrm.ToArray();

                return wssToken;
            }

            return null;
        }
Exemplo n.º 23
0
 public WSSecurityJan2004(WSSecurityTokenSerializer tokenSerializer, SamlSerializer samlSerializer)
 {
     WSSecurityTokenSerializer = tokenSerializer;
     _samlSerializer           = samlSerializer;
 }
Exemplo n.º 24
0
 public WSTrustDec2005(WSSecurityTokenSerializer tokenSerializer)
     : base(tokenSerializer)
 {
 }
        private Collection<XmlElement> NormalizeAdditionalParameters(Collection<XmlElement> additionalParameters,
                                                                     TrustDriver driver,
                                                                     bool clientSideClaimTypeRequirementsSpecified)
        {
            // Ensure STS trust version is one of the currently supported versions: Feb 05 / Trust 1.3
            Fx.Assert(((driver.StandardsManager.TrustVersion == TrustVersion.WSTrustFeb2005) ||
                                           (driver.StandardsManager.TrustVersion == TrustVersion.WSTrust13)),
                                           "Unsupported trust version specified for the STS.");

            // We have a mismatch. Make a local copy of additionalParameters for making any potential modifications 
            // as part of normalization
            Collection<XmlElement> tmpCollection = new Collection<XmlElement>();
            foreach (XmlElement e in additionalParameters)
            {
                tmpCollection.Add(e);
            }


            // 1. For Trust 1.3 EncryptionAlgorithm, CanonicalizationAlgorithm and KeyWrapAlgorithm should not be
            //    specified as top-level element if "SecondaryParameters" element already specifies this.
            if (driver.StandardsManager.TrustVersion == TrustVersion.WSTrust13)
            {
                Fx.Assert(driver.GetType() == typeof(WSTrustDec2005.DriverDec2005), "Invalid Trust Driver specified for Trust 1.3.");

                XmlElement encryptionAlgorithmElement = null;
                XmlElement canonicalizationAlgorithmElement = null;
                XmlElement keyWrapAlgorithmElement = null;
                XmlElement secondaryParameter = null;

                for (int i = 0; i < tmpCollection.Count; ++i)
                {
                    string algorithm;

                    if (driver.IsEncryptionAlgorithmElement(tmpCollection[i], out algorithm))
                    {
                        encryptionAlgorithmElement = tmpCollection[i];
                    }
                    else if (driver.IsCanonicalizationAlgorithmElement(tmpCollection[i], out algorithm))
                    {
                        canonicalizationAlgorithmElement = tmpCollection[i];
                    }
                    else if (driver.IsKeyWrapAlgorithmElement(tmpCollection[i], out algorithm))
                    {
                        keyWrapAlgorithmElement = tmpCollection[i];
                    }
                    else if (((WSTrustDec2005.DriverDec2005)driver).IsSecondaryParametersElement(tmpCollection[i]))
                    {
                        secondaryParameter = tmpCollection[i];
                    }
                }

                if (secondaryParameter != null)
                {
                    foreach (XmlNode node in secondaryParameter.ChildNodes)
                    {
                        XmlElement child = node as XmlElement;
                        if (child != null)
                        {
                            string algorithm = null;

                            if (driver.IsEncryptionAlgorithmElement(child, out algorithm) && (encryptionAlgorithmElement != null))
                            {
                                tmpCollection.Remove(encryptionAlgorithmElement);
                            }
                            else if (driver.IsCanonicalizationAlgorithmElement(child, out algorithm) && (canonicalizationAlgorithmElement != null))
                            {
                                tmpCollection.Remove(canonicalizationAlgorithmElement);
                            }
                            else if (driver.IsKeyWrapAlgorithmElement(child, out algorithm) && (keyWrapAlgorithmElement != null))
                            {
                                tmpCollection.Remove(keyWrapAlgorithmElement);
                            }
                        }
                    }
                }
            }

            // 2. Check for Mismatch.
            //      a. Trust Feb 2005 -> Trust 1.3. do the following,
            //          (i) Copy EncryptionAlgorithm and CanonicalizationAlgorithm as the top-level elements.
            //              Note, this is in contradiction to step 1. But we don't have a choice here as we cannot say from the 
            //              Additional Parameters section in the config what came from the service and what came from the client.
            //          (ii) Convert SignWith and EncryptWith elements to Trust 1.3 namespace.
            //      b. For Trust 1.3 -> Trust Feb 2005, do the following,
            //          (i) Find EncryptionAlgorithm, CanonicalizationAlgorithm from inside the "SecondaryParameters" element. 
            //              If found, then promote these as the top-level elements replacing the existing values.
            //          (ii) Convert the SignWith and EncryptWith elements to the Trust Feb 2005 namespace and drop the KeyWrapAlgorithm
            //               element.

            // make an optimistic check to detect mismatched trust-versions between STS and RP
            bool mismatch = (((driver.StandardsManager.TrustVersion == TrustVersion.WSTrustFeb2005) &&
                              !CollectionContainsElementsWithTrustNamespace(additionalParameters, TrustFeb2005Strings.Namespace)) ||
                             ((driver.StandardsManager.TrustVersion == TrustVersion.WSTrust13) &&
                              !CollectionContainsElementsWithTrustNamespace(additionalParameters, TrustDec2005Strings.Namespace)));
            // if no mismatch, return unmodified collection
            if (!mismatch)
            {
                return tmpCollection;
            }

            // 2.a
            // If we are talking to a Trust 1.3 STS, replace any Feb '05 algorithm parameters with their Trust 1.3 counterparts
            if (driver.StandardsManager.TrustVersion == TrustVersion.WSTrust13)
            {
                SecurityStandardsManager trustFeb2005StandardsManager = SecurityStandardsManager.DefaultInstance;
                // the following cast is guaranteed to succeed
                WSTrustFeb2005.DriverFeb2005 trustFeb2005Driver = (WSTrustFeb2005.DriverFeb2005)trustFeb2005StandardsManager.TrustDriver;

                for (int i = 0; i < tmpCollection.Count; i++)
                {
                    string algorithmParameter = string.Empty;

                    if (trustFeb2005Driver.IsSignWithElement(tmpCollection[i], out algorithmParameter))
                    {
                        tmpCollection[i] = driver.CreateSignWithElement(algorithmParameter);
                    }
                    else if (trustFeb2005Driver.IsEncryptWithElement(tmpCollection[i], out algorithmParameter))
                    {
                        tmpCollection[i] = driver.CreateEncryptWithElement(algorithmParameter);
                    }
                    else if (trustFeb2005Driver.IsEncryptionAlgorithmElement(tmpCollection[i], out algorithmParameter))
                    {
                        tmpCollection[i] = driver.CreateEncryptionAlgorithmElement(algorithmParameter);
                    }
                    else if (trustFeb2005Driver.IsCanonicalizationAlgorithmElement(tmpCollection[i], out algorithmParameter))
                    {
                        tmpCollection[i] = driver.CreateCanonicalizationAlgorithmElement(algorithmParameter);
                    }
                }
            }
            else
            {
                // 2.b
                // We are talking to a Feb 05 STS. Filter out any SecondaryParameters element.
                Collection<XmlElement> childrenToPromote = null;
                WSSecurityTokenSerializer trust13Serializer = new WSSecurityTokenSerializer(SecurityVersion.WSSecurity11,
                                                                                            TrustVersion.WSTrust13,
                                                                                            SecureConversationVersion.WSSecureConversation13,
                                                                                            true, null, null, null);
                SecurityStandardsManager trust13StandardsManager = new SecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12, trust13Serializer);
                // the following cast is guaranteed to succeed
                WSTrustDec2005.DriverDec2005 trust13Driver = (WSTrustDec2005.DriverDec2005)trust13StandardsManager.TrustDriver;

                foreach (XmlElement parameter in tmpCollection)
                {
                    // check if SecondaryParameters is present
                    if (trust13Driver.IsSecondaryParametersElement(parameter))
                    {
                        childrenToPromote = new Collection<XmlElement>();
                        // walk SecondaryParameters and collect any 'non-standard' children
                        foreach (XmlNode innerNode in parameter.ChildNodes)
                        {
                            XmlElement innerElement = innerNode as XmlElement;
                            if ((innerElement != null) && CanPromoteToRoot(innerElement, trust13Driver, clientSideClaimTypeRequirementsSpecified))
                            {
                                childrenToPromote.Add(innerElement);
                            }
                        }

                        // remove SecondaryParameters element
                        tmpCollection.Remove(parameter);

                        // we are done - break out of the loop
                        break;
                    }
                }

                // Probe of standard Trust elements and remember them.
                if ((childrenToPromote != null) && (childrenToPromote.Count > 0))
                {
                    XmlElement encryptionElement = null;
                    string encryptionAlgorithm = String.Empty;

                    XmlElement canonicalizationElement = null;
                    string canonicalizationAlgoritm = String.Empty;

                    XmlElement requiredClaimsElement = null;
                    Collection<XmlElement> requiredClaims = null;

                    Collection<XmlElement> processedElements = new Collection<XmlElement>();

                    foreach (XmlElement e in childrenToPromote)
                    {
                        if ((encryptionElement == null) && trust13Driver.IsEncryptionAlgorithmElement(e, out encryptionAlgorithm))
                        {
                            encryptionElement = driver.CreateEncryptionAlgorithmElement(encryptionAlgorithm);
                            processedElements.Add(e);
                        }
                        else if ((canonicalizationElement == null) && trust13Driver.IsCanonicalizationAlgorithmElement(e, out canonicalizationAlgoritm))
                        {
                            canonicalizationElement = driver.CreateCanonicalizationAlgorithmElement(canonicalizationAlgoritm);
                            processedElements.Add(e);
                        }
                        else if ((requiredClaimsElement == null) && trust13Driver.TryParseRequiredClaimsElement(e, out requiredClaims))
                        {
                            requiredClaimsElement = driver.CreateRequiredClaimsElement(requiredClaims);
                            processedElements.Add(e);
                        }
                    }

                    for (int i = 0; i < processedElements.Count; ++i)
                    {
                        childrenToPromote.Remove(processedElements[i]);
                    }

                    XmlElement keyWrapAlgorithmElement = null;

                    // Replace the appropriate elements.
                    for (int i = 0; i < tmpCollection.Count; ++i)
                    {
                        string algorithmParameter;
                        Collection<XmlElement> reqClaims;

                        if (trust13Driver.IsSignWithElement(tmpCollection[i], out algorithmParameter))
                        {
                            tmpCollection[i] = driver.CreateSignWithElement(algorithmParameter);
                        }
                        else if (trust13Driver.IsEncryptWithElement(tmpCollection[i], out algorithmParameter))
                        {
                            tmpCollection[i] = driver.CreateEncryptWithElement(algorithmParameter);
                        }
                        else if (trust13Driver.IsEncryptionAlgorithmElement(tmpCollection[i], out algorithmParameter) && (encryptionElement != null))
                        {
                            tmpCollection[i] = encryptionElement;
                            encryptionElement = null;
                        }
                        else if (trust13Driver.IsCanonicalizationAlgorithmElement(tmpCollection[i], out algorithmParameter) && (canonicalizationElement != null))
                        {
                            tmpCollection[i] = canonicalizationElement;
                            canonicalizationElement = null;
                        }
                        else if (trust13Driver.IsKeyWrapAlgorithmElement(tmpCollection[i], out algorithmParameter) && (keyWrapAlgorithmElement == null))
                        {
                            keyWrapAlgorithmElement = tmpCollection[i];
                        }
                        else if (trust13Driver.TryParseRequiredClaimsElement(tmpCollection[i], out reqClaims) && (requiredClaimsElement != null))
                        {
                            tmpCollection[i] = requiredClaimsElement;
                            requiredClaimsElement = null;
                        }
                    }

                    if (keyWrapAlgorithmElement != null)
                    {
                        // Remove KeyWrapAlgorithmElement as this is not define in Trust Feb 2005.
                        tmpCollection.Remove(keyWrapAlgorithmElement);
                    }

                    // Add the remaining elements to the additionaParameters list to the end.
                    if (encryptionElement != null) tmpCollection.Add(encryptionElement);
                    if (canonicalizationElement != null) tmpCollection.Add(canonicalizationElement);
                    if (requiredClaimsElement != null) tmpCollection.Add(requiredClaimsElement);

                    if (childrenToPromote.Count > 0)
                    {
                        // There are some non-standard elements. Just bump them to the top-level element.
                        for (int i = 0; i < childrenToPromote.Count; ++i)
                        {
                            tmpCollection.Add(childrenToPromote[i]);
                        }
                    }
                }

            }

            return tmpCollection;
        }
Exemplo n.º 26
0
 public SamlTokenEntry(WSSecurityTokenSerializer tokenSerializer, SamlSerializer samlSerializer)
     : base(tokenSerializer, samlSerializer)
 {
 }
 public WSSecurityJan2004(WSSecurityTokenSerializer tokenSerializer, SamlSerializer samlSerializer)
 {
     this.tokenSerializer = tokenSerializer;
     this.samlSerializer = samlSerializer;
 }
Exemplo n.º 28
0
 public X509TokenEntry(WSSecurityTokenSerializer tokenSerializer)
     : base(tokenSerializer, ValueTypeAbsoluteUri)
 {
 }
 public WrappedKeyTokenEntry(WSSecurityTokenSerializer tokenSerializer)
 {
     this.tokenSerializer = tokenSerializer;
 }
Exemplo n.º 30
0
 protected BinaryTokenEntry(WSSecurityTokenSerializer tokenSerializer, string valueTypeUri)
 {
     _tokenSerializer  = tokenSerializer;
     _valueTypeUris    = new string[1];
     _valueTypeUris[0] = valueTypeUri;
 }
        /// <summary>
        /// Validates a Kerberos WSS user token.
        /// </summary>
        private SecurityToken ParseAndVerifyKerberosToken(byte[] tokenData)
        {
            XmlDocument document = new XmlDocument();
            XmlNodeReader reader = null;

            try
            {
                document.InnerXml = new UTF8Encoding().GetString(tokenData).Trim();
                reader = new XmlNodeReader(document.DocumentElement);

                SecurityToken securityToken = new WSSecurityTokenSerializer().ReadToken(reader, null);
                System.IdentityModel.Tokens.KerberosReceiverSecurityToken receiver = securityToken as KerberosReceiverSecurityToken;

                KerberosSecurityTokenAuthenticator authenticator = new KerberosSecurityTokenAuthenticator();

                if (authenticator.CanValidateToken(receiver))
                {
                    authenticator.ValidateToken(receiver);
                }

                return securityToken;
            }
            catch (Exception e)
            {
                // construct translation object with default text.
                TranslationInfo info = new TranslationInfo(
                    "InvalidKerberosToken",
                    "en-US",
                    "'{0}' is not a valid Kerberos token.",
                    document.DocumentElement.LocalName);

                // create an exception with a vendor defined sub-code.
                throw new ServiceResultException(new ServiceResult(
                    e,
                    StatusCodes.BadIdentityTokenRejected,
                    "InvalidKerberosToken",
                    Namespaces.UserAuthentication,
                    new LocalizedText(info)));
            }
            finally
            {
                if (reader != null)
                {
                    reader.Close();
                }
            }
        }
 public EncryptedKeyClauseEntry(WSSecurityTokenSerializer tokenSerializer)
 {
     this.tokenSerializer = tokenSerializer;
 }
Exemplo n.º 33
0
 protected WSSecureConversation(WSSecurityTokenSerializer tokenSerializer, int maxKeyDerivationOffset, int maxKeyDerivationLabelLength, int maxKeyDerivationNonceLength)
 {
     WSSecurityTokenSerializer = tokenSerializer ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(tokenSerializer));
     _derivedKeyEntry          = new DerivedKeyTokenEntry(this, maxKeyDerivationOffset, maxKeyDerivationLabelLength, maxKeyDerivationNonceLength);
 }
Exemplo n.º 34
0
 public WrappedKeyTokenEntry(WSSecurityTokenSerializer tokenSerializer)
 {
     _tokenSerializer = tokenSerializer;
 }
 public XmlEncApr2001(WSSecurityTokenSerializer tokenSerializer)
 {
     this.tokenSerializer = tokenSerializer;
 }
Exemplo n.º 36
0
 public XmlDsigSep2000(WSSecurityTokenSerializer tokenSerializer)
 {
     this.tokenSerializer = tokenSerializer;
 }
 public SecurityTokenReferenceXXX2005ClauseEntry(WSSecurityTokenSerializer tokenSerializer, IList <WSSecurityTokenSerializer.StrEntry> strEntries) : base(tokenSerializer, strEntries)
 {
 }
 public EncryptedKeyHashStrEntry(WSSecurityTokenSerializer tokenSerializer) : base(tokenSerializer)
 {
 }
 internal static Collection<RequestSecurityTokenResponse> ExtractIssuances(Message message, MessageSecurityVersion version, WSSecurityTokenSerializer tokenSerializer, string[] actors, XmlQualifiedName expectedAppliesToQName)
 {
     return ExtractIssuances(message, new SecurityStandardsManager(version, tokenSerializer), actors, expectedAppliesToQName);
 }
Exemplo n.º 40
0
		void DefaultValues (WSSecurityTokenSerializer ser)
		{
			Assert.AreEqual (false, ser.EmitBspRequiredAttributes, "#1");
			Assert.AreEqual (128, ser.MaximumKeyDerivationLabelLength, "#2");
			Assert.AreEqual (128, ser.MaximumKeyDerivationNonceLength, "#3");
			Assert.AreEqual (64, ser.MaximumKeyDerivationOffset, "#4");
			Assert.AreEqual (SecurityVersion.WSSecurity11, ser.SecurityVersion, "#5");
		}
 public EncryptedKeyClauseEntry(WSSecurityTokenSerializer tokenSerializer)
 {
     this.tokenSerializer = tokenSerializer;
 }
Exemplo n.º 42
0
		public void ReadWriteTokenDerivedKeyTokenRefToExistent ()
		{
			WSSecurityTokenSerializer serializer =
				new WSSecurityTokenSerializer (true); // emitBSP
			SecurityToken token;
			using (XmlReader xr = XmlReader.Create (new StringReader (derived_key_token1))) {
				token = serializer.ReadToken (xr,
					GetResolver (
						new WrappedKeySecurityToken ("uuid:urn:abc", new byte [32], SecurityAlgorithms.RsaOaepKeyWrap, new X509SecurityToken (cert), null)
					));
			}
			StringWriter sw = new StringWriter ();
			using (XmlWriter w = XmlWriter.Create (sw, GetWriterSettings ())) {
				serializer.WriteToken (w, token);
			}
			Assert.AreEqual (derived_key_token1.Replace ('\'', '"').Replace ("  ", "").Replace ("\n", "").Replace ("\r", ""), sw.ToString ());
		}
 public SamlTokenEntry(WSSecurityTokenSerializer tokenSerializer, SamlSerializer samlSerializer)
     : base(tokenSerializer, samlSerializer)
 {
 }
Exemplo n.º 44
0
		[Category ("NotWorking")] // SslNegoCookieResolver needs updates and/or fixes.
		public void ReadSslnegoSCTNoStateEncoder ()
		{
			string cookie = "QgBCAoNCBpkrdXVpZC03MDlhYjYwOC0yMDA0LTQ0ZDUtYjM5Mi1mM2M1YmY3YzY3ZmItMUIErZ3da7enifVFg+e0dObwRLNCCJ4egLowfrwP4Hgn0lOSqlA2fr0k4NAKgRZX+0BVs2EOnwJ6xkIOjzCAEnLHQMkIQhCPMJC+QxtByQhCFI8wgBJyx0DJCEIWjzCQvkMbQckIAQ==";
			string xml = String.Format (@"<c:SecurityContextToken u:Id='uuid-709ab608-2004-44d5-b392-f3c5bf7c67fb-1' xmlns:c='http://schemas.xmlsoap.org/ws/2005/02/sc' xmlns:u='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd'>
  <c:Identifier>urn:uuid:b76bdd9d-89a7-45f5-83e7-b474e6f044b3</c:Identifier>
  <dnse:Cookie xmlns:dnse='http://schemas.microsoft.com/ws/2006/05/security'>{0}</dnse:Cookie>
</c:SecurityContextToken>", cookie);
			string expectedKey = "gLowfrwP4Hgn0lOSqlA2fr0k4NAKgRZX+0BVs2EOesY=";

			WSSecurityTokenSerializer serializer =
				new WSSecurityTokenSerializer (MessageSecurityVersion.Default.SecurityVersion,
					false,
					new SamlSerializer (),
					new MyStateEncoder (),
					null);
			SecurityContextSecurityToken sct;
			using (XmlReader xr = XmlReader.Create (new StringReader (xml))) {
				// Token is not registered, but is restored from the cookie
				sct = serializer.ReadToken (xr, null) as SecurityContextSecurityToken;
			}
			Assert.IsNotNull (sct, "#1");
			Assert.AreEqual (new UniqueId ("urn:uuid:b76bdd9d-89a7-45f5-83e7-b474e6f044b3"), sct.ContextId, "#2");
			Assert.IsNotNull (sct.AuthorizationPolicies.Count, "#3");
			Assert.AreEqual (0, sct.AuthorizationPolicies.Count, "#4");
			Assert.AreEqual (1, sct.SecurityKeys.Count, "#5");
			Assert.AreEqual (expectedKey, Convert.ToBase64String (((SymmetricSecurityKey) sct.SecurityKeys [0]).GetSymmetricKey ()), "#6");

			byte [] xmlbin = Convert.FromBase64String (cookie);
			XmlDictionary dic = new XmlDictionary ();
			for (int i = 0; i < 12; i++)
				dic.Add ("n" + i);
			XmlDictionaryReader br = XmlDictionaryReader.CreateBinaryReader (xmlbin, 0, xmlbin.Length, dic, new XmlDictionaryReaderQuotas ());
			while (br.LocalName != "n4")
				if (!br.Read ())
					Assert.Fail ("Unxpected binary xmlreader failure.");
			byte [] key = br.ReadElementContentAsBase64 ();
			// Hmm, so, looks like the Cookie binary depends not
			// on SSL protection but on the state encoder ...
			// does it make sense, or is a different key resolved
			// as a result of TLS negotiation?
			Assert.AreEqual (expectedKey, Convert.ToBase64String (key), "#7");
		}
 public KerberosTokenEntry(WSSecurityTokenSerializer tokenSerializer)
     : base(tokenSerializer, new string[] { SecurityJan2004Strings.KerberosTokenTypeGSS, SecurityJan2004Strings.KerberosTokenType1510 })
 {
 }
Exemplo n.º 46
0
		public void DefaultValues ()
		{
			WSSecurityTokenSerializer ser = new WSSecurityTokenSerializer ();
			DefaultValues (ser);
			DefaultValues (WSSecurityTokenSerializer.DefaultInstance);
		}
 public UserNamePasswordTokenEntry(WSSecurityTokenSerializer tokenSerializer)
 {
     this.tokenSerializer = tokenSerializer;
 }
 private Collection<XmlElement> NormalizeAdditionalParameters(Collection<XmlElement> additionalParameters, TrustDriver driver, bool clientSideClaimTypeRequirementsSpecified)
 {
     Collection<XmlElement> collection = new Collection<XmlElement>();
     foreach (XmlElement element in additionalParameters)
     {
         collection.Add(element);
     }
     if (driver.StandardsManager.TrustVersion == TrustVersion.WSTrust13)
     {
         XmlElement item = null;
         XmlElement element3 = null;
         XmlElement element4 = null;
         XmlElement element5 = null;
         for (int i = 0; i < collection.Count; i++)
         {
             string str;
             if (driver.IsEncryptionAlgorithmElement(collection[i], out str))
             {
                 item = collection[i];
             }
             else if (driver.IsCanonicalizationAlgorithmElement(collection[i], out str))
             {
                 element3 = collection[i];
             }
             else if (driver.IsKeyWrapAlgorithmElement(collection[i], out str))
             {
                 element4 = collection[i];
             }
             else if (((WSTrustDec2005.DriverDec2005) driver).IsSecondaryParametersElement(collection[i]))
             {
                 element5 = collection[i];
             }
         }
         if (element5 != null)
         {
             foreach (System.Xml.XmlNode node in element5.ChildNodes)
             {
                 XmlElement element6 = node as XmlElement;
                 if (element6 != null)
                 {
                     string encryptionAlgorithm = null;
                     if (driver.IsEncryptionAlgorithmElement(element6, out encryptionAlgorithm) && (item != null))
                     {
                         collection.Remove(item);
                     }
                     else if (driver.IsCanonicalizationAlgorithmElement(element6, out encryptionAlgorithm) && (element3 != null))
                     {
                         collection.Remove(element3);
                     }
                     else if (driver.IsKeyWrapAlgorithmElement(element6, out encryptionAlgorithm) && (element4 != null))
                     {
                         collection.Remove(element4);
                     }
                 }
             }
         }
     }
     if (((driver.StandardsManager.TrustVersion == TrustVersion.WSTrustFeb2005) && !this.CollectionContainsElementsWithTrustNamespace(additionalParameters, "http://schemas.xmlsoap.org/ws/2005/02/trust")) || ((driver.StandardsManager.TrustVersion == TrustVersion.WSTrust13) && !this.CollectionContainsElementsWithTrustNamespace(additionalParameters, "http://docs.oasis-open.org/ws-sx/ws-trust/200512")))
     {
         if (driver.StandardsManager.TrustVersion == TrustVersion.WSTrust13)
         {
             WSTrustFeb2005.DriverFeb2005 feb = (WSTrustFeb2005.DriverFeb2005) SecurityStandardsManager.DefaultInstance.TrustDriver;
             for (int j = 0; j < collection.Count; j++)
             {
                 string signatureAlgorithm = string.Empty;
                 if (feb.IsSignWithElement(collection[j], out signatureAlgorithm))
                 {
                     collection[j] = driver.CreateSignWithElement(signatureAlgorithm);
                 }
                 else if (feb.IsEncryptWithElement(collection[j], out signatureAlgorithm))
                 {
                     collection[j] = driver.CreateEncryptWithElement(signatureAlgorithm);
                 }
                 else if (feb.IsEncryptionAlgorithmElement(collection[j], out signatureAlgorithm))
                 {
                     collection[j] = driver.CreateEncryptionAlgorithmElement(signatureAlgorithm);
                 }
                 else if (feb.IsCanonicalizationAlgorithmElement(collection[j], out signatureAlgorithm))
                 {
                     collection[j] = driver.CreateCanonicalizationAlgorithmElement(signatureAlgorithm);
                 }
             }
             return collection;
         }
         Collection<XmlElement> collection2 = null;
         WSSecurityTokenSerializer tokenSerializer = new WSSecurityTokenSerializer(SecurityVersion.WSSecurity11, TrustVersion.WSTrust13, SecureConversationVersion.WSSecureConversation13, true, null, null, null);
         SecurityStandardsManager manager2 = new SecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12, tokenSerializer);
         WSTrustDec2005.DriverDec2005 trustDriver = (WSTrustDec2005.DriverDec2005) manager2.TrustDriver;
         foreach (XmlElement element7 in collection)
         {
             if (trustDriver.IsSecondaryParametersElement(element7))
             {
                 collection2 = new Collection<XmlElement>();
                 foreach (System.Xml.XmlNode node2 in element7.ChildNodes)
                 {
                     XmlElement innerElement = node2 as XmlElement;
                     if ((innerElement != null) && this.CanPromoteToRoot(innerElement, trustDriver, clientSideClaimTypeRequirementsSpecified))
                     {
                         collection2.Add(innerElement);
                     }
                 }
                 collection.Remove(element7);
                 break;
             }
         }
         if ((collection2 != null) && (collection2.Count > 0))
         {
             XmlElement element9 = null;
             string str4 = string.Empty;
             XmlElement element10 = null;
             string canonicalizationAlgorithm = string.Empty;
             XmlElement element11 = null;
             Collection<XmlElement> requiredClaims = null;
             Collection<XmlElement> collection4 = new Collection<XmlElement>();
             foreach (XmlElement element12 in collection2)
             {
                 if ((element9 == null) && trustDriver.IsEncryptionAlgorithmElement(element12, out str4))
                 {
                     element9 = driver.CreateEncryptionAlgorithmElement(str4);
                     collection4.Add(element12);
                 }
                 else if ((element10 == null) && trustDriver.IsCanonicalizationAlgorithmElement(element12, out canonicalizationAlgorithm))
                 {
                     element10 = driver.CreateCanonicalizationAlgorithmElement(canonicalizationAlgorithm);
                     collection4.Add(element12);
                 }
                 else if ((element11 == null) && trustDriver.TryParseRequiredClaimsElement(element12, out requiredClaims))
                 {
                     element11 = driver.CreateRequiredClaimsElement(requiredClaims);
                     collection4.Add(element12);
                 }
             }
             for (int k = 0; k < collection4.Count; k++)
             {
                 collection2.Remove(collection4[k]);
             }
             XmlElement element13 = null;
             for (int m = 0; m < collection.Count; m++)
             {
                 string str6;
                 if (trustDriver.IsSignWithElement(collection[m], out str6))
                 {
                     collection[m] = driver.CreateSignWithElement(str6);
                 }
                 else if (trustDriver.IsEncryptWithElement(collection[m], out str6))
                 {
                     collection[m] = driver.CreateEncryptWithElement(str6);
                 }
                 else if (trustDriver.IsEncryptionAlgorithmElement(collection[m], out str6) && (element9 != null))
                 {
                     collection[m] = element9;
                     element9 = null;
                 }
                 else if (trustDriver.IsCanonicalizationAlgorithmElement(collection[m], out str6) && (element10 != null))
                 {
                     collection[m] = element10;
                     element10 = null;
                 }
                 else if (trustDriver.IsKeyWrapAlgorithmElement(collection[m], out str6) && (element13 == null))
                 {
                     element13 = collection[m];
                 }
                 else
                 {
                     Collection<XmlElement> collection5;
                     if (trustDriver.TryParseRequiredClaimsElement(collection[m], out collection5) && (element11 != null))
                     {
                         collection[m] = element11;
                         element11 = null;
                     }
                 }
             }
             if (element13 != null)
             {
                 collection.Remove(element13);
             }
             if (element9 != null)
             {
                 collection.Add(element9);
             }
             if (element10 != null)
             {
                 collection.Add(element10);
             }
             if (element11 != null)
             {
                 collection.Add(element11);
             }
             if (collection2.Count <= 0)
             {
                 return collection;
             }
             for (int n = 0; n < collection2.Count; n++)
             {
                 collection.Add(collection2[n]);
             }
         }
     }
     return collection;
 }
 public X509TokenEntry(WSSecurityTokenSerializer tokenSerializer)
     : base(tokenSerializer, ValueTypeAbsoluteUri)
 {
 }
Exemplo n.º 50
0
 public WSSecurityJan2004(WSSecurityTokenSerializer tokenSerializer, SamlSerializer samlSerializer)
 {
     this.tokenSerializer = tokenSerializer;
     this.samlSerializer  = samlSerializer;
 }
Exemplo n.º 51
0
 public KerberosTokenEntry(WSSecurityTokenSerializer tokenSerializer)
     : base(tokenSerializer, new string[] { SecurityJan2004Strings.KerberosTokenTypeGSS, SecurityJan2004Strings.KerberosTokenType1510 })
 {
 }
        // Methods of BodyWriter
        /// <summary>
        /// Writes out an XML representation of the instance.
        /// </summary>
        /// <param name="writer">The writer to be used to write out the XML content</param>
        protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
        {
            // Write out the wst:RequestSecurityTokenResponse start tag
            writer.WriteStartElement(Constants.Trust.Elements.RequestSecurityTokenResponse, Constants.Trust.NamespaceUri);

            // If we have a non-null, non-empty tokenType...
            if (this.TokenType != null && this.TokenType.Length > 0)
            {
                // Write out the wst:TokenType start tag
                writer.WriteStartElement(Constants.Trust.Elements.TokenType, Constants.Trust.NamespaceUri);
                // Write out the tokenType string
                writer.WriteString(this.TokenType);
                writer.WriteEndElement(); // wst:TokenType
            }

            // Create a serializer that knows how to write out security tokens
            WSSecurityTokenSerializer ser = new WSSecurityTokenSerializer();

            // If we have a requestedSecurityToken...
            if (this.requestedSecurityToken != null)
            {
                // Write out the wst:RequestedSecurityToken start tag
                writer.WriteStartElement(Constants.Trust.Elements.RequestedSecurityToken, Constants.Trust.NamespaceUri);
                // Write out the requested token using the serializer
                ser.WriteToken(writer, requestedSecurityToken);
                writer.WriteEndElement(); // wst:RequestedSecurityToken
            }

            // If we have a requestedAttachedReference...
            if ( this.requestedAttachedReference != null )
            {
                // Write out the wst:RequestedAttachedReference start tag
                writer.WriteStartElement(Constants.Trust.Elements.RequestedAttachedReference, Constants.Trust.NamespaceUri);
                // Write out the reference using the serializer
                ser.WriteKeyIdentifierClause ( writer, this.requestedAttachedReference );
                writer.WriteEndElement(); // wst:RequestedAttachedReference
            }

            // If we have a requestedUnattachedReference...
            if ( this.requestedUnattachedReference != null )
            {
                // Write out the wst:RequestedUnattachedReference start tag
                writer.WriteStartElement(Constants.Trust.Elements.RequestedUnattachedReference, Constants.Trust.NamespaceUri);
                // Write out the reference using the serializer
                ser.WriteKeyIdentifierClause ( writer, this.requestedUnattachedReference );
                writer.WriteEndElement(); // wst:RequestedAttachedReference
            }

            // If we have a non-null appliesTo
            if (this.AppliesTo != null)
            {
                // Write out the wsp:AppliesTo start tag
                writer.WriteStartElement(Constants.Policy.Elements.AppliesTo, Constants.Policy.NamespaceUri);
                // Write the appliesTo in WS-Addressing 1.0 format
                this.AppliesTo.WriteTo(AddressingVersion.WSAddressing10, writer);
                writer.WriteEndElement(); // wsp:AppliesTo
            }

            // If the requestedProofToken is non-null, then the STS is providing all the key material...
            if (this.requestedProofToken != null)
            {
                // Write the wst:RequestedProofToken start tag
                writer.WriteStartElement(Constants.Trust.Elements.RequestedProofToken, Constants.Trust.NamespaceUri);
                // Write the proof token using the serializer
                ser.WriteToken(writer, requestedProofToken);
                writer.WriteEndElement(); // wst:RequestedSecurityToken
            }

            // If issuerEntropy is non-null and computeKey is true, then combined entropy is being used...
            if(this.issuerEntropy != null && this.computeKey )
            {
                // Write the wst:RequestedProofToken start tag
                writer.WriteStartElement(Constants.Trust.Elements.RequestedProofToken, Constants.Trust.NamespaceUri);
                // Write the wst:ComputeKey start tag
                writer.WriteStartElement(Constants.Trust.Elements.ComputedKey, Constants.Trust.NamespaceUri);
                // Write the PSHA1 algorithm value
                writer.WriteValue(Constants.Trust.ComputedKeyAlgorithms.PSHA1);
                writer.WriteEndElement(); // wst:ComputedKey
                writer.WriteEndElement(); // wst:RequestedSecurityToken

                // Write the wst:Entropy start tag
                writer.WriteStartElement(Constants.Trust.Elements.Entropy, Constants.Trust.NamespaceUri);
                // Write the issuerEntropy out using the serializer
                ser.WriteToken(writer, this.issuerEntropy);
                writer.WriteEndElement(); // wst:Entropy
            }

            writer.WriteEndElement(); // wst:RequestSecurityTokenResponse
        }
 public X509ThumbprintStrEntry(WSSecurityTokenSerializer tokenSerializer) : base(tokenSerializer)
 {
 }
        // Methods of BodyWriter
        protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
        {
            writer.WriteStartElement(Constants.Trust.Elements.RequestSecurityTokenResponse, Constants.Trust.NamespaceUri);

            if (this.TokenType != null && this.TokenType.Length > 0)
            {
                writer.WriteStartElement(Constants.Trust.Elements.TokenType, Constants.Trust.NamespaceUri);
                writer.WriteString(this.TokenType);
                writer.WriteEndElement(); // wst:TokenType
            }

            WSSecurityTokenSerializer ser = new WSSecurityTokenSerializer();

            if (this.RequestedSecurityToken != null)
            {
                writer.WriteStartElement(Constants.Trust.Elements.RequestedSecurityToken, Constants.Trust.NamespaceUri);                
                ser.WriteToken(writer, this.RequestedSecurityToken);                    
                writer.WriteEndElement(); // wst:RequestedSecurityToken
            }

            if ( this.RequestedAttachedReference != null )
            {
                writer.WriteStartElement(Constants.Trust.Elements.RequestedAttachedReference, Constants.Trust.NamespaceUri);
                ser.WriteKeyIdentifierClause ( writer, this.RequestedAttachedReference);
                writer.WriteEndElement(); // wst:RequestedAttachedReference
            }

            if ( this.RequestedUnattachedReference != null )
            {
                writer.WriteStartElement(Constants.Trust.Elements.RequestedUnattachedReference, Constants.Trust.NamespaceUri);
                ser.WriteKeyIdentifierClause ( writer, this.RequestedUnattachedReference);
                writer.WriteEndElement(); // wst:RequestedAttachedReference
            }

            if (this.AppliesTo != null)
            {
                writer.WriteStartElement(Constants.Policy.Elements.AppliesTo, Constants.Policy.NamespaceUri);
                this.AppliesTo.WriteTo(AddressingVersion.WSAddressing10, writer);
                writer.WriteEndElement(); // wsp:AppliesTo
            }

            if (this.RequestedProofToken != null)// Issuer entropy; write RPT only
            {
                writer.WriteStartElement(Constants.Trust.Elements.RequestedProofToken, Constants.Trust.NamespaceUri);
                ser.WriteToken(writer, this.RequestedProofToken);
                writer.WriteEndElement(); // wst:RequestedSecurityToken
            }

            if(this.IssuerEntropy != null && this.ComputeKey) // Combined entropy; write RPT and Entropy
            {
                writer.WriteStartElement(Constants.Trust.Elements.RequestedProofToken, Constants.Trust.NamespaceUri);
                writer.WriteStartElement(Constants.Trust.Elements.ComputedKey, Constants.Trust.NamespaceUri);
                writer.WriteValue(Constants.Trust.ComputedKeyAlgorithms.PSHA1);
                writer.WriteEndElement(); // wst:ComputedKey
                writer.WriteEndElement(); // wst:RequestedSecurityToken

                if (this.IssuerEntropy!= null)
                {
                    writer.WriteStartElement(Constants.Trust.Elements.Entropy, Constants.Trust.NamespaceUri);                    
                    ser.WriteToken(writer, this.IssuerEntropy);
                    writer.WriteEndElement(); // wst:Entropy
                }
            }

            writer.WriteEndElement(); // wst:RequestSecurityTokenResponse
        }
Exemplo n.º 55
0
        static void PopulateCache(Dictionary<Key, GenericXmlSecurityToken> cache, Stream stream)
        {
            XmlTextReader reader = new XmlTextReader(stream);
            while (reader.IsStartElement("Entry"))
            {
                reader.ReadStartElement();
                Uri target = new Uri(reader.ReadElementString("Target"));
                string issuerStr = reader.ReadElementString("Issuer");
                Uri issuer = string.IsNullOrEmpty(issuerStr) ? null : new Uri(issuerStr);

                reader.ReadStartElement("Token");
                reader.ReadStartElement("XML");
                XmlDocument doc = new XmlDocument();
                XmlElement tokenXml = doc.ReadNode(reader) as XmlElement;
                reader.ReadEndElement();
                byte[] key = Convert.FromBase64String(reader.ReadElementString("Key"));
                reader.ReadElementString("Id");
                DateTime validFrom = Convert.ToDateTime(reader.ReadElementString("ValidFrom"));
                DateTime validTo = Convert.ToDateTime(reader.ReadElementString("ValidTo"));
                WSSecurityTokenSerializer serializer = new WSSecurityTokenSerializer();
                reader.ReadStartElement("InternalTokenReference");
                SecurityKeyIdentifierClause internalReference = serializer.ReadKeyIdentifierClause(reader);
                reader.ReadEndElement();
                reader.ReadStartElement("ExternalTokenReference");
                SecurityKeyIdentifierClause externalReference = serializer.ReadKeyIdentifierClause(reader);
                reader.ReadEndElement();
                reader.ReadEndElement(); // token
                reader.ReadEndElement(); // entry

                List<IAuthorizationPolicy> policies = new List<IAuthorizationPolicy>();
                GenericXmlSecurityToken token = new GenericXmlSecurityToken(tokenXml, new BinarySecretSecurityToken(key), validFrom, validTo, internalReference, externalReference,
                    new ReadOnlyCollection<IAuthorizationPolicy>(policies));
                cache.Add(new Key(target, issuer), token);
            }
        }
		public WSTrustSecurityTokenService ()
		{
			serializer = WSSecurityTokenSerializer.DefaultInstance;
		}
Exemplo n.º 57
0
 internal static Collection <RequestSecurityTokenResponse> ExtractIssuances(Message message, MessageSecurityVersion version, WSSecurityTokenSerializer tokenSerializer, string[] actors, XmlQualifiedName expectedAppliesToQName)
 {
     return(ExtractIssuances(message, new SecurityStandardsManager(version, tokenSerializer), actors, expectedAppliesToQName));
 }
Exemplo n.º 58
0
 public WrappedKeyTokenEntry(WSSecurityTokenSerializer tokenSerializer)
     : base(tokenSerializer)
 {
 }
Exemplo n.º 59
0
 public WSTrustFeb2005(WSSecurityTokenSerializer tokenSerializer)
     : base(tokenSerializer)
 {
 }
Exemplo n.º 60
0
 public WSTrust(WSSecurityTokenSerializer tokenSerializer)
 {
     _tokenSerializer = tokenSerializer;
 }