Click here to Skip to main content
15,881,882 members
Articles / Web Development / ASP.NET

Web Service Authentication

Rate me:
Please Sign up or sign in to vote.
4.35/5 (41 votes)
25 Nov 2009CPOL3 min read 465.1K   8.3K   197  
A simple mechanism to authenticate users to a WebService
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Web;
using System.Web.Services;
using System.Security.Cryptography;
using System.Text;

namespace WebServiceAuthentication
{
    /// <summary>
    /// Summary description for ServicePoint.
    /// </summary>
    public class ServicePoint : System.Web.Services.WebService
    {
        public ServicePoint()
        {
            //CODEGEN: This call is required by the ASP.NET Web Services Designer
            InitializeComponent();
        }

        #region Component Designer generated code

        //Required by the Web Services Designer 
        private IContainer components = null;

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
        }

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing && components != null)
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #endregion

        [WebMethod]
        public string Authenticate(string Key)
        {
            string[] HashArray;
            string UserName, level;

            // Key string: HASH|User|OptionalData
            HashArray = Key.Split('|');
            level = "-1";	//defaul level

            if (TestHash(HashArray[0], HashArray[1], 0, "ANY"))
            {
                try
                {
                    UserName = HashArray[1];
                    // JUST FOR TEST: the User authentication level is hard-coded
                    // but may/shuold be retrieved from a DataBase
                    switch (UserName)
                    {
                        case "MyUserName":
                            level = "1";
                            break;
                        case "OtherUser":
                            level = "2";
                            break;
                        default:
                            level = "-1";
                            break;
                    }
                    if (level == "") level = "-1";
                    return "Authentication level: " + level;
                }
                catch (Exception exc)
                {
                    return "Authentication failure: " + exc.ToString();
                }
            }
            return "Authentication failure";
        }

        [WebMethod]
        public string GetToken()
        {
            string ToHash, sResult;
            DateTime dt = DateTime.Now;
            ToHash = dt.ToString("yyyyMMdd") + "|" + dt.ToString("HHmm");
            sResult = Hash(ToHash);
            return sResult;
        }

        [WebMethod]
        public string UseService(string Key, string ServiceName)
        {
            string[] HashArray;
            string UserName, level;

            // Key string: HASH|User|OptionalData
            HashArray = Key.Split('|');
            level = "-1";	//defaul level

            if (TestHash(HashArray[0], HashArray[1], 0, ServiceName))
            {
                try
                {
                    UserName = HashArray[1];
                    // JUST FOR TEST: the User authentication level is hard-coded
                    // but may/shuold be retrieved from a DataBase
                    switch (UserName)
                    {
                        case "MyUserName":
                            level = "1";
                            break;
                        case "OtherUser":
                            level = "2";
                            break;
                        default:
                            level = "-1";
                            break;
                    }
                    if (level == "1") return "YOU ARE AUTHORIZED";
                }
                catch (Exception exc)
                {
                    return "Authentication failure: " + exc.ToString();
                }
            }
            return "Authentication failure";
        }

        private bool TestHash(string HashStr, string UserName, int minutes, string ServiceName)
        {
            string Pwd, ToHash;
            string sResult, sResultT, sResultToken;
            try
            {
                /* SAMPLE TO READ THE PASSWORD FROM A DATABASE
                string qryStr;
                System.Data.SqlClient.SqlConnection uConn;
                System.Data.SqlClient.SqlCommand uCmd;
                System.Data.SqlClient.SqlDataReader udr;

                // get the password from a DB 
                uConn = new SqlConnection();
                uConn.ConnectionString = "Server=localhost;UID=sa;PWD=sa;APP=ServicePoint;Database=Users";
                if (ServiceName=="ANY")
                    qryStr="select password from UsersTable where UserName='"+UserName.Trim()+"'" ;
                else
                    qryStr="SELECT password FROM UsersTable USR INNER JOIN Systems SYS ON USR.UserName = SYS.UserName " +
                        "WHERE USR.UserName = '"+UserName.Trim()+"' AND SYS.Systems = '"+ServiceName.Trim()+"'";
                uCmd = new SqlCommand(qryStr, uConn);
                uConn.Open();
                Pwd = (string)uCmd.ExecuteScalar();
                if (Pwd==null)
                {
                    uConn.Close();
                    return false;
                }
                else
                    Pwd=Pwd.ToString().Trim();
                uConn.Close();
                */

                if (ServiceName == "ANY")
                    // JUST FOR TEST: the password is hard-coded:
                    Pwd = "SeCrEt";
                else
                    // JUST FOR TEST: the password is hard-coded:
                    Pwd = "SeCrEt" + ServiceName;


                DateTime dt = DateTime.Now;
                System.TimeSpan minute = new System.TimeSpan(0, 0, minutes, 0, 0);
                dt = dt - minute;
                //before hashing we have:
                //USERNAME|PassWord|YYYYMMDD|HHMM
                ToHash = UserName.ToUpper() + "|" + Pwd + "|" + dt.ToString("yyyyMMdd") + "|" + dt.ToString("HHmm");
                sResult = Hash(ToHash);
                //TokenWeGotBefore
                ToHash = dt.ToString("yyyyMMdd") + "|" + dt.ToString("HHmm");
                sResultToken = Hash(ToHash);
                //USERNAME|PassWord|TokenWeGotBefore
                ToHash = UserName.ToUpper() + "|" + Pwd + "|" + sResultToken;
                sResultT = Hash(ToHash);

                if ((sResult == HashStr) || (sResultT == HashStr))
                    return true;
                else
                    if (minutes == 0) // allowed max 2 minutes - 1 second to call web service
                        return TestHash(HashStr, UserName, 1, ServiceName);
                    else
                        return false;
            }
            catch
            {
                return false;
            }
        }

        private string Hash(string ToHash)
        {
            // First we need to convert the string into bytes, which means using a text encoder.
            Encoder enc = System.Text.Encoding.ASCII.GetEncoder();

            // Create a buffer large enough to hold the string
            byte[] data = new byte[ToHash.Length];
            enc.GetBytes(ToHash.ToCharArray(), 0, ToHash.Length, data, 0, true);

            // This is one implementation of the abstract class MD5.
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(data);

            return BitConverter.ToString(result).Replace("-", "").ToLower();
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Italy Italy
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions