Thursday, January 21, 2010

Raw Signed Soap Call


using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Web.Services2.Security.X509;
using Microsoft.Web.Services2;
using Microsoft.Web.Services2.Security.Tokens;
using Microsoft.Web.Services2.Security;
using System.Xml.Serialization;

namespace MDTestTool.Tests
{
class RawSoapTest : Microsoft.Web.Services2.Messaging.SoapClient
{
public RawSoapTest() { }
public RawSoapTest(string url) :base(new Uri(url))
{


}

public string getRawSoapResponseText( string soapText, string method)
{
try
{


this.Timeout = -1;
SoapEnvelope envelope = new SoapEnvelope();
envelope.LoadXml(soapText);


X509CertificateStore store = X509CertificateStore.CurrentUserStore(X509CertificateStore.MyStore);
bool open = store.OpenRead();
X509CertificateCollection col = store.Certificates;
bool found = false;
foreach (X509Certificate cert in col)
{
if (!found && cert.SupportsDigitalSignature && cert.IsCurrent )
{
SignMessage(envelope.Context, cert, 30000);



found = true;
}

}
if (!found) throw new Exception("No suitable Certificate Found");
SoapEnvelope resp = this.SendRequestResponse(method, envelope);
return resp.OuterXml;
}
catch (Exception ex)
{
return ex.Message;
}
}

private void SignMessage(SoapContext requestContext, X509Certificate certificate,int timestampTimeout){



X509SecurityToken stSecurityToken = new X509SecurityToken(certificate);

if (stSecurityToken != null){

MessageSignature sig = new MessageSignature(stSecurityToken);

requestContext.Security.Tokens.Add(stSecurityToken);
requestContext.Security.Elements.Add(sig);


requestContext.Security.Timestamp.TtlInSeconds = timestampTimeout;



}


}





}
}

2 comments:

Noel said...

This does not work yet. It is failing to add a messagecontext to the call

Noel said...

Actually this does work I missed a <MessageContext/> tag