Click here to Skip to main content
Email Password   helpLost your password?

Introduction

This article is an attempt to share my WSE 3.0 investigations and give a working real-world example of securing web services.

The WSE 3.0 library provides a number of �Turnkey� security mechanisms based on X.509 certificates, Username tokens over SSL, or Kerberos tickets. All that stuff like X.509, SSL, Kerberos tickets is good in laboratory conditions or for enterprise level applications where the hosting environment (or deployment target) is under full control. Relatively simple applications require a much simpler implementation (but not less secure ;-)), so we used to implement a security based on Username tokens derived from username and password. This technique doesn�t demand any specific requirements to the hosting environment.

This article gives answers to the following questions:

Background

Of course, this article requires a good understanding of SOAP web services and some previous experience with the WSE 2.0 library. However, the code from this article is self-containing and can be used in your applications with minor or no changes.

Before including this code to your production application, take a look at the WSE development center to grab more information about what is this and how it can be used.

The WSE 3.0 October CTP library (the latest WSE release) that is required to run the samples below can be downloaded from here. Please note, the library is still in beta, but it works perfectly with the .NET 2.0 RTM. Microsoft promises that WSE will be released closer to the official VS.NET 2005 go-live date which is currently November 7, 2005.

So, don�t waste your time and start learning this exciting new technology right now and migrating your almost legacy ;-) WSE 2.0 code!

Using the code

Before describing the code snippets I�d like to say some words about the basic idea of the overall WSE 3.0 architecture. The first sight on WSE 3.0 leaves a feeling that it will be so hard and long to get it work for you and there is not any desire for implementing it. But after spending some time studying and experimenting with the code you start realizing that WSE 3.0 is a huge step forward in comparison to the previous WSE 2.0 allowing writing less code and giving more flexibility in configuration.

WSE 3.0 is based on policies. Each individual policy can be applied to either a web service class or a web service proxy (client) class. A policy is a set of assertions. I think �assertion� is quite an unsuitable word here, but it occurs that assertion is just a factory class for creating input/output SOAP filters that will be injected in the SOAP processing pipeline. All policies can be declared in a separate �policy cache� file and then can be assigned to the web service class with the help of an attribute or to the proxy class programmatically. A policy cache file is an XML document including:

  1. the set of so-named �extensions� that are simply the list of named assertions with their corresponding type names and
  2. policies themselves each of which is a list of extensions (assertions) with corresponding optional configuration elements inside.

Well, let�s start writing the code! The first step is to implement a custom assertion which will be applied to the web service proxy. The primary function of assertion is constructing four SOAP filters:

  1. Client output filter (working with the SOAP request issued by the client)
  2. Client input filter (working with the SOAP response received from the service)
  3. Service input filter (working with the SOAP request received from the client)
  4. Service output filter (working with the SOAP response issued by the web service)

The second optional function of assertion is parsing the assertion configuration elements from the policy cache file. This step is required if the assertion is applied declaratively through the policy cache file.

The code for our client Username assertion:

public class UsernameClientAssertion : SecurityPolicyAssertion
{
    private string username;
    private string password;

    public UsernameClientAssertion(string username, string password)
    {
        this.username = username;
        this.password = password;
    }

    public override SoapFilter 
           CreateClientOutputFilter(FilterCreationContext context)
    {
        return new ClientOutputFilter(this, context);
    }

    public override SoapFilter 
           CreateClientInputFilter(FilterCreationContext context)
    {
        // we don't provide ClientInputFilter

        return null;
    }

    public override SoapFilter 
           CreateServiceInputFilter(FilterCreationContext context)
    {
        // we don't provide any processing for web service side

        return null;
    }

    public override SoapFilter 
           CreateServiceOutputFilter(FilterCreationContext context)
    {
        // we don't provide any processing for web service side

        return null;
    }

    ...
}

As our client assertion requires username and password, it will be assigned to the proxy imperatively in the code and thus, the assertion has a constructor for passing credentials. The credentials are just stored in the private fields and then can be accessed in output filter.

Our client assertion provides only one �ClientOutputFilter�. The primary purposes of the client output filter are:

  1. Create username token.
  2. Sign SOAP message with username token.
  3. Encrypt SOAP body.
  4. Encrypt SOAP custom headers marked with a special namespace.

The code of the client output filter:

class ClientOutputFilter : SendSecurityFilter
{
    UsernameClientAssertion parentAssertion;
    FilterCreationContext filterContext;

    public ClientOutputFilter(UsernameClientAssertion parentAssertion, 
                              FilterCreationContext filterContext)
        : base(parentAssertion.ServiceActor, false, parentAssertion.ClientActor)
    {
        this.parentAssertion = parentAssertion;
        this.filterContext = filterContext;
    }

    public override void SecureMessage(SoapEnvelope envelope, Security security)
    {
        UsernameToken userToken = new UsernameToken(
            parentAssertion.username,
            parentAssertion.password,
            PasswordOption.SendNone);
              // we don't send password over network

              // but we just use username/password to sign/encrypt message


        // Add the token to the SOAP header.

        security.Tokens.Add(userToken);

        // Sign the SOAP message by using the UsernameToken.

        MessageSignature sig = new MessageSignature(userToken);
        security.Elements.Add(sig);

        // encrypt BODY

        EncryptedData data = new EncryptedData(userToken);

        // encrypt custom headers

        for (int index = 0; index < 
                 envelope.Header.ChildNodes.Count; index++)
        {
            XmlElement child = 
              envelope.Header.ChildNodes[index] as XmlElement;

            // find all SecureSoapHeader headers

            // marked with a special attribute

            if (child != null && child.NamespaceURI == 
                         "http://company.com/samples/wse/")
            {
                // create ID attribute for referencing purposes

                string id = Guid.NewGuid().ToString();
                child.SetAttribute("Id", "http://docs.oasis-" + 
                      "open.org/wss/2004/01/oasis-200401-" + 
                      "wss-wssecurity-utility-1.0.xsd", id);

                // Create an encryption reference for the custom SOAP header.

                data.AddReference(new EncryptionReference("#" + id));
            }
        }

        // add ancrypted data to the security context

        security.Elements.Add(data);
    }
}

It is pretty suitable to define assertion filters as inner classes, because they would have simple names and they can see parent assertion fields.

The base SOAP header class that all your headers should be derived from to be secured, looks like the following:

/// <summary>

/// This is base class for all custom SOAP headers

/// that should be encrypted in the response.

/// </summary>

public class SecureSoapHeader : SoapHeader
{
    /// <summary>

    /// This property is just a flag telling us

    /// that this SOAP header should be encrypted.

    /// </summary>

    [XmlAttribute("SecureHeader", 
       Namespace="http://company.com/samples/wse/")]
    public bool SecureHeader;
}

The code encrypting custom SOAP headers is quite unique here. I was Googling the internet trying to find information about this subject and had no success. Then I decided to write my own solution. I spent a certain time to realize how it can be implemented using standard functionality. The code is based on the sample: how to sign custom SOAP headers, given in the WSE 3.0 documentation. When playing with signing custom headers, I noticed at least two inconsistencies in the provided sample:

  1. Within the custom SOAP header you can�t declare a custom �Id� property mapped to the XML �Id� attribute with this namespace. Certainly, you can do this, but it doesn�t make sense, because when the initial SOAP message is serialized, this system namespace is re-declared with a random prefix, not the �wsu� prefix as expected. The answer to this problem is that if you want to add a service �wsu:id� attribute to your custom header, you should do this after the �wsu� namespace has been declared.
  2. The second inconsistency is that when you are creating SignatureReference or EncryptionReference, to add it to the respective collection you should specify the reference URI in the form �#[id]� (where [id] is the unique identifier of the node � GUID), not �#Id:[id]� like the documentation suggests.

That�s all the required code for the client side. The code for how to specify this assertion for the client will be given below. For now let�s turn to the web service side and consider the service-side assertion. The code for UsernameServiceAssertion is:

public class UsernameServiceAssertion : SecurityPolicyAssertion
{
    public UsernameServiceAssertion()
    {
    }

    public override SoapFilter 
           CreateClientOutputFilter(FilterCreationContext context)
    {
        // we don't provide any processing for client side

        return null;
    }

    public override SoapFilter 
           CreateClientInputFilter(FilterCreationContext context)
    {
        // we don't provide any processing for client side

        return null;
    }

    public override SoapFilter 
           CreateServiceInputFilter(FilterCreationContext context)
    {
        return new ServiceInputFilter(this, context);
    }

    public override SoapFilter 
           CreateServiceOutputFilter(FilterCreationContext context)
    {
        // we don't provide ServiceOutputFilter

        return null;
    }

    public override void ReadXml(XmlReader reader, 
           IDictionary<string, Type> extensions)
    {
        if (reader == null)
            throw new ArgumentNullException("reader");
        if (extensions == null)
            throw new ArgumentNullException("extensions");

        // determine the name of the extension

        string tagName = null;
        foreach (string extName in extensions.Keys)
        {
            if (extensions[extName] == 
                typeof(UsernameServiceAssertion))
            {
                tagName = extName;
                break;
            }
        }

        // read the first element (maybe empty)

        reader.ReadStartElement(tagName);
    }

    public override void WriteXml(XmlWriter writer)
    {
        // Typically this is not needed for custom policies

    }

    ...
}

Note the difference from the client assertion: we return only the service input filter and add two additional methods for working with the assertion configuration elements. The ReadXml method in our example is just reading an empty XML element declaring an assertion in the policy. Also, the documentation doesn�t mention these two methods, but when you apply the assertion declaratively in the policy cache file, it will fail if the ReadXml method is not overridden.

The main purpose of the service input filter is checking which SOAP elements are signed and encrypted (I�ve removed the code checking encrypted elements to make the example simpler).

The code for the ServiceInputFilter class:

public class ServiceInputFilter : ReceiveSecurityFilter
{
    UsernameServiceAssertion parentAssertion;
    FilterCreationContext filterContext;

    public ServiceInputFilter(UsernameServiceAssertion parentAssertion, 
           FilterCreationContext filterContext)
           : base(parentAssertion.ServiceActor, false, 
                  parentAssertion.ClientActor)
    {
        this.parentAssertion = parentAssertion;
        this.filterContext = filterContext;
    }

    public override void ValidateMessageSecurity(SoapEnvelope envelope, 
                                                     Security security)
    {
        bool IsSigned = false;
        if (security != null)
        {
            foreach (ISecurityElement element in security.Elements)
            {
                if (element is MessageSignature)
                {
                    // The given context contains a Signature element.

                    MessageSignature sign = element as MessageSignature;

                    if (CheckSignature(envelope, security, sign))
                    {
                        // The SOAP message is signed.

                        if (sign.SigningToken is UsernameToken)
                        {
                            // The SOAP message is signed 

                            // with a UsernameToken.

                            IsSigned = true;
                        }
                    }
                }
            }
        }

        if (!IsSigned)
            throw new SecurityFault("Message did" + 
               " not meet security requirements.");
    }

    private bool CheckSignature(SoapEnvelope envelope, 
                 Security security, MessageSignature signature)
    {
        //

        // Now verify which parts of the message were actually signed.

        //

        SignatureOptions actualOptions = signature.SignatureOptions;
        SignatureOptions expectedOptions = SignatureOptions.IncludeSoapBody;

        if (security != null && security.Timestamp != null)
            expectedOptions |= SignatureOptions.IncludeTimestamp;

        //

        // The <Action> and <To> are required addressing elements.

        //

        expectedOptions |= SignatureOptions.IncludeAction;
        expectedOptions |= SignatureOptions.IncludeTo;

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

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

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

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

        if (envelope.Context.Addressing.ReplyTo != null && 
            envelope.Context.Addressing.ReplyTo.TargetElement != null)
              expectedOptions |= SignatureOptions.IncludeReplyTo;
        //

        // Check if the all the expected options are the present.

        //

        return ((expectedOptions & actualOptions) == expectedOptions);

    }
}

The filter class is also implemented as an inner class for UsernameServiceAssertion.

In order to verify username tokens on the service side, you should provide a custom implementation of the Username token manager class. For our example, it may look as follows:

public class ServiceUsernameTokenManager : UsernameTokenManager
{
    /// <summary>

    /// Constructs an instance of this security token manager.

    /// </summary>

    public ServiceUsernameTokenManager()
    {
    }

    /// <summary>

    /// Constructs an instance of this security token manager.

    /// </summary>

    /// <param name="nodes">An XmlNodeList containing

    /// XML elements from a configuration file.</param>

    public ServiceUsernameTokenManager(XmlNodeList nodes)
        : base(nodes)
    {
    }

    /// <summary>

    /// Returns the password or password equivalent for the username provided.

    /// </summary>

    /// <param name="token">The username token</param>

    /// <returns>The password (or password equivalent) for the username</returns>

    protected override string AuthenticateToken(UsernameToken token)
    {
        string username = token.Username;

        // it's up to you where you will get a password for some user

        // you may:

        // 1) get the password hash from web.config or system registry

        //    if you are implementing per-server security

        // 2) get the password from the database or XML file for the given user name


        // for example purposes we just return a reversed value of username

        char[] ch = username.ToCharArray();
        Array.Reverse(ch);
        return new String(ch);
    }

}

The goal of the AuthenticateToken method is to return passwords corresponding to usernames.

Now let�s see how to use all the logic above to secure the communication between the client and the service.

The first step is enabling WSE 3.0 support for both the client and the service in the app.config and the web.config files respectively:

  1. Add WSE configuration section handler.
  2. Add the <soapServerProtocolFactory> element for WSE in the <webServices> element (service only).
  3. Add the WSE configuration section.
  4. Specify the custom security token manager class (service only).
  5. Specify the name of the policy cache file (service only and possibly client, but not in our example).

For more details on how to enable WSE support, you may inspect the app.config and the web.config in the attached article sample.

The second step is creating a policy cache file for use within the web service. For our example, it may look as the follows:

<policies xmlns="http://schemas.microsoft.com/wse/2005/06/policy">
  <extensions>
    <extension name="usernameAssertion" 
      type="UsernameAssertionLibrary.UsernameServiceAssertion, 
                                     UsernameAssertionLibrary" />
  </extensions>
  <policy name="ServerPolicy">
    <usernameAssertion />
  </policy>
</policies>

The third step is applying a policy to the web service with the �Policy� attribute as follows:

...
using Microsoft.Web.Services3; 

[WebService(Namespace = "http://company.com/samples/wse/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[Policy("ServerPolicy")]
// we define policy on service level,

// so each service method will be covered by it

public class Service : System.Web.Services.WebService
// look, you don't need to inherit

// your service from some custom class

{
   ...

The forth step is applying a policy to the web service proxy:

// create web service proxy

// NOTE!!! When updating web reference in Visual Studio,

// don't forget to change its base class

// to Microsoft.Web.Services3.WebServicesClientProtocol then

WseSample.Service srv = new WseSample.Service();

// create custom SOAP header and assign it to web service

WseSample.BankAccountSettings settings = 
    new WseSample.BankAccountSettings();
settings.PinCode = "1111";
srv.BankAccountSettingsValue = settings;

// create custom policy assertion and assign it to proxy

// for password we just use reversed username

// it's important, because UsernameTokenManager

// on the service side applies the same logic

// when looking for user password

UsernameClientAssertion assert = 
   new UsernameClientAssertion("admin", "nimda");

// create policy

Policy policy = new Policy();
policy.Assertions.Add(assert);

// and set it to web service

srv.SetPolicy(policy);

// invoke web service method

bool valid = srv.CheckAccountStatus("123456");

That�s all! Now all calls to your web service are authenticated and all sensitive request information is encrypted! You may verify this by checking the InputTrace.webinfo and OutputTrace.webinfo trace files for both the service and the client.

Conclusion

I�d like to give some ideas for how the sample from the article can be improved:

  1. You may add authorization logic to your web service. Just add the code for creating custom IPrincipal in UsernameTokenManager and role checks inside web methods.
  2. Signing and encrypting the SOAP response. You may implement additional service output and client input filters to sign/encrypt SOAP responses and verify them on the client side.
  3. Compression assertion. You may write a custom assertion using System.IO.Compression classes to compress/decompress SOAP requests/responses.
  4. You may implement assertions to make authentication/authorization work with SOAP clients written in other languages as Perl, PHP, and VBScript (SOAP Toolkit).

History

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
Generalwebmethod cache no effect (with use wse 3.0 custom assertion)
micy_15314
0:58 30 Jan '10  
hi
i use Custom WSE 3.0 Policy Assertions for Signing and Encrypting SOAP Messages with Username Tokens but
webmethod cache no effect in my source code
[WebMethod(CacheDuration=60)]
if i don't use it (wse 3.0)
this work correctly
GeneralHELP FOR MY THESIS
xle2911
11:22 18 Nov '09  
HI I THANK YOU FOR YOUR CONTRIBUTION. I WOULD LIKE TO ASK YOU YOUR EMAIL BECAUSE I AM DEVELOPING MY THESIS PROYECT AND I NEED SUPPORT.

HELP ME PLEASE MY EMAIL IS XLE2911@HOTMAIL.COM
GeneralHow to using with java Client
pako_239
9:52 20 Jul '09  
How i can map this to a java client?? what i need to do?
GeneralMy vote of 1
pophelix
7:18 23 Mar '09  
can't debug and do't chang the user and password
QuestionCan you do Policy Assignment to the webservice in code?
Ian Moores
1:25 26 Nov '08  
Can you do Policy Assignment to the webservice in code dependant on, say protocol usage, port, etc..... we want one web service to support multiple policies, dependant on who is calling it... any ideas?

Please visit http://www.ianmoores.ic24.net

QuestionThanks but what about secure conversations?
calahans
4:30 10 Jun '08  
This article has been a great help, but I am looking to enable a secure conversation with this. No matter what I do I never get the token back after the first call - I am trying :

SecurityContextToken sct2 =srv.GetClientCredential<SecurityContextToken>();

Any help welcomed.

Thanks
GeneralWhich line of CheckSignature actually checks custome header ?
kyus94
9:11 4 Jun '08  
Which line of CheckSignature actually checks custome header ?
CheckSignature checks all the default elements. Can some one pleasex explain how it checks the signature of custom soap header

kyus

GeneralInvoke from web browser
Crisan Radu
4:54 2 Jun '08  
Hello,

Congratulations for the sample, it is great value for my needs. Could you please clarify for me a small detail? Why there is no user authentication performed when method is executed from web browser? In your web service sample there is a "settings" protection to prevent execution from web browser, but till then I expect to have a block based on user/password assertion. Many thanks.
GeneralServer Not Found Exception
Samual Jones
23:11 12 Apr '08  
Hi,

I am getting "server not found" exception when i add policy attribute to the web service. My web service dont have any header. How can i encrypt message body.

Can i turn encryption on and off at runtime.
Questionwhat a perfect sample!! however [modified]
shin.hyunseok
20:17 29 Oct '07  
does these codes can chages WSDL or inside of WSDL policy? You know, if a client is JAVA or something so that client has no idea which authentication is needed to operatae with .NET server. From my understanding, WSDL gives all information to operate with web service Server. but this codes can not change WSDL policy.
IS THERE ANY WAY that i can give authentication policy information through WSDL or am i worng to approch to solve authentication notice problems?

can you give me an idea? plz? i have been search this authentication problems for 4 weeks


-- modified at 20:19 Thursday 1st November, 2007
GeneralRe: what a perfect sample!! however
MadShad
2:13 13 Apr '08  
WS-Security is a public standard.

WSDL is designed to provide meta information in order to generate a proxy implementation for the service.

This means that architectural (Java, PHP, etc.) implementations of that standard are responsible for the interpretation of the WSDL.

The policy is a means of defining additional information required to interpret the details of a specific implementation. This information may or may not be a defined standard.

If the policy defines a non-standard implementation (such as here in this article) then it becomes your responsibility to understand and create a corresponding implementation in the architecture of your choice (Java, PHP, etc.)

I think I have answered your question, nö? WTF
QuestionSecurity of messages
ArnarGudnason
4:45 27 Sep '07  
Hi

I´m a bit confuised. I thought that this code (great by the way, the most readable I´ve seen)encrypted the header and the body of the message to the service. When I look at the input trace at the service I can clearly read username and other variables, f.x the pincode variable is in clear text.
How can I fix it so that the entire content of the message is encrypted?

thanks
Addi
Iceland
QuestionEncrypt body and response?
neal007
9:10 17 Sep '07  
I implemented this code, thank you for it! I would like the response to be encrypted so people can't see the results being sent back. In fact, I'm not sure the body being sent is encrypted either, I'd have to check. From what I understand you're only encrypting the soap header. I really need the body being sent and the response returned to be encrypted as well so I don't have to use HTTPS and buy unnecessary server certs. Any tips?

Neal Culiner
President, NC Software, Inc.

QuestionRe: Encrypt body and response?
neal007
15:44 17 Sep '07  
Okay, I have everything going TO the service fine. The header is encrypted, although I had a problem there as it was using the namespace of my hosting service and not what I put in the SecureSoapHeader area, and I have the body encrypted and signed. All is good there. Now all I want/need is to get the RESULT, the return value encrypted. Anyone know how to do this? I don't want snoopers seeing the values returned from the web service method calls.

Neal Culiner
President, NC Software, Inc.

GeneralError using policy file
AyanAyan
23:43 10 Jul '07  
Hi,

I am getting an error while using the code given in the article. May be I am missing something. Can anyone please help.

1) The code for UsernameAssertionLibrary is exactly same as given

2) I have commented the following part to check how the code behaves (UsernameClientAssertion.cs)
//MessageSignature sig = new MessageSignature(userToken);
//security.Elements.Add(sig);
3) Update the reference

4) When I execute it for the first time it gives me proper error message

5) Now I uncomment the commented portion and update the reference

6) This time it gives the following error

System.Web.Services.Protocols.SoapHeaderException: Microsoft.Web.Services3.Security.SecurityFault: Security requirements are not satisfied because the security header is not present in the incoming message.
at Microsoft.Web.Services3.Design.UsernameOverTransportAssertion.ServiceInputFilter.ValidateMessageSecurity(SoapEnvelope envelope, Security security)

Following is the client side code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Web.Services3;
using Microsoft.Web.Services3.Design;
using Microsoft.Web.Services3.Security.Tokens;
using System.Security;
using System.Security.Cryptography;

using WSE30Test.WSE3Service;
using Microsoft.Web.Services3.Security;
using UsernameAssertionLibrary;

namespace WSE30Test
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

}

Service serviceProxy = new Service();

private void button1_Click(object sender, EventArgs e)
{

string sUsername = "Ayan";
string sPassword = "Password";
UsernameClientAssertion oAssert = new UsernameClientAssertion(sUsername, sPassword);


Policy oPolicy = new Policy();
oPolicy.Assertions.Add(oAssert);
serviceProxy.SetPolicy(oPolicy);
try
{
string sResult = serviceProxy.HelloMyFriend();
MessageBox.Show(sResult);
}
catch (Exception oEx)
{
MessageBox.Show(oEx.ToString());
}
}
}
}


Service code:

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using Microsoft.Web.Services3;
using Microsoft.Web.Services3.Design;
using Microsoft.Web.Services3.Security;
using Microsoft.Web.Services3.Security.Tokens;

using UsernameAssertionLibrary;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[Microsoft.Web.Services3.Policy("ServerPolicy")]

public class Service : System.Web.Services.WebService
{
public Settings settings;

public Service () {

}

[WebMethod, SoapHeader("settings")]
public string HelloMyFriend() {
return "Hello " + RequestSoapContext.Current.IdentityToken.Identity.Name;
}
}




Thanks,
Ayan
QuestionHow to run thissss
honeysip
0:50 8 Jun '07  
Hi All

I downloaded the above project...Its worth useful for thedevelopers trying to secure webmethods.
I could build it successfully...
I am unable to run the project.Can anyone tell me how to use or how to run this project..

Thanks
JokeRe: How to run thissss
fadee
3:02 25 Aug '07  
Laugh

-------------------
Therez No Place like ... 127.0.0.1

QuestionNo Definition for SetPolicy !!!
_Thurein_
22:37 7 May '07  
Error 1
'UsernameAssertionClient.WseSample.Service' does not contain a definition for 'SetPolicy'

Please show me the way to solve it !!!
Thanks
AnswerNo Definition for SetPolicy !!!
_Thurein_
22:49 7 May '07  
I have found something that ........
A comment is written that it has to change from "SoapHttpClientProtocol" to "WebServicesClientProtocol" .....

but how about using "ServiceWse" instead of "Service" ....

Please correct it if I'm wrong ....
GeneralRe: No Definition for SetPolicy !!!
vinodkrebc
1:01 17 Mar '09  
Hello Every Body,,


setPolicy()method was not found in that class
GeneralIts the ws really secure
levalencia
5:10 9 Apr '07  
Hello, I am securing a webservice and using a program called Ethereal to intercept the soap messages,



This is the result from the program, I am watching somethings encrypted and some others on plain xml!!







POST /Ssa/WsKepler.asmx HTTP/1.1

User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 2.0.50727.42)

VsDebuggerCausalityData: uIDPo8w/c8oSL7hKiXfWEkj8XrEAAAAAYDtAfPp/2ECh2RtGkmD2LnaKog3oSJhMksrZxMD91xkACAAA

Content-Type: text/xml; charset=utf-8

SOAPAction: "http://www.avansoft.com/SSA/SeleccionarTodasEmpresas"

Host: agamenon:120

Content-Length: 4900

Expect: 100-continue



HTTP/1.1 100 Continue



http://www.avansoft.com/SSA/SeleccionarTodasEmpresasurn:uuid:8c0a39f7-b3ac-4458-98c4-a14e87d10c20http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymoushttp://agamenon:120/Ssa/WsKepler.asmx2007-04-09T13:49:20Z2007-04-09T13:54:20ZadminFDO4n4+J/tbzdvJE8P+S0g==2007-04-09T13:49:20ZoGkgSxHCBuZRfHOEPQe8GvO3bCs=rsS9We+P7fPqgIIklCsHO/X5i7I=u10uC18fX4ZTZ26s2cCchMRW/Vc=US5UF9BhmHv0KqIVfevxuc9Ma+8=RMPBNYZr2GIYSbvoDo+avJQnTNk=Vay5eIPi50xLWnpkEaucoGlq/p4=h5HLwDjiucoF0XTYqvQ9ZIijtqw=sEFKHnpCCRjDrvthR9rhUBWTbNa24ZyOrWDlz6xdJ2TzLK4qvMA3mCsdbzs1pHzsVTpveusLM6rHnBLOIUmL4cDK6F9jmA/fAYN3udU5ZHgKzt8GRz4BIu74n1v7wcSSHTTP/1.1 200 OK

Date: Mon, 09 Apr 2007 13:49:21 GMT

Server: Microsoft-IIS/6.0

X-Powered-By: ASP.NET

X-AspNet-Version: 2.0.50727

Cache-Control: private, max-age=0

Content-Type: text/xml; charset=utf-8

Content-Length: 2364



http://www.avansoft.com/SSA/SeleccionarTodasEmpresasResponseurn:uuid:7261b612-9c4f-4094-9da4-9887fd5537b5urn:uuid:8c0a39f7-b3ac-4458-98c4-a14e87d10c20http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous2007-04-09T13:49:21Z2007-04-09T13:54:21Z0001-01-01T00:00:002342343asdas0001-01-01T00:00:002342384a assdas ldas asda0001-01-01T00:00:002387923489La mia0001-01-01T00:00:00238934893Haceb0001-01-01T00:00:002393428ssssszxx0001-01-01T00:00:0034534534asadasd0001-01-01T00:00:0034534534534assssssss0001-01-01T00:00:0034784389La suya0001-01-01T00:00:005645645sdfsdfsdfsd0001-01-01T00:00:00
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1449613&SiteID=1&mode=1[^]
AnswerRe: Its the ws really secure
Phil2
11:41 6 May '07  
My WireShark shows it's really encrypted Smile
Don't forget this example is encrypted one way only.;P
GeneralHow to Use this to Encrypt Body Coming Back from Server [modified]
Robin Lilly
17:14 14 Dec '06  
I'm trying to figure out how to use this code to encrypt the Message body coming back from the Service.

I have added a CreateClientInputFilter that uses the code from ServiceInputFilter in the UsernameClientAssertion.cs.

In the UserNameServiceAssertion.cs I added a CreateServiceOutputFilter. I used the same code for the ClientOutputFilter but I hardcoded the same username password as in the assertion in the client.

The output gets encrypted from the service but when it invokes the ClientInputFilter I get this in the Input Trace on the client:
   <processingStep description="Entering SOAP filter UsernameAssertionLibrary.UsernameClientAssertion+ClientInputFilter" />
      <processingStep description="Exception thrown: The security token could not be authenticated or authorized">   at Microsoft.Web.Services3.Security.Tokens.SecurityTokenManager.LoadXmlSecurityToken(XmlElement element)
   at Microsoft.Web.Services3.Security.Tokens.SecurityTokenManager.GetTokenFromXml(XmlElement element)
   at Microsoft.Web.Services3.Security.Security.LoadToken(XmlElement element, SecurityConfiguration configuration, Int32&amp; tokenCount)
   at Microsoft.Web.Services3.Security.Security.LoadXml(XmlElement element)
   at Microsoft.Web.Services3.Security.Security.CreateFrom(SoapEnvelope envelope, String localActor, String serviceActor)
   at Microsoft.Web.Services3.Security.ReceiveSecurityFilter.ProcessMessage(SoapEnvelope envelope)
   at Microsoft.Web.Services3.Pipeline.ProcessInputMessage(SoapEnvelope envelope)</processingStep>
   </inputMessage>

The client basically never invokes the ClientInputFilter (same as ServiceInputFilter). I was thinking I need to get the policy applied like the service did so I added the following via the WSE security tool in the app.config

      <security>
         <securityTokenManager>

            <add type="UsernameAssertionLibrary.UsernameServiceAssertion, UsernameAssertionLibrary" namespace="http://company.com/samples/wse/" localName="usernameAssertion" />
         </securityTokenManager>
      </security>


However that still didn't solve the problem. Maybe I need to apply the same UserNameToken from the client in the serviceoutputfilter.

Currently the serviceoutputfilter (serviceassertion) looks almost Identical to the clientoutputfilter (clientassertion)


               public override void SecureMessage(SoapEnvelope envelope, Security security)
                  {
                       
                        UsernameToken userToken = new UsernameToken(
                              "admin", "nimda",
                              PasswordOption.SendNone); // we don't send password over network
                        // but we just use username/password to sign/encrypt message
                       
                        // Add the token to the SOAP header.
                        security.Tokens.Add(userToken);

parentAssertion.UserName & Password do not exist in UsernameServiceAssertion.

I am lacking an understanding of how the authentication needs to take place on the client side to verify that this is valid.

Thanks.


Robin LIlly
GeneralRe: How to Use this to Encrypt Body Coming Back from Server
Phil2
8:04 15 Dec '06  
Hi Robin, you can achieve encrypting body from server the same way as you did from client.
Don't forget to implement Client Token Manager and delete the stuff from web.config -
add type="UsernameAssertionLibrary.UsernameServiceAssertion, UsernameAssertionLibrary" and so on...
because you defined policy programatically, not declaratively.
Hope this helps...
QuestionRe: How to Use this to Encrypt Body Coming Back from Server
Robin Lilly
9:25 15 Dec '06  
See code http://www.ilogbook.com/utep/titlev/wseexample.zip[^]

I'm not sure what I should do on the client Token manager. I haven't been able to track down your direction on this.

Currently the encryption works, but when it gets to the client it throws the error in the output trace.
<processingStep description="Entering SOAP filter UsernameAssertionLibrary.UsernameClientAssertion+ClientInputFilter" /> <processingStep description="Exception thrown: The security token could not be authenticated or authorized"< at Microsoft.Web.Services3.Security.Tokens.SecurityTokenManager.LoadXmlSecurityToken(XmlElement element) I assume this is the problem with the Client Token Manger. Can you elaborate?

I removed the code I added in the web config for the policy
<security> <securityTokenManager>
<add type="UsernameAssertionLibrary.UsernameServiceAssertion, UsernameAssertionLibrary" namespace="http://company.com/samples/wse/" localName="usernameAssertion" /> </securityTokenManager> </security>

Thank you.


Robin LIlly


Last Updated 8 Nov 2005 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010