Tuesday, May 10, 2011

Validate user against LDAP...

    ...
    using System.DirectoryServices;

        ...
        public bool IsValidLDAPUser(string userName, string password, string ldapPath)
        {
            DirectoryEntry entry = new DirectoryEntry(ldapPath, userName, password);
            DirectorySearcher searcher = new DirectorySearcher(entry);
            searcher.SearchScope = SearchScope.OneLevel;

            try
            {
                SearchResult result = searcher.FindOne();
                return result != null ? true : false;
            }
            catch
            {
                return false;
            }
            finally
            {
                if (searcher != null) searcher.Dispose();
                if (entry != null) entry.Dispose();
            }
        }
        ...

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());
    
    ...