/// <summary>
        /// Determines if the DispatchContext contains a valid request action for incoming RSTR messages.
        /// </summary>
        private static bool IsValidRSTRAction(DispatchContext dispatchContext)
        {
            bool valid = false;
            string action = dispatchContext.RequestAction;

            if (dispatchContext.TrustNamespace == WSTrust13Constants.NamespaceURI)
            {
                switch (action)
                {
                    case WSTrust13Constants.Actions.CancelFinalResponse:
                    case WSTrust13Constants.Actions.CancelResponse:
                    case WSTrust13Constants.Actions.IssueFinalResponse:
                    case WSTrust13Constants.Actions.IssueResponse:
                    case WSTrust13Constants.Actions.RenewFinalResponse:
                    case WSTrust13Constants.Actions.RenewResponse:
                    case WSTrust13Constants.Actions.ValidateFinalResponse:
                    case WSTrust13Constants.Actions.ValidateResponse:
                        valid = true;
                        break;
                }
            }
            if (dispatchContext.TrustNamespace == WSTrustFeb2005Constants.NamespaceURI)
            {
                switch (action)
                {
                    case WSTrustFeb2005Constants.Actions.CancelResponse:
                    case WSTrustFeb2005Constants.Actions.IssueResponse:
                    case WSTrustFeb2005Constants.Actions.RenewResponse:
                    case WSTrustFeb2005Constants.Actions.ValidateResponse:
                        valid = true;
                        break;
                }
            }

            return valid;
        }
        /// <summary>
        /// Creates a <see cref="DispatchContext"/> object for use by the <see cref="DispatchRequest"/> method.
        /// </summary>
        /// <param name="requestMessage">The incoming request message.</param>
        /// <param name="requestAction">The SOAP action of the request.</param>
        /// <param name="responseAction">The default SOAP action of the response.</param>
        /// <param name="trustNamespace">Namespace URI of the trust version of the incoming request.</param>
        /// <param name="requestSerializer">The <see cref="WSTrustRequestSerializer"/> used to deserialize 
        /// incoming RST messages.</param>
        /// <param name="responseSerializer">The <see cref="WSTrustResponseSerializer"/> used to deserialize 
        /// incoming RSTR messages.</param>
        /// <param name="serializationContext">The <see cref="WSTrustSerializationContext"/> to use 
        /// when deserializing incoming messages.</param>
        /// <returns>A <see cref="DispatchContext"/> object.</returns>
        protected virtual DispatchContext CreateDispatchContext(Message requestMessage,
                                                                 string requestAction,
                                                                 string responseAction,
                                                                 string trustNamespace,
                                                                 WSTrustRequestSerializer requestSerializer,
                                                                 WSTrustResponseSerializer responseSerializer,
                                                                 WSTrustSerializationContext serializationContext)
        {
            DispatchContext dispatchContext = new DispatchContext()
            {
                Principal = OperationContext.Current.ClaimsPrincipal as ClaimsPrincipal,
                RequestAction = requestAction,
                ResponseAction = responseAction,
                TrustNamespace = trustNamespace
            };

            XmlReader requestBodyReader = requestMessage.GetReaderAtBodyContents();
            //
            // Take a peek at the request with the serializers to figure out if this is a standard incoming
            // RST or if this is an instance of a challenge-response style message pattern where an RSTR comes in.
            //
            if (requestSerializer.CanRead(requestBodyReader))
            {
                dispatchContext.RequestMessage = requestSerializer.ReadXml(requestBodyReader, serializationContext);
            }
            else if (responseSerializer.CanRead(requestBodyReader))
            {
                dispatchContext.RequestMessage = responseSerializer.ReadXml(requestBodyReader, serializationContext);
            }
            else
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidRequestException(SR.GetString(SR.ID3114)));
            }

            //
            // CAUTION: Don't create the STS until after the RST or RSTR is deserialized or the test team
            //          has major infrastructure problems.
            //          
            dispatchContext.SecurityTokenService = CreateSTS();
            return dispatchContext;
        }
        /// <summary>
        /// Validates the DispatchContext.
        /// </summary>
        /// <param name="dispatchContext">The <see cref="DispatchContext"/> to validate.</param>
        /// <remarks>
        /// This routine ensures that the <see cref="DispatchContext"/> represents a legal request
        /// prior to being passed into <see cref="DispatchRequest"/>. This routine's default implementation
        /// is to reject incoming RST messages with RSTR actions and vice versa.
        /// </remarks>
        protected virtual void ValidateDispatchContext(DispatchContext dispatchContext)
        {
            if (dispatchContext.RequestMessage is RST
                 && !IsValidRSTAction(dispatchContext))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidRequestException(
                        SR.GetString(SR.ID3113, "RequestSecurityToken", dispatchContext.RequestAction)));
            }

            if (dispatchContext.RequestMessage is RSTR
                 && !IsValidRSTRAction(dispatchContext))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                    new InvalidRequestException(
                        SR.GetString(SR.ID3113, "RequestSecurityTokenResponse", dispatchContext.RequestAction)));
            }
        }
        /// <summary>
        /// Processes a WS-Trust request message, and optionally determines the appropriate
        /// response message and the WS-Addressing action for the response message.
        /// </summary>
        /// <param name="dispatchContext">Defines the request parameters to process and exposes properties
        /// that determine the response message and action.</param>
        protected virtual void DispatchRequest(DispatchContext dispatchContext)
        {
            RST rst = dispatchContext.RequestMessage as RST;
            STS sts = dispatchContext.SecurityTokenService;
            ClaimsPrincipal icp = dispatchContext.Principal;

            if (rst != null)
            {
                switch (rst.RequestType)
                {
                    case RequestTypes.Cancel:
                        dispatchContext.ResponseMessage = sts.Cancel(icp, rst);
                        break;
                    case RequestTypes.Issue:
                        dispatchContext.ResponseMessage = sts.Issue(icp, rst);
                        break;
                    case RequestTypes.Renew:
                        dispatchContext.ResponseMessage = sts.Renew(icp, rst);
                        break;
                    case RequestTypes.Validate:
                        dispatchContext.ResponseMessage = sts.Validate(icp, rst);
                        break;
                    default:
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID3112, rst.RequestType)));
                }
            }
            else
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID3022)));
            }
        }
 /// <summary>
 /// Begins an asynchronous call to <see cref="DispatchRequest"/>.
 /// </summary>
 /// <param name="dispatchContext">Defines the request parameters to process and exposes properties
 /// that determine the response message and action.</param>
 /// <param name="asyncCallback">An optional asynchronous callback, to be called when the 
 /// dispatch is complete.</param>
 /// <param name="asyncState">A user-provided object that distinguishes this particular asynchronous 
 /// dispatch request from other requests.</param>
 /// <returns><see cref="IAsyncResult"/> that represents the asynchronous operation. Used as the input
 /// to <see cref="EndDispatchRequest"/>.</returns>
 protected virtual IAsyncResult BeginDispatchRequest(DispatchContext dispatchContext, AsyncCallback asyncCallback, object asyncState)
 {
     return new DispatchRequestAsyncResult(dispatchContext, asyncCallback, asyncState);
 }
            public DispatchRequestAsyncResult(DispatchContext dispatchContext, AsyncCallback asyncCallback, object asyncState)
                : base(asyncCallback, asyncState)
            {
                _dispatchContext = dispatchContext;

                ClaimsPrincipal icp = dispatchContext.Principal;
                RST rst = dispatchContext.RequestMessage as RST;
                STS sts = dispatchContext.SecurityTokenService;

                if (rst == null)
                {
                    this.Complete(true, DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID3023))));
                    return;
                }

                switch (rst.RequestType)
                {
                    case RequestTypes.Cancel:
                        sts.BeginCancel(icp, rst, OnCancelComplete, null);
                        break;
                    case RequestTypes.Issue:
                        sts.BeginIssue(icp, rst, OnIssueComplete, null);
                        break;
                    case RequestTypes.Renew:
                        sts.BeginRenew(icp, rst, OnRenewComplete, null);
                        break;
                    case RequestTypes.Validate:
                        sts.BeginValidate(icp, rst, OnValidateComplete, null);
                        break;
                    default:
                        this.Complete(true, DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID3112, rst.RequestType))));
                        break;
                }
            }
 //
 // Asynchronously invoked when WSTrustServiceContract.BeginDispatchRequest completes.
 //
 private void OnDispatchRequestCompleted(IAsyncResult ar)
 {
     try
     {
         _dispatchContext = _trustServiceContract.EndDispatchRequest(ar);
         this.Complete(false);
     }
     catch (Exception ex)
     {
         if (System.Runtime.Fx.IsFatal(ex))
         {
             throw;
         }
         this.Complete(false, ex);
     }
 }
            public ProcessCoreAsyncResult(WSTrustServiceContract contract,
                                           DispatchContext dispatchContext,
                                           MessageVersion messageVersion,
                                           WSTrustResponseSerializer responseSerializer,
                                           WSTrustSerializationContext serializationContext,
                                           AsyncCallback asyncCallback,
                                           object asyncState)
                : base(asyncCallback, asyncState)
            {
                if (contract == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contract");
                }

                if (dispatchContext == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("dispatchContext");
                }

                if (responseSerializer == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("responseSerializer");
                }

                if (serializationContext == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serializationContext");
                }

                _trustServiceContract = contract;
                _dispatchContext = dispatchContext;
                _messageVersion = messageVersion;
                _responseSerializer = responseSerializer;
                _serializationContext = serializationContext;

                contract.BeginDispatchRequest(dispatchContext, OnDispatchRequestCompleted, null);
            }