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

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 -

Merging multiple PDFs using iTextSharp in asp.net c#

In this article i will show you how to merge multiple pdfs into one using ITextSharp below is the two approach one is to pass your input files path, output file path (will be created if not exist) and another is pass direct input stream, output stream and it will write the merge files into output stream.

How to handle click event of linkbutton inside gridview

Recently I have posted how to sort only current page of gridview , Scrollble gridview with fixed header through javascript , File upload control inside gridview during postback and now i am going to explain how to handle click event of linkbutton or any button type control inside gridview. We can handle click event of any button type control inside gridview by two way first is through event bubbling and second one is directly (in this type of event handling we need to access current girdviewrow container)

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-".