Skip to main content

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

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 != "") {
        } else return false;
    error: function(xhr, ajaxOptions, thrownError) {
 catch (ex) {

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

public static string LocalWS(String Msg)
    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.");
    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 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)

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 Following code demonstrating the various ways of implementation.