Example #1
0
        public string DescribeReadyCode(ReadyCode code)
        {
            // Dump HTTP reqquest
            System.Web.HttpContext cntx = this.Context;
            cntx.Request.SaveAs(Server.MapPath("httpdump.txt"), true);

            // Verifies that a SOAP request was received.
            SoapContext requestContext = HttpSoapContext.RequestContext;

            if (requestContext == null)
            {
                throw new
                      ApplicationException("Either a non-SOAP request was " +
                                           "received or the WSE is not properly installed for " +
                                           "the Web application hosting the XML Web service.");
            }
            X509SecurityToken theToken = GetFirstX509Token(requestContext.Security);

            switch (code)
            {
            case ReadyCode.Ready:
                return("Systemet er klar til at modtage indberetningsklienten.");

            case ReadyCode.Error_CertificateExpired:
                return("Certifikatet er udløbet.");

            default:
            case ReadyCode.Error_Unknown:
                return("Ukendt fejl.");
            }
        }
Example #2
0
        private void InitializeServiceProxy()
        {
            // Create NodalService proxy reference
            _ercotClient = new NodalService();

            // Load cert and sign SOAP message
            // clientCert = new X509Certificate2(@"C:\Projects\ErcotAPITestWS\ErcotAPITest\Cert\API_103_CERT.pfx", "a1e5i9");
            _clientCert      = new X509Certificate2(CLIENT_CERT_PATH, CLIENT_CERT_PASSWORD);
            _ercotMisApiCert = new X509Certificate2(@"C:\Projects\ErcotAPITestWS\ErcotAPITest\Cert\misapi.cer");

            _ercotClient.ClientCertificates.Add(_clientCert);
            _ercotClient.ClientCertificates.Add(_ercotMisApiCert);

            _context = _ercotClient.RequestSoapContext;
            _token   = new X509SecurityToken(_clientCert);
            _token2  = new X509SecurityToken(_ercotMisApiCert);
            //These are obsolete but necessary since they use old technology
            _context.Security.Tokens.Add(_token);
            _context.Security.Tokens.Add(_token2);
            _context.Security.Elements.Add(new MessageSignature(_token));


            //Set TLS1.2 protocol
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

            // Handle service reply with a callback method
            _ercotClient.MarketInfoCompleted += this.ErcotClient_MarketInfoCompleted;
        }
        /// <summary>
        /// Attempts to handle the SOAP header described in <see cref="Namespace" /> and <seealso cref="Name" />.
        /// </summary>
        /// <param name="context">The <see cref="SoapContext" /> of the current SOAP request.</param>
        /// <returns>An awaitable <see cref="ValueTask" />.</returns>
        protected override async ValueTask InvokeAsync(SoapContext context)
        {
            var index = FindHeaderIndex(context, Name, Namespace);

            if (index >= 0)
            {
                Logger.LogDebug($"Attempting to handle header '{Name}'.");

                var header  = context.Request.Headers[index];
                var handled = false;
                try
                {
                    handled = await HandleHeaderAsync(context, header, index);
                }
                catch (Exception ex)
                {
                    Logger.LogWarning(ex, $"Could not understand header '{Name}'.");
                }
                finally
                {
                    if (handled)
                    {
                        context.Request.Headers.UnderstoodHeaders.Add(header);
                    }
                }
            }
            await Next(context);
        }
        private void CallWebService(int a, int b, string url)
        {
            // Instantiate an instance of the web service proxy
            AddNumbers  serviceProxy   = new AddNumbers();
            SoapContext requestContext = serviceProxy.RequestSoapContext;

            // Get our security token
            UsernameToken token = token = new UsernameToken(user, pass, PasswordOption.SendHashed);

            // Add the signature element to a security section on the request
            // to sign the request
            requestContext.Security.Tokens.Add(token);
            requestContext.Security.Elements.Add(new MessageSignature(token));

            // requestContext.Timestamp.Ttl = 6000000;
            // Call the service
            if (url != null)
            {
                serviceProxy.Url = url;
            }
            Console.WriteLine("Calling {0}", serviceProxy.Url);
            int sum = serviceProxy.AddInt(a, b);

            // Success!
            string message = string.Format("{0} + {1} = {2}", a, b, sum);

            Console.WriteLine("Web Service returned: {0}", message);
        }
        private void LoadDocumentsFromContext(ref NodeDocument[] documents)
        {
            SoapContext responseSoapContext = this.requestor.ResponseSoapContext;
            XmlElement  documentElement     = responseSoapContext.Envelope.DocumentElement;
            Hashtable   hashtable           = new Hashtable();
            XmlNodeList elementsByTagName   = documentElement.GetElementsByTagName("content");

            this.RaiseRequestorEvent("Parsing Documents");
            foreach (XmlNode node in elementsByTagName)
            {
                XmlAttributeCollection attributes = node.Attributes;
                if (attributes["href"] == null)
                {
                    throw new ApplicationException("Unable to find the href attribute in the context. Most likely because the response is not DIME. Please read the Node functional spec 1.1");
                }
                string str       = attributes["href"].Value;
                string innerText = node.ParentNode["name"].InnerText;
                hashtable.Add(innerText, str);
            }
            for (int i = 0; i < documents.Length; i++)
            {
                string         str3       = (string)hashtable[documents[i].name];
                DimeAttachment attachment = responseSoapContext.Attachments[str3];
                byte[]         buffer     = new BinaryReader(attachment.Stream).ReadBytes((int)attachment.Stream.Length);
                documents[i].content = buffer;
            }
        }
        private void HandleTimestamp(XmlReader reader, SoapContext soap)
        {
            var timestamp = ReadTimestamp(reader);

            AssertTimestamp(timestamp, soap);
            soap.SetWsSecurityTimestamp(timestamp);
        }
        private void HandleFaultException(FaultException ex, SoapContext <TService> context)
        {
            _logger.LogWarning(ex, $"Fault exception: {ex.Message}");
            var messageFault = ex.CreateMessageFault();

            context.Response = FaultMessage.CreateFaultMessage(context.MessageVersion, messageFault, context.Request.Headers.Action);
        }
Example #8
0
        public ReadyStatus Ready()
        {
            // Dump HTTP reqquest
            System.Web.HttpContext cntx = this.Context;
            cntx.Request.SaveAs(Server.MapPath("httpdump.txt"), true);

            // Verifies that a SOAP request was received.
            SoapContext requestContext = HttpSoapContext.RequestContext;

            if (requestContext == null)
            {
                throw new
                      ApplicationException("Either a non-SOAP request was " +
                                           "received or the WSE is not properly installed for " +
                                           "the Web application hosting the XML Web service.");
            }
            X509SecurityToken theToken = GetFirstX509Token(requestContext.Security);

            ReadyStatus r = new ReadyStatus();

            r.Status      = ReadyCode.Ready;
            r.Description = DescribeReadyCode(r.Status);

            return(r);
        }
Example #9
0
        private void CallWebService(int a, int b, string url)
        {
            // Instantiate an instance of the web service proxy
            AddNumbers  serviceProxy   = new AddNumbers();
            SoapContext requestContext = serviceProxy.RequestSoapContext;

            // Get the Asymmetric key
            X509SecurityToken token = GetEncryptionToken();

            if (token == null)
            {
                throw new ApplicationException("No security token provided.");
            }

            // Add an EncryptedData element to the security collection
            // to encrypt the request.
            requestContext.Security.Elements.Add(new EncryptedData(token));
            if (url != null)
            {
                serviceProxy.Url = url;
            }

            // Call the service
            Console.WriteLine("Calling {0}", serviceProxy.Url);
            int sum = serviceProxy.AddInt(a, b);

            // Success!
            string message = string.Format("{0} + {1} = {2}", a, b, sum);

            Console.WriteLine("Web Service returned: {0}", message);
        }
Example #10
0
        public void GetDataSet()
        {
            SoapContext sc = HttpSoapContext.ResponseContext;

            if (null == sc)
            {
                throw new ApplicationException("Only SOAP requests allowed");
            }

            SqlConnection conn = new SqlConnection(@"data source=(local)\NetSDK;" +
                                                   "initial catalog=Northwind;integrated security=SSPI");

            SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM customers", conn);
            DataSet        ds = new DataSet("CustomerDS");

            da.Fill(ds, "Customers");

            // dispose of all objects that are no longer necessary
            da.Dispose();
            conn.Dispose();

            MemoryStream     memoryStream = new MemoryStream(1024);
            GZipOutputStream gzipStream   = new GZipOutputStream(memoryStream);

            ds.WriteXml(gzipStream);
            gzipStream.Finish();
            memoryStream.Seek(0, SeekOrigin.Begin);

            DimeAttachment dimeAttachment = new DimeAttachment("application/x-gzip",
                                                               TypeFormatEnum.MediaType,
                                                               memoryStream);

            sc.Attachments.Add(dimeAttachment);
        }
Example #11
0
		private void cmdLoadDataset_Click(object sender, System.EventArgs e)
		{
			// call the service
			localhost.Service1 svc = new localhost.Service1();
			svc.GetDataSet();

			// get the SOAP context, see if there are attachments
			SoapContext sc = svc.ResponseSoapContext;
			if (1 != sc.Attachments.Count)
			{
				MessageBox.Show("Error: # of attachments received is not the # that was expected");
				return;
			}

			GZipInputStream gzipInputStream = new GZipInputStream(sc.Attachments[0].Stream);
			MemoryStream ms = new MemoryStream(1024);
			int nSize = 2048;
			byte[] writeData = new byte[2048];

			while (true) 
			{
				nSize = gzipInputStream.Read(writeData, 0, nSize);
				if (nSize > 0) 
					ms.Write(writeData, 0, nSize);
				else 
					break;
			}
			
			ms.Seek(0, SeekOrigin.Begin);

			DataSet ds = new DataSet();
			ds.ReadXml(ms);
			dg.SetDataBinding(ds, "Customers");
		}
Example #12
0
        private void CallWebService(int a, int b, string url)
        {
            // Instantiate an instance of the web service proxy
            AddNumbers  serviceProxy   = new AddNumbers();
            SoapContext requestContext = serviceProxy.RequestSoapContext;

            // Get our security token
            X509SecurityToken token = GetSecurityToken();

            if (token == null)
            {
                throw new ApplicationException("No key provided for signature.");
            }

            // Add the signature element to a security section on the request
            // to sign the request
            requestContext.Security.Tokens.Add(token);
            requestContext.Security.Elements.Add(new MessageSignature(token));

            //requestContext.Timestamp.Ttl = 6000000;
            // Call the service
            if (url != null)
            {
                serviceProxy.Url = url;
            }
            Console.WriteLine("Calling {0}", serviceProxy.Url);
            int sum = serviceProxy.AddInt(a, b);

            // Success!
            string message = string.Format("{0} + {1} = {2}", a, b, sum);

            Console.WriteLine("Web Service returned: {0}", message);
        }
Example #13
0
        public void SetTechnicalSupportUserSecurity()
        {
            UsernameToken userToken      = new UsernameToken("[email protected]%1987654323", "kennwort", PasswordOption.SendPlainText);
            SoapContext   requestContext = RequestSoapContext;

            requestContext.Security.Tokens.Clear();
            requestContext.Security.Tokens.Add(userToken);
        }
 public static void VerifyMessageParts(SoapContext context)
 {
     // Body
     if (context.Envelope.Body == null)
     {
         throw new ApplicationException("The message must contain a soap:Body element");
     }
 }
Example #15
0
        public void SetRegistrarSecurity()
        {
            UsernameToken userToken      = new UsernameToken("*****@*****.**", "kennwort", PasswordOption.SendPlainText);
            SoapContext   requestContext = RequestSoapContext;

            requestContext.Security.Tokens.Clear();
            requestContext.Security.Tokens.Add(userToken);
        }
Example #16
0
        public void SetDefaultSecurity()
        {
            // Setup WS-Security authentication
            UsernameToken userToken      = new UsernameToken(Username, Password, PasswordOption.SendPlainText);
            SoapContext   requestContext = RequestSoapContext;

            requestContext.Security.Tokens.Add(userToken);
            //requestContext.Security.Timestamp.TtlInSeconds = SvcConfig.TtlInSeconds;
        }
        private void AssertTimestamp(Timestamp timestamp, SoapContext context)
        {
            // TODO: add clock skew options
            var now = Clock.UtcNow.UtcDateTime;

            if (timestamp.Created.AddMinutes(-5).ToUniversalTime() > now || timestamp.Expires.ToUniversalTime() < now)
            {
                throw context.CreateMessageExpiredFault();
            }
        }
Example #18
0
        private void SetMustUnderstand()
        {
            this.RaiseRequestorEvent("Getting SOAP Context");
            SoapContext requestSoapContext = this.requestor.RequestSoapContext;

            requestSoapContext.Path.EncodedMustUnderstand = "false";
            requestSoapContext.Attachments.Clear();
            this.RaiseRequestorEvent("Clearing Attachments");
            requestSoapContext.Clear();
        }
Example #19
0
        //get certificate and attach it
        public static void prepareSoapContext(SoapContext soapContext)
        {
            X509Certificate2  ucert    = GetCertificate();
            X509SecurityToken cerToken = new X509SecurityToken(ucert);

            MessageSignature cerSig = new MessageSignature(cerToken);

            soapContext.Security.Elements.Add(cerSig);


            // requestContext.Security.Tokens.Add(cerToken);
        }
        private FaultException CreateFaultException(SoapContext context, Exception exception)
        {
            var version = context.MessageVersion;
            var code    = version.CreateFaultCode();

            if (context.Options.IncludeExceptionDetailInFaults)
            {
                var detail = new ExceptionDetail(exception);
                return(new FaultException <ExceptionDetail>(detail, version.CreateFaultReason(exception.Message)));
            }

            return(new FaultException(version.CreateFaultReason(), code, context.Request.Headers.Action));
        }
Example #21
0
    protected void Page_Load(object sender, EventArgs e)
    {
        MyService.ServiceWse wse = new MyService.ServiceWse();
        wse.SetPolicy("UserTokenClient");
        UsernameToken token = new UsernameToken("naynish", "bhairav@12", PasswordOption.SendPlainText);

        wse.SetClientCredential(token);
        SoapContext reqContext = wse.RequestSoapContext;

        reqContext.Security.Timestamp.TtlInSeconds = 120;
        reqContext.Security.Tokens.Add(token);
        Label1.Text = wse.HelloWorld();
    }
Example #22
0
        private void CallWebService(int a, int b)
        {
            AddNumbers  serviceProxy   = new AddNumbers();
            SoapContext requestContext = serviceProxy.RequestSoapContext;

            requestContext.Timestamp.Ttl = 60000;

            Console.WriteLine("Calling {0}", serviceProxy.Url);
            int sum = serviceProxy.AddInt(a, b);

            string message = string.Format("{0} + {1} = {2}", a, b, sum);

            Console.WriteLine("Web Service called successfully: {0}", message);
        }
        static bool CheckSignature(SoapContext context, MessageSignature signature)
        {
            //
            // Now verify which parts of the message were actually signed.
            //
            SignatureOptions actualOptions   = signature.SignatureOptions;
            SignatureOptions expectedOptions = SignatureOptions.IncludeSoapBody;

            if (context.Security != null && context.Security.Timestamp != null &&
                context.Security.Timestamp.TargetElement != null)
            {
                expectedOptions |= SignatureOptions.IncludeTimestamp;
            }

            //
            // The <Action> and <To> are required addressing elements.
            //
            expectedOptions |= SignatureOptions.IncludeAction;
            expectedOptions |= SignatureOptions.IncludeTo;

            if (context.Addressing.FaultTo != null && context.Addressing.FaultTo.TargetElement != null)
            {
                expectedOptions |= SignatureOptions.IncludeFaultTo;
            }

            if (context.Addressing.From != null && context.Addressing.From.TargetElement != null)
            {
                expectedOptions |= SignatureOptions.IncludeFrom;
            }

            if (context.Addressing.MessageID != null && context.Addressing.MessageID.TargetElement != null)
            {
                expectedOptions |= SignatureOptions.IncludeMessageId;
            }

            if (context.Addressing.RelatesTo != null && context.Addressing.RelatesTo.TargetElement != null)
            {
                expectedOptions |= SignatureOptions.IncludeRelatesTo;
            }

            if (context.Addressing.ReplyTo != null && context.Addressing.ReplyTo.TargetElement != null)
            {
                expectedOptions |= SignatureOptions.IncludeReplyTo;
            }
            //
            // Check if the all the expected options are the present.
            //
            return((expectedOptions & actualOptions) == expectedOptions);
        }
Example #24
0
        //[System.Web.Services.Protocols.SoapRpcMethod()]
        public string SayHello(string name)
        {
            SoapContext              requestContext  = Microsoft.Web.Services2.RequestSoapContext.Current;
            SoapContext              responseContext = Microsoft.Web.Services2.ResponseSoapContext.Current;
            ISecurityTokenManager    stm             = SecurityTokenManager.GetSecurityTokenManagerByTokenType(WSTrust.TokenTypes.X509v3);
            X509SecurityTokenManager x509tm          = stm as X509SecurityTokenManager;

            x509tm.DefaultSessionKeyAlgorithm = "TripleDES";

            //----------Encryption
            X509SecurityToken x509Token = getToken("client");

            if (x509Token == null)
            {
                //throw new SecurityFault(SecurityFault.FailedAuthenticationMessage, SecurityFault.FailedAuthenticationCode);
                throw new SecurityFault("Could not get encryption token...", SecurityFault.FailedAuthenticationCode);
            }
            else
            {
                EncryptedData ed = new EncryptedData(x509Token);
                responseContext.Security.Tokens.Add(x509Token);
                responseContext.Security.Elements.Add(ed);
            }

            //---------UsernameToken
//			UsernameToken usernameToken = GetSigningToken() as UsernameToken;
//			if (usernameToken == null || usernameToken.PasswordOption == PasswordOption.SendPlainText) {
//				throw new SecurityFault(SecurityFault.FailedAuthenticationMessage, SecurityFault.FailedAuthenticationCode);
//			}
//
            //---------Signature
//			//X509SecurityToken
            x509Token = getToken("server");
            X509SecurityToken x509TokenSigningToken = GetSigningToken() as X509SecurityToken;

            if (x509TokenSigningToken == null)               //|| !CompareArray(x509TokenSigningToken.KeyIdentifier.Value, Convert.FromBase64String(clientKeyIdentifier))) {
            {
                throw new SecurityFault("Could not get signing token...", SecurityFault.FailedAuthenticationCode);
            }
            else
            {
                responseContext.Security.Tokens.Add(x509Token);
                responseContext.Security.Elements.Add(new MessageSignature(x509Token));
            }

            return("Hello," + name);
        }
Example #25
0
    public string HelloWorld()
    {
        SoapContext cntxt = RequestSoapContext.Current;

        if (cntxt == null)
        {
            return("must have soap request context");
        }
        foreach (SecurityToken item in cntxt.Security.Tokens)
        {
            if (item is UsernameToken)
            {
                UsernameToken user = (UsernameToken)item;
                return("user: "******"Hello World");
    }
Example #26
0
        private static void serviceClientSetting(WebServicesClientProtocol serviceClient, string url, string username = null, string password = null, int timeout = -1)
        {
            serviceClient.Url = url;

            /* timeout is 0 if config verb EBSServiceTimeout is not defined.
             * It is set at the _sr_client CS_SERVICEREQUEST_PUB_Service() instance
             * level, so all the ws calls (from this proxy client) have this timeout setting
             */
            serviceClient.Timeout = timeout == 0 ? -1 : timeout;

            if (!String.IsNullOrWhiteSpace(username) && !String.IsNullOrWhiteSpace(password))
            {
                // add wsse:Security headers.
                UsernameToken userNameToken = new UsernameToken(username, password, PasswordOption.SendPlainText);
                SoapContext   soapContext   = serviceClient.RequestSoapContext;
                soapContext.Security.Tokens.Add(userNameToken);
            }
        }
Example #27
0
        public SecurityToken GetSigningToken()
        {
            SoapContext context = RequestSoapContext.Current;

            foreach (ISecurityElement element in context.Security.Elements)
            {
                if (element is MessageSignature)
                {
                    // The given context contains a Signature element.
                    MessageSignature sig = element as MessageSignature;
                    return(sig.SigningToken);
                    //if (CheckSignature(context, sig)) {
                    //	return sig.SigningToken;
                    //}
                }
            }
            return(null);
        }
        public static SecurityToken GetSigningToken(SoapContext context)
        {
            foreach (ISecurityElement element in context.Security.Elements)
            {
                if (element is MessageSignature)
                {
                    // The given context contains a Signature element.
                    MessageSignature sig = element as MessageSignature;

                    if (CheckSignature(context, sig))
                    {
                        // The SOAP Body is signed.
                        return(sig.SigningToken);
                    }
                }
            }

            return(null);
        }
Example #29
0
        private void AddDocumentsToContext(NodeDocument[] documents)
        {
            this.SetMustUnderstand();
            SoapContext requestSoapContext = this.requestor.RequestSoapContext;
            Hashtable   hashtable          = new Hashtable();

            this.RaiseRequestorEvent("Parsing Documents");
            for (int i = 0; i < documents.Length; i++)
            {
                DimeAttachment attachment = new DimeAttachment();
                attachment.TypeFormat = TypeFormatEnum.MediaType;
                attachment.Type       = "application/octet-stream";
                attachment.Id         = string.Format("Document-{0}", i);
                attachment.Stream     = new MemoryStream(documents[i].content);
                requestSoapContext.Attachments.Add(attachment);
                hashtable.Add(documents[i].name, attachment.Id);
                this.RaiseRequestorEvent("Document Parsed");
            }
            requestSoapContext.Add("hrefs", hashtable);
        }
Example #30
0
        protected override async ValueTask InvokeAsync(SoapContext context)
        {
            var action   = context.Request.Headers.Action;
            var instance = context.RequestServices.GetService(context.Contract);

            var methodInfo = _locator.GetMethod(context.Contract, action);
            var name       = _locator.GetOperationName(context.Contract, action);
            var ns         = _locator.GetNamespace(context.Contract, action);

            var parameters = _reader.ReadParameters(methodInfo, context.Request, ns);
            var result     = await _invoker.InvokeMethodAsync(instance, methodInfo, parameters, context.CancellationToken);

            var response = result.Result as Message;

            if (response == null)
            {
                var serializer = new OperationResponseSerializer(result.OutParameters, ns, name);
                response = Message.CreateMessage(context.MessageVersion, null, result.Result, serializer);
            }
            context.Response = response;
        }
	  public static SecurityToken GetEncryptingToken(SoapContext context)
	    {
	      SecurityToken encryptingToken = null;

	      foreach (ISecurityElement element in context.Security.Elements)
		{
		  if (element is EncryptedData)
		    {
		      EncryptedData encryptedData = element as EncryptedData;
		      System.Xml.XmlElement targetElement = encryptedData.TargetElement;										

		      if ( SoapEnvelope.IsSoapBody(targetElement))
			{
			  // The given context has the Body element Encrypted.
			  encryptingToken = encryptedData.SecurityToken;
			}
		    }
		}

	      return encryptingToken;
	    }
        /// <summary>
        /// Gets the license token.
        /// </summary>
        /// <param name="context"> The SoapContext type.</param>
        /// <returns> A UsernameToken type.</returns>
        public static UsernameToken GetLicenseToken(SoapContext context)
        {
            if (context == null)
                throw new Exception(
                    "Only SOAP requests are permitted.");

            // Make sure there's a token
            if (context.Security.Tokens.Count == 0)
            {
                throw new SoapException(
                    "Missing security token",
                    SoapException.ClientFaultCode);
            }
            else
            {
                if ( context.Security.Tokens["LicenseToken"] != null )
                {
                    UsernameToken tok = (UsernameToken)context.Security.Tokens["LicenseToken"];

                    return tok;
            //
            //					if ( tok.Password.Length > 16 )
            //					{
            //						throw new SoapException(
            //							"Missing security token",
            //							SoapException.ClientFaultCode);
            //					}
            //					else
            //					{
            //						return tok;
            //					}
                }
                else
                {
                    throw new Exception("LicenseToken not supplied");
                }
            }
        }
	  public static void VerifyMessageParts(SoapContext context) 
	    {
	      // Body
	      if ( context.Envelope.Body == null )
		throw new ApplicationException("The message must contain a soap:Body element");
	    }
	  public static SecurityToken GetSigningToken(SoapContext context)
	    {
	      foreach ( ISecurityElement element in context.Security.Elements )
		{
		  if ( element is MessageSignature )
		    {
		      // The given context contains a Signature element.
		      MessageSignature sig = element as MessageSignature;

		      if (CheckSignature(context, sig))
			{
			  // The SOAP Body is signed.
			  return sig.SigningToken;
			}
		    }
		}

	      return null;
	    }
	  static bool CheckSignature(SoapContext context, MessageSignature signature)
	    {
	      //
	      // Now verify which parts of the message were actually signed.
	      //
	      SignatureOptions actualOptions   = signature.SignatureOptions;
	      SignatureOptions expectedOptions = SignatureOptions.IncludeSoapBody;

	      if (context.Security != null && context.Security.Timestamp != null  
		  && context.Security.Timestamp.TargetElement != null) 
		expectedOptions |= SignatureOptions.IncludeTimestamp;

	      //
	      // The <Action> and <To> are required addressing elements.
	      //
	      expectedOptions |= SignatureOptions.IncludeAction;
	      expectedOptions |= SignatureOptions.IncludeTo;

	      if ( context.Addressing.FaultTo != null && context.Addressing.FaultTo.TargetElement != null )
		expectedOptions |= SignatureOptions.IncludeFaultTo;

	      if ( context.Addressing.From != null && context.Addressing.From.TargetElement != null )
		expectedOptions |= SignatureOptions.IncludeFrom;

	      if ( context.Addressing.MessageID != null && context.Addressing.MessageID.TargetElement != null )
		expectedOptions |= SignatureOptions.IncludeMessageId;

	      if ( context.Addressing.RelatesTo != null && context.Addressing.RelatesTo.TargetElement != null )
		expectedOptions |= SignatureOptions.IncludeRelatesTo;

	      if ( context.Addressing.ReplyTo != null && context.Addressing.ReplyTo.TargetElement != null )
		expectedOptions |= SignatureOptions.IncludeReplyTo;
	      //
	      // Check if the all the expected options are the present.
	      //
	      return ( ( expectedOptions & actualOptions ) == expectedOptions );

	    }