Skip to main content

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 from this blog

regex - check if a string contains only alphabets c#

How to validate that input string contains only alphabets, validating that textbox contains only alphabets (letter), so here is some of the ways for doing such task. char have a property named isLetter which is for checking if character is a letter or not, or you can check by the regular expression  or you can validate your textbox through regular expression validator in asp.net. Following code demonstrating the various ways of implementation.

How to validate dropdownlist in JavaScript

In this article you will see how to put validation in dropdownlist by javascript, suppose first item value of dropdownlist is 0 and text is "-Select-" just like given below and we have to validate that at least one item is selected excluding default i.e "-Select-".

Uploading large file in chunks in Asp.net Mvc c# from Javascript ajax

Often we have a requirement to upload files in Asp.net, Mvc c# application but when it comes to uploading larger file, we always think how to do it as uploading large file in one go have many challenges like UI responsiveness, If network fluctuate for a moment in between then uploading task get breaks and user have to upload it again etc.

how $document.ready() is different from window.onload()

we often use window.onload() in javascript and $document.ready() in jquery and assume that both are same just jquery library wrap up javascript window.onload() and introduce $document.ready() but no there is much difference between them below is the explanation -