コード例 #1
0
        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            if (!reply.IsEmpty && !reply.IsFault) {
                var buffer = reply.CreateBufferedCopy(short.MaxValue);
                var copy = buffer.CreateMessage();
                reply = buffer.CreateMessage();

                string xmlMessage = copy.GetReaderAtBodyContents().ReadOuterXml();
                var hashType = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters["hash"];

                if (hashType != null) {
                    byte[] hash = null;
                    if (hashType.Equals("MD5", StringComparison.OrdinalIgnoreCase)) {
                        MD5 md5 = MD5.Create();
                        hash = md5.ComputeHash(Encoding.UTF8.GetBytes(xmlMessage));
                    } else if (hashType.Equals("SHA1", StringComparison.OrdinalIgnoreCase)) {
                        SHA1 sha1 = SHA1.Create();
                        hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(xmlMessage));
                    }

                    if (hash != null) {
                        WebOperationContext.Current.OutgoingResponse.Headers.Add("Hash", Convert.ToBase64String(hash));
                    }

                }

            }
        }
コード例 #2
0
        public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
        {
            MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
            request = buffer.CreateMessage();

            request.Headers.Add(new AuthorizationHeader(Config.AuthorizationTokenValue));

            return null;
        }
コード例 #3
0
        public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            //create a copy of the message since a message can be read only once
            MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
            request = buffer.CreateMessage();
            Message dupeRequest = buffer.CreateMessage();

            //log the action
            Helper.Log(dupeRequest.Headers.Action);

            buffer.Close();

            Helper.Log("IDispatchMessageInspector.AfterReceiveRequest() called from " + Helper.GetClientIP());
            return null;
        }
コード例 #4
0
        public bool CheckAccess(OperationContext operationContext, ref System.ServiceModel.Channels.Message message)
        {
            var copy = message.CreateBufferedCopy(2048);
            string base64Value = copy.CreateNavigator().SelectSingleNode("//Binary").Value;
            if (string.IsNullOrEmpty(base64Value))
            {
                LogManager.Log.Warn("CheckAccess returned false - the message body was not found");
                return false;
            }

            NameValueCollection param = new NameValueCollection();

            using (MemoryStream stream = new MemoryStream(Convert.FromBase64String(base64Value)))
            using (StreamReader sr = new StreamReader(stream))
            {
                param = HttpUtility.ParseQueryString(sr.ReadToEnd());
            }

            message = copy.CreateMessage();
            copy.Close();

            ITwilioRequestValidator req = RequestValidator.GetInstance();

            if (WebOperationContext.Current.IncomingRequest.UriTemplateMatch == null)
            {
                LogManager.Log.Warn("Incoming request missing UriTemplateMatch - probably didn't go to the correct controller - rejected SMS");
                return false;
            }

            string uri = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri.OriginalString;

            string sig = WebOperationContext.Current.IncomingRequest.Headers["X-Twilio-Signature"];
            if (string.IsNullOrEmpty(sig))
            {
                LogManager.Log.Warn("X-Twilio-Signature missing - rejected SMS");
                return false;
            }

            if (req.IsValid(uri, sig, param))
            {
                return true;
            }

            LogManager.Log.Warn("X-Twilio-Signature failure - rejected SMS");
            return false;
        }
コード例 #5
0
        /// <summary>
        /// Implementation will add the headers for MS-WOPI before a request message is sent to a service.
        /// </summary>
        /// <param name="request">Specify the message to be sent to the service.</param>
        /// <param name="channel">Specify the client object channel.</param>
        /// <returns>Return null.</returns>
        public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
        {
            // Restore the request.
            string requestString = request.ToString();
            XmlDocument requestXml = new XmlDocument();
            requestXml.LoadXml(requestString);
            SchemaValidation.LastRawRequestXml = requestXml.DocumentElement;

            // Create a clone message for the request.
            MessageBuffer messageBuffer = request.CreateBufferedCopy(int.MaxValue);
            request = messageBuffer.CreateMessage();

            if (this.context.OperationType == OperationType.WOPICellStorageRequest
                || this.context.OperationType == OperationType.WOPICellStorageRelativeRequest)
            {
                // Remove the SoapAction header
                request.Headers.RemoveAll("Action", "http://schemas.microsoft.com/ws/2005/05/addressing/none");

                // Add all the MUST header values
                this.AddHeader(ref request, "X-WOPI-Proof", this.context.XWOPIProof);
                this.AddHeader(ref request, "X-WOPI-TimeStamp", this.context.XWOPITimeStamp);
                this.AddHeader(ref request, "Authorization", this.context.XWOPIAuthorization);

                // Add all the optional value
                if (this.context.IsXWOPIOverrideSpecified)
                {
                    this.AddHeader(ref request, "X-WOPI-Override", this.context.GetValueOrDefault<string>("X-WOPI-Override", "COBALT"));
                }

                if (this.context.IsXWOPISizeSpecified)
                {
                    this.AddHeader(ref request, "X-WOPI-Size", this.context.GetValueOrDefault<int>("X-WOPI-Size", this.SizeOfWOPIMessage(messageBuffer.CreateMessage())).ToString());
                }

                if (this.context.OperationType == OperationType.WOPICellStorageRelativeRequest)
                {
                    if (this.context.IsXWOPIRelativeTargetSpecified)
                    {
                        this.AddHeader(ref request, "X-WOPI-RelativeTarget", this.context.XWOPIRelativeTarget);
                    }
                }
            }

            return null;
        }
コード例 #6
0
 public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
 {
     try
     {
         var trace = TraceManager.Trace;
         if (trace.Properties.ContainsKey(SDBTraceProperties.TRACE_SUCCESS_PROPERTY) == false)
         {
             trace.Properties[SDBTraceProperties.TRACE_SUCCESS_PROPERTY] = reply.IsFault == false;
         }
         if (trace.Properties.ContainsKey(SDBTraceProperties.TRACE_RESULT_PROPERTY) == false)
         {
             var buffer = reply.CreateBufferedCopy(Int32.MaxValue);
             reply = buffer.CreateMessage();
             var writer = new StringWriter();
             buffer.CreateMessage().WriteMessage(new XmlTextWriter(writer));
             trace.Properties[SDBTraceProperties.TRACE_RESULT_PROPERTY] = writer.ToString();
         }
         TraceManager.EndTrace();
     }
     catch (Exception e)
     {
         log.ErrorFormat("Fail on trace end: {0}{1}{2}", e.Message, Environment.NewLine, e.StackTrace);
     }
 }
コード例 #7
0
ファイル: Service1.cs プロジェクト: virajs/klWCFSecurity
        //Server Side
        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            X509Certificate2 myCert = CryptoHelper.FindCertificate(StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectDistinguishedName, "CN=klServer");
            byte[] myHash = myCert.GetCertHash();

            byte[] mySignedHash = CryptoHelper.Sign(myHash, myCert);
            byte[] mySignedDetachedHash = CryptoHelper.SignDetached(myHash, myCert);

            byte[] myEncryptedHash = CryptoHelper.Encrypt(mySignedHash, myCert);
            byte[] myEncryptedDetachedHash = CryptoHelper.Encrypt(mySignedDetachedHash, myCert);

            byte[] myDecodedHash = CryptoHelper.VerifyAndRemoveSignature(mySignedHash);

            bool myOK = CryptoHelper.VerifyDetached(mySignedHash, mySignedDetachedHash);

            char[] keyChars = new char[mySignedHash.Length];

            for (int i = 0; i < mySignedHash.Length; i++)
                keyChars[i] = (char)mySignedHash[i];

            reply.Headers.Add((new CustomSecurityHeader(new string(keyChars))));

            MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue);
            reply = buffer.CreateMessage();
            Console.WriteLine("Service Sending:\n{0}", buffer.CreateMessage().ToString());
        }
コード例 #8
0
        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            MessageBuffer buffer = reply.CreateBufferedCopy(int.MaxValue);
            _receivedMessage = buffer.CreateMessage();

            reply = buffer.CreateMessage();
        }
コード例 #9
0
ファイル: Test.cs プロジェクト: Kingston-Wharves/TestProjects
        public void DeserializeRequest(System.ServiceModel.Channels.Message message, object[] parameters)
        {
            var buffer = message.CreateBufferedCopy(int.MaxValue);

            var messageSource = buffer.CreateMessage(); // don't affect the underlying stream

            XDocument doc = null;

            using (var messageReader = messageSource.GetReaderAtBodyContents())
            {
                doc = XDocument.Parse(messageReader.ReadOuterXml()); // few issues with encoding here (strange bytes at start of string), this technique resolves that
            }

            foreach (var element in doc.Descendants())
            {
                MakeNillable(element);
            }

            // create a new message with our corrected XML
            var messageTarget = Message.CreateMessage(messageSource.Version, null, doc.CreateReader());
            messageTarget.Headers.CopyHeadersFrom(messageSource.Headers);

            // now delegate the work to the inner formatter against our modified message, its the parameters were after
            try
            {
                var x = parameters;
                _innerFormatter.DeserializeRequest(messageTarget, parameters);
            }
            catch (Exception ex)
            {
                ////check null values in the parameters
                //if (ex.InnerException.Message == "ValueType 'System.Int32' cannot be null.")
                //{
                //}
                //throw new FaultException<EpayException>(new EpayException
                //{
                //});
                //if an error occurs here we know that one of the fields failed to be deserialized correctly
            }
        }
コード例 #10
0
 public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
 {
     try
     {
         MessageBuffer buffer = reply.CreateBufferedCopy(Int32.MaxValue);
         reply = buffer.CreateMessage();
         System.IO.File.WriteAllText(@"c:\temp\testthord\response-" + DateTime.Now.ToString("MMddyyyyhhmmssfff") + ".xml", reply.ToString());
     }
     catch (Exception e)
     {
         Log4Net.Logger.loggError(e, "Error in receiving response from Thord", "", "AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)"); 
     }
 }
コード例 #11
0
        public object BeforeSendRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel)
        {
            // Use the WSE 3.0 security token class
            UsernameToken token = new UsernameToken(this.Username, this.Password, PasswordOption.SendPlainText);

            // Serialize the token to XML
            XmlElement securityToken = token.GetXml(new XmlDocument());

            //
            MessageHeader securityHeader = MessageHeader.CreateHeader("Security", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd", securityToken, false);
            request.Headers.Add(securityHeader);

            MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
            request = buffer.CreateMessage();
            try
            {
                System.IO.File.WriteAllText(@"c:\temp\testthord\" + DateTime.Now.ToString("MMddyyyyhhmmssfff") + ".xml", request.ToString());
            }
            catch { }

            // complete
            return Convert.DBNull;
        }