Web Service BasicAuthentication Solution

I’ve shown how to add the Authorization header to your client. Now, lets take it server side. How do we receive that header and either allow access or reject the request with a SoapException. Lets start at the authentication piece. This object will be instantiated from the endpoint method and references a remote ActiveDirectory LDAP. I also happen to be using log4net as my logging solution. Cut that part out if not needed.

namespace
{
    public class BasicAuthenticator
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(BasicAuthenticator));
        private static string searchString = "OU= ...";
        HttpContext context;
        LdapConnection ldapConn = null;

        public BasicAuthenticator(HttpContext context)
        {
            this.context = context;

            string server1 = ConfigurationManager.AppSettings["LDAP_Server1"];
            string server2 = ConfigurationManager.AppSettings["LDAP_Server2"];
            string port = ConfigurationManager.AppSettings["LDAP_PORT"];
            LdapDirectoryIdentifier ldapIdentity = new LdapDirectoryIdentifier(new string[] { server1, server2 }, Convert.ToInt32(port), false, false);
            ldapConn = new LdapConnection(ldapIdentity);
        }

        public bool authenticate()
        {
            bool authentic = false;

            string authStr = context.Request.Headers["Authorization"];

            if (authStr == null || authStr.Length == 0)
                return false;

            authStr = authStr.Trim();

            string encodedCredentials = authStr.Substring(6);

            byte[] decodedBytes = Convert.FromBase64String(encodedCredentials);
            string s = new ASCIIEncoding().GetString(decodedBytes);

            string[] userPass = s.Split(new char[] { ':' });
            string username = userPass[0];
            string password = userPass[1];

            log.Info("Authentication Attempt: " + username);

            if (TryAuth(context.ApplicationInstance, username, password))
            {
                context.User = new GenericPrincipal(new GenericIdentity(username, "ImporterWS.Basic"), null);
                authentic = true;
            }

            return authentic;
        }

        private bool TryAuth(HttpApplication app, string username, string password)
        {
            bool authentic = false;
            try
            {
                ldapConn.Credential = new NetworkCredential(username, password);

                DirectoryEntry entry = new DirectoryEntry("LDAP://" + searchString, username, password);
                object nativeObject = entry.NativeObject;
                authentic = true;
            }
            catch (DirectoryServicesCOMException dsce)
            {
                log.Warn(dsce.Message);
            }

            log.Debug("Authentic: " + authentic);
            return authentic;
        }
    }
}

 


[WebMethod]

public string HelloWorld()

{
    Authenticator authenticator = new Authenticator(Context);
    if (authenticator.authenticate())
    {
        return "Hello World!";
    }
    else
    {
        throw new SoapException("Authentication Failure", SoapException.ClientFaultCode, Context.Request.Url.AbsoluteUri, node);
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s