RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Implement Secure .NET Web Services with WS-Security : Page 3

Implement secure .NET Web services by digitally signing, encrypting, and adding security credentials to SOAP messages.

The View from the Server Side
Now let's look on the server side of this Web service. As mentioned previously, you must implement the interface IPasswordProvider and register the implementing class in the WSE runtime. You do this in the section <Microsoft.Web.Services> of the web.config file of the Web service:

         type="WebService1.PasswordProvider, WebService1" />

The attribute type of the element <passwordProvider> takes the class in the form of Namespace.ClassName, ClassName. I have implemented the interface as follows:

public class PasswordProvider : IPasswordProvider
   public String GetPassword(UsernameToken token)
      return "password";

In a real Web service you can query the password of the current user (token.Username) from a storage entity like a database or a XML file. The Web method I use is straightforward:

public String HelloWorld()
   SoapContext requestContext = 
   String strResult = ";

   if (requestContext != null)
      UsernameToken token = GetFirstUsernameToken(

      if (token != null)
         strResult = "Hello World, " + token.Username;

   return strResult;

private UsernameToken GetFirstUsernameToken(Security sec)
   UsernameToken retval = null;

   if (sec.Tokens.Count > 0)
      foreach (SecurityToken tok in sec.Tokens)
         retval = tok as UsernameToken;

         if (retval != null) return retval;

With the private method GetFirstUsernameToken I find the first UsernameToken and return the string Hello World, including the name of the user. When you set breakpoints at the methods GetPassword and HelloWorld, you can see that the former is called before the latter. When the client sends an incorrect password with the SOAP request and you debug the Web service again, you find out that the method GetPassword is called but then the request is rejected. The WSE runtime prevents the code in the function HelloWorld from being executed.

Close Icon
Thanks for your registration, follow us on our social networks to keep up-to-date