Beispiel #1
0
        public void Serialize()
        {
            var serializer = new XmlSerializer(typeof(SubscribeRequestMessageBody));

            var message = new SubscribeRequestMessageBody();
            // Supply mock Delivery
            var delivery = new Mock <Delivery>(MockBehavior.Strict);

            delivery.As <IXmlSerializable>().Setup(item => item.WriteXml(It.IsAny <XmlWriter>()));
            message.Delivery = delivery.Object;
            message.EndTo    = EndpointAddressAugust2004.FromEndpointAddress(new EndpointAddress("http://tempuri.org/endTo"));
            // Supply mock Expires
            var expires = new Mock <Expires>(MockBehavior.Strict);

            expires.As <IXmlSerializable>().Setup(item => item.WriteXml(It.IsAny <XmlWriter>()));
            message.Expires = expires.Object;
            message.Filter  = new XPathMessageFilter(@"/foo");

            XElement xml;

            using (var stream = new MemoryStream())
            {
                serializer.Serialize(stream, message);
                stream.Position = 0;
                xml             = XElement.Load(stream);
            }
            var areEqual = XNode.DeepEquals(XElement.Parse("<wse:Subscribe xmlns:wse='http://schemas.xmlsoap.org/ws/2004/08/eventing'><wse:EndTo><Address xmlns='http://schemas.xmlsoap.org/ws/2004/08/addressing'>http://tempuri.org/endTo</Address></wse:EndTo><wse:Filter>/foo</wse:Filter></wse:Subscribe>"), xml.FirstNode);

            Assert.IsTrue(areEqual);
        }
Beispiel #2
0
        /// <summary>
        /// Replaces the <see cref="Identifier"/> value, if any, with the supplied <paramref name="id"/>, if any.
        /// </summary>
        /// <param name="id">The new identifier value to use, or clear if null.</param>
        public void CreateIdentifierHeader(Guid?id)
        {
            var builder = new EndpointAddressBuilder(this.EndpointAddress.ToEndpointAddress());
            var header  = builder.Headers.FirstOrDefault(a => a.Name == "Identifier" && a.Namespace == Constants.WsEventing.Namespace);

            if (id == null)
            {
                if (header == null)
                {
                    return;
                }

                var wasRemoved = builder.Headers.Remove(header);
                Debug.Assert(wasRemoved);
            }
            else
            {
                if (header != null)
                {
                    var wasRemoved = builder.Headers.Remove(header);
                    Debug.Assert(wasRemoved);
                }
                var uuid = new UniqueId(id.Value);
                header = AddressHeader.CreateAddressHeader("Identifier", Constants.WsEventing.Namespace, uuid.ToString());

                builder.Headers.Add(header);
            }

            this.epa = EndpointAddressAugust2004.FromEndpointAddress(builder.ToEndpointAddress());
        }
        /// <summary>
        /// Converts and EndpointReferenceType to an EndpointAddressAugust2004
        /// </summary>
        /// <returns>Returns an EndpointAddressAugust2004 object</returns>
        public EndpointAddressAugust2004 ToEndpointReference()
        {
            var builder = new StringBuilder();

            using (var writer = XmlDictionaryWriter.CreateDictionaryWriter(XmlWriter.Create(builder, new XmlWriterSettings()
            {
                Indent = false, OmitXmlDeclaration = true
            })))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(EndpointReferenceType));

                serializer.Serialize(writer, this);
            }

            using (var reader = XmlDictionaryReader.CreateDictionaryReader(XmlReader.Create(new StringReader(builder.ToString()), new XmlReaderSettings()
            {
                IgnoreWhitespace = true
            })))
            {
                builder.Clear();

                var address = EndpointAddress.ReadFrom(AddressingVersion.WSAddressingAugust2004, reader);

                return(EndpointAddressAugust2004.FromEndpointAddress(address));
            }
        }
        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            if (reader.IsStartElement("Delivery", Constants.WsEventing.Namespace) == false)
            {
                throw new XmlException("Invalid Element, it must be 'Delivery'");
            }

            String modeAsString = reader.GetAttribute("Mode", Constants.WsEventing.Namespace);

            this.DeliveryMode = String.IsNullOrEmpty(modeAsString) ? DeliveryMode = new Uri(Constants.WsEventing.DeliverModes.Push) : new Uri(modeAsString);

            reader.ReadToDescendant("NotifyTo", Constants.WsEventing.Namespace);
            this.NotifyTo = EndpointAddressAugust2004.FromEndpointAddress(EndpointAddress.ReadFrom(AddressingVersion.WSAddressingAugust2004, reader));
            if (this.NotifyTo == null)
            {
                throw new XmlException("Missing element 'NotifyTo'");
            }

            while (reader.NodeType != XmlNodeType.EndElement)
            {
                var additionalElement = XElement.Parse(reader.ReadOuterXml());
                this.additionalElements.Add(additionalElement);
            }

            reader.ReadEndElement();
        }
 public VolatileEnlistmentInDoubtRecordSchema10(Guid enlistmentId, EndpointAddress replyTo) : base(enlistmentId)
 {
     base.schemaId = "http://schemas.microsoft.com/2006/08/ServiceModel/VolatileEnlistmentInDoubtTraceRecord";
     if (replyTo != null)
     {
         this.replyTo = EndpointAddressAugust2004.FromEndpointAddress(replyTo);
     }
 }
Beispiel #6
0
 public RecoverCoordinatorRecordSchema10(string transactionId, EndpointAddress coordinatorService) : base(transactionId)
 {
     base.schemaId = "http://schemas.microsoft.com/2006/08/ServiceModel/RecoverCoordinatorTraceRecord";
     if (coordinatorService != null)
     {
         this.coordinatorService = EndpointAddressAugust2004.FromEndpointAddress(coordinatorService);
     }
 }
Beispiel #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SubscriptionManager"/> class from the supplied <paramref name="address"/> and <paramref name="id"/>.
        /// </summary>
        /// <remarks>
        /// This overload is used in similar fashion to <see cref="SubscriptionManager(Uri, WsEventing.Identifier)">this constructor</see> with the
        /// variation of supplying a full set of WSA reference parameters in the created EPA. This can be used to perform the direct creation or
        /// manipulation of the EPA (including the presence of an <see cref="WsEventing.Identifier"/> element).
        /// </remarks>
        /// <param name="address">The endpoint address of the subscription manager used by the event sink to manage subscriptions for this event source.</param>
        /// <param name="headers">A collection of <see cref="AddressHeader">headers</see> that re contained as part of the WSA reference parameters in the created EPA.</param>
        public SubscriptionManager(Uri address, IEnumerable <AddressHeader> headers)
        {
            Contract.Requires(address != null, "address");
            Contract.Requires(headers != null, "headers");
            Contract.Requires(Contract.ForAll(headers, item => item != null));

            this.epa = EndpointAddressAugust2004.FromEndpointAddress(new EndpointAddress(address, headers.ToArray()));
        }
 public RegisterParticipantRecordSchema10(string transactionId, Guid enlistmentId, ControlProtocol protocol, EndpointAddress participantService) : base(transactionId, enlistmentId, protocol)
 {
     base.schemaId = "http://schemas.microsoft.com/2006/08/ServiceModel/RegisterParticipantTraceRecord";
     if (participantService != null)
     {
         this.participantService = EndpointAddressAugust2004.FromEndpointAddress(participantService);
     }
 }
 public RegisterFailureRecordSchema10(string transactionId, ControlProtocol protocol, EndpointAddress protocolService, string reason) : base(transactionId, protocol, reason)
 {
     base.schemaId = "http://schemas.microsoft.com/2006/08/ServiceModel/RegisterFailureTraceRecord";
     if (protocolService != null)
     {
         this.protocolService = EndpointAddressAugust2004.FromEndpointAddress(protocolService);
     }
 }
Beispiel #10
0
 public RegistrationCoordinatorResponseInvalidMetadataSchema10(CoordinationContext context, ControlProtocol protocol, EndpointAddress coordinatorService) : base(context, protocol)
 {
     base.schemaId = "http://schemas.microsoft.com/2006/08/ServiceModel/RegistrationCoordinatorResponseInvalidMetadataTraceRecord";
     if (coordinatorService != null)
     {
         this.coordinatorService = EndpointAddressAugust2004.FromEndpointAddress(coordinatorService);
     }
 }
Beispiel #11
0
        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            this.epa = EndpointAddressAugust2004.FromEndpointAddress(System.ServiceModel.EndpointAddress.ReadFrom(AddressingVersion.WSAddressingAugust2004, reader, "SubscriptionManager", Constants.WsEventing.Namespace));
        }
Beispiel #12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Delivery"/> class with the suppleid <paramref name="mode"/> and <paramref name="notifyTo"/> <see cref="Uri"/> parameter values.
        /// </summary>
        /// <param name="mode">A <see cref="Uri"/> containing the <see cref="DeliveryMode"/> value.</param>
        /// <param name="notifyTo">An <see cref="EndpointAddress"/> containing the location to notify an event message to.</param>
        public Delivery(Uri mode, EndpointAddress notifyTo)
        {
            Contract.Requires <ArgumentNullException>(mode != null, "mode");
            Contract.Requires <ArgumentNullException>(notifyTo != null, "notifyTo");

            this.mode               = mode;
            this.notifyTo           = EndpointAddressAugust2004.FromEndpointAddress(notifyTo);
            this.additionalElements = new Collection <XElement>();
        }
Beispiel #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SubscribeRequestMessageBody"/> class with the supplied <paramref name="delivery"/> and optional <see cref="EndpointAddress"/> to send a notice if a subscription is terminated.
        /// </summary>
        /// <param name="delivery">The <see cref="Delivery"/> value.</param>
        /// <param name="endTo">An optional <see cref="EndpointAddress"/> containing the EPR that should be used when to send a notice if a subscription is terminated.</param>
        public SubscribeRequestMessageBody(Delivery delivery, EndpointAddress endTo = null)
        {
            Contract.Requires <ArgumentNullException>(delivery != null, "delivery");

            this.delivery = delivery;
            if (endTo == null)
            {
                return;
            }
            this.endTo = EndpointAddressAugust2004.FromEndpointAddress(endTo);
        }
Beispiel #14
0
        public void ReadFromAugust2004Error2()
        {
            //Missing <Address> element
            string xml = @"<a:ReplyTo xmlns:a='http://schemas.xmlsoap.org/ws/2004/08/addressing'>http://www.w3.org/2005/08/addressing/anonymous</a:ReplyTo>";

            XmlReader           src    = XmlReader.Create(new StringReader(xml));
            XmlDictionaryReader reader =
                XmlDictionaryReader.CreateDictionaryReader(src);

            EndpointAddressAugust2004 e2k4 = EndpointAddressAugust2004.FromEndpointAddress(new EndpointAddress("http://test"));

            ((IXmlSerializable)e2k4).ReadXml(reader);
        }
Beispiel #15
0
        public void ReadFromAugust2004Error()
        {
            //Reading address from EndpointAddress10 namespace with EndpointAddressAugust2004
            string xml = @"<a:ReplyTo xmlns:a='http://www.w3.org/2005/08/addressing'><a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address></a:ReplyTo>";

            XmlReader           src    = XmlReader.Create(new StringReader(xml));
            XmlDictionaryReader reader =
                XmlDictionaryReader.CreateDictionaryReader(src);

            EndpointAddressAugust2004 e2k4 = EndpointAddressAugust2004.FromEndpointAddress(new EndpointAddress("http://test"));

            ((IXmlSerializable)e2k4).ReadXml(reader);
        }
Beispiel #16
0
        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }

            if (reader.IsStartElement("Subscribe", Constants.WsEventing.Namespace) == false)
            {
                throw new XmlException("Invalid Element, it must be 'Subscribe'");
            }

            reader.ReadStartElement("Subscribe", Constants.WsEventing.Namespace);
            while (reader.NodeType != XmlNodeType.EndElement)
            {
                if (reader.IsStartElement("EndTo", Constants.WsEventing.Namespace))
                {
                    this.EndTo = EndpointAddressAugust2004.FromEndpointAddress(EndpointAddress.ReadFrom(AddressingVersion.WSAddressingAugust2004, reader));
                }
                else if (reader.IsStartElement("Delivery", Constants.WsEventing.Namespace))
                {
                    this.Delivery = new Delivery(reader);
                }
                else if (reader.IsStartElement("Expires", Constants.WsEventing.Namespace))
                {
                    this.Expires = new Expires(reader);
                }
                else if (reader.IsStartElement("Filter", Constants.WsEventing.Namespace))
                {
                    String dialect = reader.GetAttribute("Dialect");
                    if (String.IsNullOrEmpty(dialect) || dialect == Constants.WsEventing.Dialects.XPath)
                    {
                        this.Filter        = new XPathMessageFilter(reader);
                        this.filterDialect = Constants.WsEventing.Dialects.XPath;
                    }
                    else
                    {
                        reader.Skip();
                        this.filterDialect = dialect;
                    }
                }
                reader.MoveToContent();
            }
            reader.ReadEndElement();
        }
Beispiel #17
0
        public void ReadFromAugust2004()
        {
            string xml = @"<a:ReplyTo xmlns:a='http://schemas.xmlsoap.org/ws/2004/08/addressing'><a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address></a:ReplyTo>";

            XmlReader           src    = XmlReader.Create(new StringReader(xml));
            XmlDictionaryReader reader =
                XmlDictionaryReader.CreateDictionaryReader(src);

            EndpointAddressAugust2004 e2k4 = EndpointAddressAugust2004.FromEndpointAddress(new EndpointAddress("http://test"));

            ((IXmlSerializable)e2k4).ReadXml(reader);
            Console.WriteLine(e2k4.ToEndpointAddress().Uri.AbsoluteUri);

            EndpointAddress a = e2k4.ToEndpointAddress();

            Assert.AreEqual("http://www.w3.org/2005/08/addressing/anonymous", a.Uri.AbsoluteUri, "#1");
            Assert.IsFalse(a.IsAnonymous, "#2");
        }
        public static void WriteEndPointAddress(DiscoveryVersion discoveryVersion, EndpointAddress endpointAddress, XmlWriter writer)
        {
            Fx.Assert(discoveryVersion != null, "The discoveryVersion must be non null");
            Fx.Assert(writer != null, "The writer must be non null");

            if (discoveryVersion == DiscoveryVersion.WSDiscoveryApril2005 || discoveryVersion == DiscoveryVersion.WSDiscoveryCD1)
            {
                EndpointAddressAugust2004 endpoint = EndpointAddressAugust2004.FromEndpointAddress(endpointAddress);
                discoveryVersion.Implementation.EprSerializer.WriteObject(writer, endpoint);
            }
            else if (discoveryVersion == DiscoveryVersion.WSDiscovery11)
            {
                EndpointAddress10 endpoint = EndpointAddress10.FromEndpointAddress(endpointAddress);
                discoveryVersion.Implementation.EprSerializer.WriteObject(writer, endpoint);
            }
            else
            {
                Fx.Assert("The discoveryVersion parameter cannot be null.");
            }
        }
Beispiel #19
0
        void AddEndpointAddressHeader(string name, string ns, EndpointAddress address)
        {
            if (address == null)
            {
                return;
            }
            if (MessageVersion.Addressing.Equals(AddressingVersion.WSAddressing10))
            {
                Add(MessageHeader.CreateHeader(name, ns, EndpointAddress10.FromEndpointAddress(address)));
            }
#if !MOBILE
            else if (MessageVersion.Addressing.Equals(AddressingVersion.WSAddressingAugust2004))
            {
                Add(MessageHeader.CreateHeader(name, ns, EndpointAddressAugust2004.FromEndpointAddress(address)));
            }
#endif
            else
            {
                throw new InvalidOperationException("WS-Addressing header is not allowed for AddressingVersion.None");
            }
        }
Beispiel #20
0
        public static void Main()
        {
            // <Snippet1>
            // Create an EndpointAddress with a specified address.
            EndpointAddress epa1 = new EndpointAddress("http://localhost/ServiceModelSamples");

            Console.WriteLine("The URI of the EndpointAddress is {0}:", epa1.Uri);
            Console.WriteLine();

            //Initialize an EndpointAddressAugust2004 from the endpointAddress.
            EndpointAddressAugust2004 epaA4 = EndpointAddressAugust2004.FromEndpointAddress(epa1);

            //Serialize and then deserializde the EndpointAugust2004 type.

            //Convert the EndpointAugust2004 back into an EndpointAddress.
            EndpointAddress epa2 = epaA4.ToEndpointAddress();

            Console.WriteLine("The URI of the EndpointAddress is still {0}:", epa2.Uri);
            Console.WriteLine();
            // </Snippet1>
        }
Beispiel #21
0
        void AddEndpointAddressHeader(string name, string ns, EndpointAddress address)
        {
            RemoveAll("FaultTo", Constants.WsaNamespace);
            if (address == null)
            {
                return;
            }
            if (MessageVersion.Addressing.Equals(AddressingVersion.WSAddressing10))
            {
                Add(MessageHeader.CreateHeader(name, ns, EndpointAddress10.FromEndpointAddress(address)));
            }
#if !NET_2_1
            else if (MessageVersion.Addressing.Equals(AddressingVersion.WSAddressingAugust2004))
            {
                Add(MessageHeader.CreateHeader(name, ns, EndpointAddressAugust2004.FromEndpointAddress(address)));
            }
#endif
            else
            {
                throw new InvalidOperationException("WS-Addressing header is not allowed for AddressingVersion.None");
            }
        }
        private BodyWriter ProcessNegotiation(SspiNegotiationTokenAuthenticatorState negotiationState, Message incomingMessage, BinaryNegotiation incomingNego)
        {
            BinaryNegotiation outgoingBinaryNegotiation;
            ISspiNegotiation  sspiNegotiation = negotiationState.SspiNegotiation;

            byte[] outgoingBlob = sspiNegotiation.GetOutgoingBlob(incomingNego.GetNegotiationData(), System.ServiceModel.Security.SecurityUtils.GetChannelBindingFromMessage(incomingMessage), this.extendedProtectionPolicy);
            if (!sspiNegotiation.IsValidContext)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(System.ServiceModel.SR.GetString("InvalidSspiNegotiation")), incomingMessage);
            }
            if ((outgoingBlob == null) && !sspiNegotiation.IsCompleted)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(System.ServiceModel.SR.GetString("NoBinaryNegoToSend")), incomingMessage);
            }
            if (outgoingBlob != null)
            {
                outgoingBinaryNegotiation = this.GetOutgoingBinaryNegotiation(sspiNegotiation, outgoingBlob);
            }
            else
            {
                outgoingBinaryNegotiation = null;
            }
            if (sspiNegotiation.IsCompleted)
            {
                SecurityContextSecurityToken token;
                WrappedKeySecurityToken      token2;
                int num;
                ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies = this.ValidateSspiNegotiation(sspiNegotiation);
                this.IssueServiceToken(negotiationState, authorizationPolicies, out token, out token2, out num);
                negotiationState.SetServiceToken(token);
                SecurityKeyIdentifierClause  clause   = base.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(token, SecurityTokenReferenceStyle.External);
                SecurityKeyIdentifierClause  clause2  = base.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(token, SecurityTokenReferenceStyle.Internal);
                RequestSecurityTokenResponse response = new RequestSecurityTokenResponse(base.StandardsManager)
                {
                    Context   = negotiationState.Context,
                    KeySize   = num,
                    TokenType = base.SecurityContextTokenUri
                };
                if (outgoingBinaryNegotiation != null)
                {
                    response.SetBinaryNegotiation(outgoingBinaryNegotiation);
                }
                response.RequestedUnattachedReference = clause;
                response.RequestedAttachedReference   = clause2;
                response.SetLifetime(token.ValidFrom, token.ValidTo);
                if (negotiationState.AppliesTo != null)
                {
                    if (incomingMessage.Version.Addressing != AddressingVersion.WSAddressing10)
                    {
                        if (incomingMessage.Version.Addressing != AddressingVersion.WSAddressingAugust2004)
                        {
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("AddressingVersionNotSupported", new object[] { incomingMessage.Version.Addressing })));
                        }
                        response.SetAppliesTo <EndpointAddressAugust2004>(EndpointAddressAugust2004.FromEndpointAddress(negotiationState.AppliesTo), negotiationState.AppliesToSerializer);
                    }
                    else
                    {
                        response.SetAppliesTo <EndpointAddress10>(EndpointAddress10.FromEndpointAddress(negotiationState.AppliesTo), negotiationState.AppliesToSerializer);
                    }
                }
                response.MakeReadOnly();
                AddToDigest(negotiationState, response, false);
                RequestSecurityTokenResponse response2 = new RequestSecurityTokenResponse(base.StandardsManager)
                {
                    RequestedSecurityToken = token,
                    RequestedProofToken    = token2,
                    Context   = negotiationState.Context,
                    KeySize   = num,
                    TokenType = base.SecurityContextTokenUri
                };
                if (outgoingBinaryNegotiation != null)
                {
                    response2.SetBinaryNegotiation(outgoingBinaryNegotiation);
                }
                response2.RequestedAttachedReference   = clause2;
                response2.RequestedUnattachedReference = clause;
                if (negotiationState.AppliesTo != null)
                {
                    if (incomingMessage.Version.Addressing != AddressingVersion.WSAddressing10)
                    {
                        if (incomingMessage.Version.Addressing != AddressingVersion.WSAddressingAugust2004)
                        {
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("AddressingVersionNotSupported", new object[] { incomingMessage.Version.Addressing })));
                        }
                        response2.SetAppliesTo <EndpointAddressAugust2004>(EndpointAddressAugust2004.FromEndpointAddress(negotiationState.AppliesTo), negotiationState.AppliesToSerializer);
                    }
                    else
                    {
                        response2.SetAppliesTo <EndpointAddress10>(EndpointAddress10.FromEndpointAddress(negotiationState.AppliesTo), negotiationState.AppliesToSerializer);
                    }
                }
                response2.MakeReadOnly();
                byte[] authenticator = ComputeAuthenticator(negotiationState, token.GetKeyBytes());
                RequestSecurityTokenResponse response3 = new RequestSecurityTokenResponse(base.StandardsManager)
                {
                    Context = negotiationState.Context
                };
                response3.SetAuthenticator(authenticator);
                response3.MakeReadOnly();
                return(new RequestSecurityTokenResponseCollection(new List <RequestSecurityTokenResponse>(2)
                {
                    response2, response3
                }, base.StandardsManager));
            }
            RequestSecurityTokenResponse rstr = new RequestSecurityTokenResponse(base.StandardsManager)
            {
                Context = negotiationState.Context
            };

            rstr.SetBinaryNegotiation(outgoingBinaryNegotiation);
            rstr.MakeReadOnly();
            AddToDigest(negotiationState, rstr, false);
            return(rstr);
        }
        protected override BodyWriter ProcessRequestSecurityToken(Message request, RequestSecurityToken requestSecurityToken, out NegotiationTokenAuthenticatorState negotiationState)
        {
            BodyWriter writer;

            if (request == null)
            {
                throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request");
            }
            if (requestSecurityToken == null)
            {
                throw TraceUtility.ThrowHelperArgumentNull("requestSecurityToken", request);
            }
            try
            {
                EndpointAddress        address;
                DataContractSerializer serializer;
                string        str;
                string        str2;
                int           num;
                byte[]        buffer;
                byte[]        buffer2;
                SecurityToken token;
                ReadOnlyCollection <IAuthorizationPolicy> instance;
                if ((requestSecurityToken.RequestType != null) && (requestSecurityToken.RequestType != base.StandardsManager.TrustDriver.RequestTypeIssue))
                {
                    throw TraceUtility.ThrowHelperWarning(new SecurityNegotiationException(System.ServiceModel.SR.GetString("InvalidRstRequestType", new object[] { requestSecurityToken.RequestType })), request);
                }
                if ((requestSecurityToken.TokenType != null) && (requestSecurityToken.TokenType != base.SecurityContextTokenUri))
                {
                    throw TraceUtility.ThrowHelperWarning(new SecurityNegotiationException(System.ServiceModel.SR.GetString("CannotIssueRstTokenType", new object[] { requestSecurityToken.TokenType })), request);
                }
                requestSecurityToken.GetAppliesToQName(out str, out str2);
                if ((str == "EndpointReference") && (str2 == request.Version.Addressing.Namespace))
                {
                    if (request.Version.Addressing != AddressingVersion.WSAddressing10)
                    {
                        if (request.Version.Addressing != AddressingVersion.WSAddressingAugust2004)
                        {
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("AddressingVersionNotSupported", new object[] { request.Version.Addressing })));
                        }
                        serializer = DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddressAugust2004), 0x10000);
                        address    = requestSecurityToken.GetAppliesTo <EndpointAddressAugust2004>(serializer).ToEndpointAddress();
                    }
                    else
                    {
                        serializer = DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddress10), 0x10000);
                        address    = requestSecurityToken.GetAppliesTo <EndpointAddress10>(serializer).ToEndpointAddress();
                    }
                }
                else
                {
                    address    = null;
                    serializer = null;
                }
                if (this.shouldMatchRstWithEndpointFilter)
                {
                    System.ServiceModel.Security.SecurityUtils.MatchRstWithEndpointFilter(request, base.EndpointFilterTable, base.ListenUri);
                }
                WSTrust.Driver.ProcessRstAndIssueKey(requestSecurityToken, null, this.KeyEntropyMode, base.SecurityAlgorithmSuite, out num, out buffer, out buffer2, out token);
                UniqueId contextId               = System.ServiceModel.Security.SecurityUtils.GenerateUniqueId();
                string   id                      = System.ServiceModel.Security.SecurityUtils.GenerateId();
                DateTime utcNow                  = DateTime.UtcNow;
                DateTime expirationTime          = TimeoutHelper.Add(utcNow, base.ServiceTokenLifetime);
                SecurityMessageProperty security = request.Properties.Security;
                if (security != null)
                {
                    instance = SecuritySessionSecurityTokenAuthenticator.CreateSecureConversationPolicies(security, expirationTime);
                }
                else
                {
                    instance = EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance;
                }
                SecurityContextSecurityToken token2 = base.IssueSecurityContextToken(contextId, id, buffer2, utcNow, expirationTime, instance, base.EncryptStateInServiceToken);
                if (this.preserveBootstrapTokens)
                {
                    token2.BootstrapMessageProperty = (security == null) ? null : ((SecurityMessageProperty)security.CreateCopy());
                    System.ServiceModel.Security.SecurityUtils.ErasePasswordInUsernameTokenIfPresent(token2.BootstrapMessageProperty);
                }
                RequestSecurityTokenResponse response = new RequestSecurityTokenResponse(base.StandardsManager)
                {
                    Context = requestSecurityToken.Context,
                    KeySize = num,
                    RequestedUnattachedReference = base.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(token2, SecurityTokenReferenceStyle.External),
                    RequestedAttachedReference   = base.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(token2, SecurityTokenReferenceStyle.Internal),
                    TokenType = base.SecurityContextTokenUri,
                    RequestedSecurityToken = token2
                };
                if (buffer != null)
                {
                    response.SetIssuerEntropy(buffer);
                    response.ComputeKey = true;
                }
                if (token != null)
                {
                    response.RequestedProofToken = token;
                }
                if (address != null)
                {
                    if (request.Version.Addressing != AddressingVersion.WSAddressing10)
                    {
                        if (request.Version.Addressing != AddressingVersion.WSAddressingAugust2004)
                        {
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("AddressingVersionNotSupported", new object[] { request.Version.Addressing })));
                        }
                        response.SetAppliesTo <EndpointAddressAugust2004>(EndpointAddressAugust2004.FromEndpointAddress(address), serializer);
                    }
                    else
                    {
                        response.SetAppliesTo <EndpointAddress10>(EndpointAddress10.FromEndpointAddress(address), serializer);
                    }
                }
                response.MakeReadOnly();
                negotiationState = new NegotiationTokenAuthenticatorState();
                negotiationState.SetServiceToken(token2);
                if (base.StandardsManager.MessageSecurityVersion.SecureConversationVersion == SecureConversationVersion.WSSecureConversationFeb2005)
                {
                    return(response);
                }
                if (base.StandardsManager.MessageSecurityVersion.SecureConversationVersion != SecureConversationVersion.WSSecureConversation13)
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
                }
                RequestSecurityTokenResponseCollection responses = new RequestSecurityTokenResponseCollection(new List <RequestSecurityTokenResponse>(1)
                {
                    response
                }, base.StandardsManager);
                writer = responses;
            }
            finally
            {
                SecuritySessionSecurityTokenAuthenticator.RemoveCachedTokensIfRequired(request.Properties.Security);
            }
            return(writer);
        }
            protected override BodyWriter GetFirstOutgoingMessageBody(FederatedTokenProviderState negotiationState, out MessageProperties messageProperties)
            {
                messageProperties = null;
                RequestSecurityToken rst = new RequestSecurityToken(this.StandardsManager);

                if (this.addTargetServiceAppliesTo)
                {
                    if (this.MessageVersion.Addressing == AddressingVersion.WSAddressing10)
                    {
                        rst.SetAppliesTo <EndpointAddress10>(
                            EndpointAddress10.FromEndpointAddress(negotiationState.TargetAddress),
                            DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddress10), DataContractSerializerDefaults.MaxItemsInObjectGraph));
                    }
                    else if (this.MessageVersion.Addressing == AddressingVersion.WSAddressingAugust2004)
                    {
                        rst.SetAppliesTo <EndpointAddressAugust2004>(
                            EndpointAddressAugust2004.FromEndpointAddress(negotiationState.TargetAddress),
                            DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddressAugust2004), DataContractSerializerDefaults.MaxItemsInObjectGraph));
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, this.MessageVersion.Addressing)));
                    }
                }
                rst.Context = negotiationState.Context;
                if (!this.isKeySizePresentInRstProperties)
                {
                    rst.KeySize = this.keySize;
                }
                Collection <XmlElement> newRequestProperties = new Collection <XmlElement>();

                if (this.requestProperties != null)
                {
                    for (int i = 0; i < this.requestProperties.Count; ++i)
                    {
                        newRequestProperties.Add(this.requestProperties[i]);
                    }
                }
                if (!isKeyTypePresentInRstProperties)
                {
                    XmlElement keyTypeElement = this.StandardsManager.TrustDriver.CreateKeyTypeElement(this.keyType);
                    newRequestProperties.Insert(0, keyTypeElement);
                }
                if (this.keyType == SecurityKeyType.SymmetricKey)
                {
                    byte[] requestorEntropy = negotiationState.GetRequestorEntropy();
                    rst.SetRequestorEntropy(requestorEntropy);
                }
                else if (this.keyType == SecurityKeyType.AsymmetricKey)
                {
                    RsaKeyIdentifierClause rsaClause     = new RsaKeyIdentifierClause(negotiationState.Rsa);
                    SecurityKeyIdentifier  keyIdentifier = new SecurityKeyIdentifier(rsaClause);
                    newRequestProperties.Add(this.StandardsManager.TrustDriver.CreateUseKeyElement(keyIdentifier, this.StandardsManager));
                    RsaSecurityTokenParameters rsaParameters = new RsaSecurityTokenParameters();
                    rsaParameters.InclusionMode      = SecurityTokenInclusionMode.Never;
                    rsaParameters.RequireDerivedKeys = false;
                    SupportingTokenSpecification rsaSpec = new SupportingTokenSpecification(negotiationState.RsaSecurityToken, EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance, SecurityTokenAttachmentMode.Endorsing, rsaParameters);
                    messageProperties = new MessageProperties();
                    SecurityMessageProperty security = new SecurityMessageProperty();
                    security.OutgoingSupportingTokens.Add(rsaSpec);
                    messageProperties.Security = security;
                }
                if (this.keyType == SecurityKeyType.SymmetricKey && this.KeyEntropyMode == SecurityKeyEntropyMode.CombinedEntropy)
                {
                    newRequestProperties.Add(this.StandardsManager.TrustDriver.CreateComputedKeyAlgorithmElement(this.StandardsManager.TrustDriver.ComputedKeyAlgorithm));
                }
                rst.RequestProperties = newRequestProperties;
                rst.MakeReadOnly();
                return(rst);
            }
        protected override BodyWriter ProcessRequestSecurityToken(Message request, RequestSecurityToken requestSecurityToken, out NegotiationTokenAuthenticatorState negotiationState)
        {
            if (request == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request");
            }
            if (requestSecurityToken == null)
            {
                throw TraceUtility.ThrowHelperArgumentNull("requestSecurityToken", request);
            }
            try
            {
                if (requestSecurityToken.RequestType != null && requestSecurityToken.RequestType != this.StandardsManager.TrustDriver.RequestTypeIssue)
                {
                    throw TraceUtility.ThrowHelperWarning(new SecurityNegotiationException(SR.GetString(SR.InvalidRstRequestType, requestSecurityToken.RequestType)), request);
                }
                if (requestSecurityToken.TokenType != null && requestSecurityToken.TokenType != this.SecurityContextTokenUri)
                {
                    throw TraceUtility.ThrowHelperWarning(new SecurityNegotiationException(SR.GetString(SR.CannotIssueRstTokenType, requestSecurityToken.TokenType)), request);
                }

                EndpointAddress        appliesTo;
                DataContractSerializer appliesToSerializer;
                string appliesToName;
                string appliesToNamespace;
                requestSecurityToken.GetAppliesToQName(out appliesToName, out appliesToNamespace);
                if (appliesToName == AddressingStrings.EndpointReference && appliesToNamespace == request.Version.Addressing.Namespace)
                {
                    if (request.Version.Addressing == AddressingVersion.WSAddressing10)
                    {
                        appliesToSerializer = DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddress10), DataContractSerializerDefaults.MaxItemsInObjectGraph);
                        appliesTo           = requestSecurityToken.GetAppliesTo <EndpointAddress10>(appliesToSerializer).ToEndpointAddress();
                    }
                    else if (request.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
                    {
                        appliesToSerializer = DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddressAugust2004), DataContractSerializerDefaults.MaxItemsInObjectGraph);
                        appliesTo           = requestSecurityToken.GetAppliesTo <EndpointAddressAugust2004>(appliesToSerializer).ToEndpointAddress();
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, request.Version.Addressing)));
                    }
                }
                else
                {
                    appliesTo           = null;
                    appliesToSerializer = null;
                }
                if (this.shouldMatchRstWithEndpointFilter)
                {
                    SecurityUtils.MatchRstWithEndpointFilter(request, this.EndpointFilterTable, this.ListenUri);
                }
                int           issuedKeySize;
                byte[]        issuerEntropy;
                byte[]        proofKey;
                SecurityToken proofToken;
                WSTrust.Driver.ProcessRstAndIssueKey(requestSecurityToken, null, this.KeyEntropyMode, this.SecurityAlgorithmSuite,
                                                     out issuedKeySize, out issuerEntropy, out proofKey, out proofToken);
                UniqueId contextId      = SecurityUtils.GenerateUniqueId();
                string   id             = SecurityUtils.GenerateId();
                DateTime effectiveTime  = DateTime.UtcNow;
                DateTime expirationTime = TimeoutHelper.Add(effectiveTime, this.ServiceTokenLifetime);
                // ensure that a SecurityContext is present in the message
                SecurityMessageProperty securityProperty = request.Properties.Security;
                ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies;
                if (securityProperty != null)
                {
                    authorizationPolicies = SecuritySessionSecurityTokenAuthenticator.CreateSecureConversationPolicies(securityProperty, expirationTime);
                }
                else
                {
                    authorizationPolicies = EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance;
                }
                SecurityContextSecurityToken serviceToken = this.IssueSecurityContextToken(contextId, id, proofKey, effectiveTime, expirationTime, authorizationPolicies,
                                                                                           this.EncryptStateInServiceToken);
                if (this.preserveBootstrapTokens)
                {
                    serviceToken.BootstrapMessageProperty = (securityProperty == null) ? null : (SecurityMessageProperty)securityProperty.CreateCopy();
                    SecurityUtils.ErasePasswordInUsernameTokenIfPresent(serviceToken.BootstrapMessageProperty);
                }
                RequestSecurityTokenResponse rstr = new RequestSecurityTokenResponse(this.StandardsManager);
                rstr.Context = requestSecurityToken.Context;
                rstr.KeySize = issuedKeySize;
                rstr.RequestedUnattachedReference = this.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(serviceToken, SecurityTokenReferenceStyle.External);
                rstr.RequestedAttachedReference   = this.IssuedSecurityTokenParameters.CreateKeyIdentifierClause(serviceToken, SecurityTokenReferenceStyle.Internal);
                rstr.TokenType = this.SecurityContextTokenUri;
                rstr.RequestedSecurityToken = serviceToken;
                if (issuerEntropy != null)
                {
                    rstr.SetIssuerEntropy(issuerEntropy);
                    rstr.ComputeKey = true;
                }
                if (proofToken != null)
                {
                    rstr.RequestedProofToken = proofToken;
                }
                if (appliesTo != null)
                {
                    if (request.Version.Addressing == AddressingVersion.WSAddressing10)
                    {
                        rstr.SetAppliesTo <EndpointAddress10>(EndpointAddress10.FromEndpointAddress(appliesTo), appliesToSerializer);
                    }
                    else if (request.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
                    {
                        rstr.SetAppliesTo <EndpointAddressAugust2004>(EndpointAddressAugust2004.FromEndpointAddress(appliesTo), appliesToSerializer);
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.GetString(SR.AddressingVersionNotSupported, request.Version.Addressing)));
                    }
                }
                rstr.MakeReadOnly();
                negotiationState = new NegotiationTokenAuthenticatorState();
                negotiationState.SetServiceToken(serviceToken);

                if (this.StandardsManager.MessageSecurityVersion.SecureConversationVersion == SecureConversationVersion.WSSecureConversationFeb2005)
                {
                    return(rstr);
                }
                else if (this.StandardsManager.MessageSecurityVersion.SecureConversationVersion == SecureConversationVersion.WSSecureConversation13)
                {
                    List <RequestSecurityTokenResponse> rstrList = new List <RequestSecurityTokenResponse>(1);
                    rstrList.Add(rstr);
                    RequestSecurityTokenResponseCollection rstrCollection = new RequestSecurityTokenResponseCollection(rstrList, this.StandardsManager);
                    return(rstrCollection);
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
                }
            }
            finally
            {
                SecuritySessionSecurityTokenAuthenticator.RemoveCachedTokensIfRequired(request.Properties.Security);
            }
        }
Beispiel #26
0
            protected override BodyWriter GetFirstOutgoingMessageBody(IssuedSecurityTokenProvider.FederatedTokenProviderState negotiationState, out MessageProperties messageProperties)
            {
                messageProperties = null;
                RequestSecurityToken token = new RequestSecurityToken(base.StandardsManager);

                if (this.addTargetServiceAppliesTo)
                {
                    if (this.MessageVersion.Addressing != AddressingVersion.WSAddressing10)
                    {
                        if (this.MessageVersion.Addressing != AddressingVersion.WSAddressingAugust2004)
                        {
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("AddressingVersionNotSupported", new object[] { this.MessageVersion.Addressing })));
                        }
                        token.SetAppliesTo <EndpointAddressAugust2004>(EndpointAddressAugust2004.FromEndpointAddress(negotiationState.TargetAddress), DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddressAugust2004), 0x10000));
                    }
                    else
                    {
                        token.SetAppliesTo <EndpointAddress10>(EndpointAddress10.FromEndpointAddress(negotiationState.TargetAddress), DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddress10), 0x10000));
                    }
                }
                token.Context = negotiationState.Context;
                if (!this.isKeySizePresentInRstProperties)
                {
                    token.KeySize = this.keySize;
                }
                Collection <XmlElement> collection = new Collection <XmlElement>();

                if (this.requestProperties != null)
                {
                    for (int i = 0; i < this.requestProperties.Count; i++)
                    {
                        collection.Add(this.requestProperties[i]);
                    }
                }
                if (!this.isKeyTypePresentInRstProperties)
                {
                    XmlElement item = base.StandardsManager.TrustDriver.CreateKeyTypeElement(this.keyType);
                    collection.Insert(0, item);
                }
                if (this.keyType == SecurityKeyType.SymmetricKey)
                {
                    byte[] requestorEntropy = negotiationState.GetRequestorEntropy();
                    token.SetRequestorEntropy(requestorEntropy);
                }
                else if (this.keyType == SecurityKeyType.AsymmetricKey)
                {
                    RsaKeyIdentifierClause clause        = new RsaKeyIdentifierClause(negotiationState.Rsa);
                    SecurityKeyIdentifier  keyIdentifier = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { clause });
                    collection.Add(base.StandardsManager.TrustDriver.CreateUseKeyElement(keyIdentifier, base.StandardsManager));
                    RsaSecurityTokenParameters tokenParameters = new RsaSecurityTokenParameters {
                        InclusionMode      = SecurityTokenInclusionMode.Never,
                        RequireDerivedKeys = false
                    };
                    SupportingTokenSpecification specification = new SupportingTokenSpecification(negotiationState.RsaSecurityToken, System.ServiceModel.Security.EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance, SecurityTokenAttachmentMode.Endorsing, tokenParameters);
                    messageProperties = new MessageProperties();
                    SecurityMessageProperty property = new SecurityMessageProperty {
                        OutgoingSupportingTokens = { specification }
                    };
                    messageProperties.Security = property;
                }
                if ((this.keyType == SecurityKeyType.SymmetricKey) && (this.KeyEntropyMode == SecurityKeyEntropyMode.CombinedEntropy))
                {
                    collection.Add(base.StandardsManager.TrustDriver.CreateComputedKeyAlgorithmElement(base.StandardsManager.TrustDriver.ComputedKeyAlgorithm));
                }
                token.RequestProperties = collection;
                token.MakeReadOnly();
                return(token);
            }
Beispiel #27
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SubscriptionManager"/> class from the supplied and fully initialized <see cref="System.ServiceModel.EndpointAddress"/>.
        /// </summary>
        /// <param name="address">The EPA used to address the subscription management for event source.</param>
        public SubscriptionManager(EndpointAddress address)
        {
            Contract.Requires(address != null, "address");

            this.epa = EndpointAddressAugust2004.FromEndpointAddress(address);
        }
        private async ValueTask <BodyWriter> ProcessNegotiationAsync(SspiNegotiationTokenAuthenticatorState negotiationState, Message incomingMessage, BinaryNegotiation incomingNego)
        {
            ISspiNegotiation sspiNegotiation = negotiationState.SspiNegotiation;

            byte[] outgoingBlob = sspiNegotiation.GetOutgoingBlob(incomingNego.GetNegotiationData(),
                                                                  SecurityUtils.GetChannelBindingFromMessage(incomingMessage),
                                                                  ExtendedProtectionPolicy);

            if (sspiNegotiation.IsValidContext == false)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.Format(SR.InvalidSspiNegotiation)), incomingMessage);
            }
            // if there is no blob to send back the nego must be complete from the server side
            if (outgoingBlob == null && sspiNegotiation.IsCompleted == false)
            {
                throw TraceUtility.ThrowHelperError(new SecurityNegotiationException(SR.Format(SR.NoBinaryNegoToSend)), incomingMessage);
            }
            BinaryNegotiation outgoingBinaryNegotiation;

            if (outgoingBlob != null)
            {
                outgoingBinaryNegotiation = GetOutgoingBinaryNegotiation(sspiNegotiation, outgoingBlob);
            }
            else
            {
                outgoingBinaryNegotiation = null;
            }
            BodyWriter replyBody;

            if (sspiNegotiation.IsCompleted)
            {
                ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies = await ValidateSspiNegotiationAsync(sspiNegotiation);

                SecurityContextSecurityToken serviceToken;
                WrappedKeySecurityToken      proofToken;
                int issuedKeySize;
                IssueServiceToken(negotiationState, authorizationPolicies, out serviceToken, out proofToken, out issuedKeySize);
                negotiationState.SetServiceToken(serviceToken);

                SecurityKeyIdentifierClause externalTokenReference = IssuedSecurityTokenParameters.CreateKeyIdentifierClause(serviceToken, SecurityTokenReferenceStyle.External);
                SecurityKeyIdentifierClause internalTokenReference = IssuedSecurityTokenParameters.CreateKeyIdentifierClause(serviceToken, SecurityTokenReferenceStyle.Internal);

                RequestSecurityTokenResponse dummyRstr = new RequestSecurityTokenResponse(StandardsManager)
                {
                    Context   = negotiationState.Context,
                    KeySize   = issuedKeySize,
                    TokenType = SecurityContextTokenUri
                };
                if (outgoingBinaryNegotiation != null)
                {
                    dummyRstr.SetBinaryNegotiation(outgoingBinaryNegotiation);
                }
                dummyRstr.RequestedUnattachedReference = externalTokenReference;
                dummyRstr.RequestedAttachedReference   = internalTokenReference;
                dummyRstr.SetLifetime(serviceToken.ValidFrom, serviceToken.ValidTo);
                if (negotiationState.AppliesTo != null)
                {
                    if (incomingMessage.Version.Addressing == AddressingVersion.WSAddressing10)
                    {
                        dummyRstr.SetAppliesTo <EndpointAddress10>(EndpointAddress10.FromEndpointAddress(
                                                                       negotiationState.AppliesTo),
                                                                   negotiationState.AppliesToSerializer);
                    }
                    else if (incomingMessage.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
                    {
                        dummyRstr.SetAppliesTo <EndpointAddressAugust2004>(EndpointAddressAugust2004.FromEndpointAddress(
                                                                               negotiationState.AppliesTo),
                                                                           negotiationState.AppliesToSerializer);
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.Format(SR.AddressingVersionNotSupported, incomingMessage.Version.Addressing)));
                    }
                }
                dummyRstr.MakeReadOnly();
                AddToDigest(negotiationState, dummyRstr, false);
                RequestSecurityTokenResponse negotiationRstr = new RequestSecurityTokenResponse(StandardsManager)
                {
                    RequestedSecurityToken = serviceToken,

                    RequestedProofToken = proofToken,
                    Context             = negotiationState.Context,
                    KeySize             = issuedKeySize,
                    TokenType           = SecurityContextTokenUri
                };
                if (outgoingBinaryNegotiation != null)
                {
                    negotiationRstr.SetBinaryNegotiation(outgoingBinaryNegotiation);
                }
                negotiationRstr.RequestedAttachedReference   = internalTokenReference;
                negotiationRstr.RequestedUnattachedReference = externalTokenReference;
                if (negotiationState.AppliesTo != null)
                {
                    if (incomingMessage.Version.Addressing == AddressingVersion.WSAddressing10)
                    {
                        negotiationRstr.SetAppliesTo <EndpointAddress10>(
                            EndpointAddress10.FromEndpointAddress(negotiationState.AppliesTo),
                            negotiationState.AppliesToSerializer);
                    }
                    else if (incomingMessage.Version.Addressing == AddressingVersion.WSAddressingAugust2004)
                    {
                        negotiationRstr.SetAppliesTo <EndpointAddressAugust2004>(
                            EndpointAddressAugust2004.FromEndpointAddress(negotiationState.AppliesTo),
                            negotiationState.AppliesToSerializer);
                    }
                    else
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                  new ProtocolException(SR.Format(SR.AddressingVersionNotSupported, incomingMessage.Version.Addressing)));
                    }
                }
                negotiationRstr.MakeReadOnly();

                byte[] authenticator = ComputeAuthenticator(negotiationState, serviceToken.GetKeyBytes());
                RequestSecurityTokenResponse authenticatorRstr = new RequestSecurityTokenResponse(StandardsManager)
                {
                    Context = negotiationState.Context
                };
                authenticatorRstr.SetAuthenticator(authenticator);
                authenticatorRstr.MakeReadOnly();

                List <RequestSecurityTokenResponse> rstrList = new List <RequestSecurityTokenResponse>(2)
                {
                    negotiationRstr,
                    authenticatorRstr
                };
                replyBody = new RequestSecurityTokenResponseCollection(rstrList, StandardsManager);
            }
            else
            {
                RequestSecurityTokenResponse rstr = new RequestSecurityTokenResponse(StandardsManager)
                {
                    Context = negotiationState.Context
                };
                rstr.SetBinaryNegotiation(outgoingBinaryNegotiation);
                rstr.MakeReadOnly();
                AddToDigest(negotiationState, rstr, false);
                replyBody = rstr;
            }

            return(replyBody);
        }