Thursday, May 5, 2011

Validate webservice client via SOAP header...

First, the SOAP header
    namespace SecureWebServiceDemo
    {
        using System;
        using System.Web.Services.Protocols;

        public class MySoapHeader : SoapHeader
        {
            private string _userName;
            private string _password;

            public MySoapHeader()
            {
            }

            public string UserName
            {
                get { return _userName; }
                set { _userName = value; }
            }

            public string Password
            {
                get { return _password; }
                set { _password = value; }
            }
        }
    }
Next, the webservice
    using ...

    namespace SecureWebServiceDemo
    {
        /// 
        /// Summary description for MyWebService
        /// 
        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [ToolboxItem(false)]
        public class MyWebService : System.Web.Services.WebService
        {
            public MySoapHeader _header;
            private const string _userName = "testuser";
            private const string _password = "123456";

            [SoapHeader("_header")]
            [WebMethod]
            public string HelloWorld()
            {
                if (_header == null || _header.UserName != _userName || _header.Password != _password) throw new Exception("Invalid User");
                
                return "Hello World";
            }
        }
    }
Finally, the client side
    ...
    
    localhost.MySoapHeader header = new localhost.MySoapHeader();
    header.UserName = "testuser";
    header.Password = "123456";

    localhost.MyWebService test = new localhost.MyWebService();
    test.MySoapHeaderValue = header;
    Console.WriteLine(test.HelloWorld());
    
    ...

No comments:

Post a Comment