Security in asp.net ajax webservice

Many time we need to make a service in our domain and call them through javascript (exposing them to client),so here we are exposing our service to world wide web and we need to ensure that our service is secure, I search a lot but didn’t find any appropriate solution so I wrote this post ..


Make a funtion (GenerateTicket) all you need to create a ticket from aspx page and register it in to html page and add this ticket into request header during the calling service through ajax further when a request raise for invoking a webservice check the request header and check that ticket presence and value into your webservice through function(ValidateTicket) and authenticate that request..

Aspx Part :-

To ensure that it is not called from any other place except the aspx pages. Truly speaking, there is no full proof way you can guarantee but you can add some complexity, so it gets a bit difficult comparing the above. Lets say in the aspx page which is used to call the web service we add the following code:

First of all create a ticket and store it in session, make key more complicated include session key that is unique for user and distroid after when user quit the job..

Every time the page is rendered it creates a new Guid, puts it in the Session and embedded it as a JavaScript global variable (<%=strSecTckt %>).


protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
       GenerateTicket();
}

public string strSecTckt;
private void GenerateTicket()
{
 string Key = "SecurityTicket:" + Session.SessionID;
 strSecTckt = Guid.NewGuid().ToString();
 Session[Key] = strSecTckt;
}


Below is the jquery code to invoking web service,when we are invoking the web method we have to make sure that the required header is added.
Add a header named STicket through beforesend property (xhr .setRequestHeader).

JavaScript Calling Part :-

function CallSecureLocalWS() {
 try {
  var dat = "{Msg:'hello'}";
  var options = {
    type: "POST",
    url: "webservicedemo.aspx/LocalWS",
    data: dat,
    beforeSend: function(xhr) {
        xhr.setRequestHeader("STicket""<%=strSecTckt %>");
    },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        if (msg.d != "") {
            alert(msg.d);
        } else return false;
    },
    error: function(xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
        alert(ajaxOptions);
    }
  };
   $.ajax(options);
 }
 catch (ex) {
  alert("Error");
 }
}


Service part:-

Here we have to validate every request, for that check header ticket(named STicket) every time and match them from our session ticket value..


[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string LocalWS(String Msg)
{
    ValidateTicket();
    return Msg + ":Vivek";
}
private static void ValidateTicket()
{
 HttpContext context = HttpContext.Current;
 if (context != null)
 {
   string headerTicket = context.Request.Headers["STicket"];
   if (string.IsNullOrEmpty(headerTicket))
     throw new System.Security.SecurityException("Security ticket must be present.");

  string Key = "SecurityTicket:" + context.Session.SessionID;
  string ServerTicket = Convert.ToString(context.Session[Key]);

  if (string.Compare(headerTicket, ServerTicket, false) != 0)
    throw new System.Security.SecurityException("Security ticket  mismatched.");
 }
 else
    throw new System.Security.SecurityException("Not authorized.");
}



Popular Posts