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.

Regular expression for alphanumeric with space in asp.net c#

How to validate that string contains only alphanumeric value with some spacial character and with whitespace and how to validate that user can only input alphanumeric with given special character or space in a textbox (like name fields or remarks fields). In remarks fields we don't want that user can enter anything, user can only able to enter alphanumeric with white space and some spacial character like -,. etc if you allow. Some of regular expression given below for validating alphanumeric value only, alphanumeric with whitspace only and alphanumeric with whitespace and some special characters.

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 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)