How to create a secure webservice in asp.net

Web service is a way to communicate between 2 machines via HTTP, those 2 machines can be on the different platform.
See more about web service at this URL: http://www.sharepointcafe.net/2015/05/all-about-web-service-soap-rest.html
As you know web service is a way to communicate over HTTP, so the main concern here is security.
How to make a secure web service?

Below are few authentication options that are available to web service in ASP.Net

  1. Windows Basic
  2. Windows Basic Over SSL
  3. Windows Client Certificates
  4. Custom SOAP Headers
In this blog, I will explain how can we secure web service using Custom SOAP Header.

Custom SOAP Headers

SOAP web service includes following items it.
SOAP Envelop, SOAP Header, SOAP Body, SOAP Fault
Let’s implement Custom SOAP Header by an example.
Create a Web Project in Visual Studio, Add web service in your project.
Write Below code:

    /// <summary>
    /// Summary description for EmpWebService
    /// </summary>
    [WebService(Namespace = “http://tempuri.org/”)]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class EmpWebService : System.Web.Services.WebService
    {
        public AuthHeader Authentication;
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
        [SoapHeader(“Authentication”)]
        public string GetMessage(string name)
        {
            if (Authentication != null)
            {
                if (Authentication.IsAuthenticated())
                {
                    string msg = string.Format(“Hello {0}”, name);
                    return msg;
                }
                else
                {
                    return “Invalid Credentials”;
                }
            }
            else
            {
                return “User Authentication Fail”;
            }
        }
    }

Note, I have decorated GetMessage method with SoapHeader(“Authentication”)
Also, I have declared a variable called Authentication of type AuthHeader.

Below is AuthHeader class.

    public class AuthHeader : SoapHeader
    {
        public string Username { get; set; }
        public string Password { get; set; }
        public bool IsAuthenticated()
        {
            //Write Code to get user details from database
            try
            {
                SqlParameter[] param = new SqlParameter[2];
                param[0] = new SqlParameter(“@username”, Username);
                param[1] = new SqlParameter(“@password”, Password);
                SqlDataReader reader = DAL.ExecuteReader(“DBCon”, “SP_GetUserCrdentials”, param);
                if (reader.Read())
                    return true;
                else
                    return false;
                
            }
            catch (Exception)
            {
                throw;
            }
        }
    }

Data Access Layer

public class DAL
    {
        public static SqlDataReader ExecuteReader(string dbConnectionName, string storedProcedure, SqlParameter[] parameters)
        {
            SqlConnection sqlConnection = new SqlConnection(“Put your connection string”);
            SqlCommand sqlCommand = new SqlCommand(storedProcedure, sqlConnection);
            SqlDataReader sqlDataReader = null;
            sqlCommand.CommandType = CommandType.StoredProcedure;
            if (parameters != null)
                sqlCommand.Parameters.AddRange(parameters);
            try
            {
                sqlConnection.Open();
                sqlDataReader = sqlCommand.ExecuteReader(CommandBehavior.CloseConnection);
            }
            catch (SqlException ex)
            {
            }
            finally
            {
                
            }
            return sqlDataReader;
        }
    }

Now create a client to consume web service.
I have created a console application to consume.
Pass username and password and if it matches with the credentials stored in the database then you will get greeting message else you will see an error message.

namespace ConsumeSecureWebService
{
    class Program
    {
        static void Main(string[] args)
        {
            EmpSecureWebService.EmpWebServiceSoapClient objEMPSOAP = new EmpSecureWebService.EmpWebServiceSoapClient();
            EmpSecureWebService.AuthHeader authentication = new EmpSecureWebService.AuthHeader
            {
                Username = Console.ReadLine(),
                Password = Console.ReadLine()
            };
            string result = objEMPSOAP.GetMessage(authentication, “Ram Kumar”);
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}

Note that I have added below attribute to web method GetMessage()

[SoapHeader(“Authentication”)]

I have created a separate class called “AuthHeader” inheriting another class “SoapHeader

Once you run the ASMX file in the browser, you may notice an XML is present on the page.
And see this XML has a tag <AuthHeader> which is a class name inherited from SoapHeader class.


Read this - What is Microservice Architecture?

Related Blogs –

Please follow and like us:

Leave a Comment