Search code examples
asp.netajaxrequesthandlerashx

How to secure ajax handlers?


I am using post like this in http://www.mywebsite.com/hello.aspx page:

$.post("handler.ashx", {}, function (x) { alert(x); });

How to check the address from which the handler is running?

public void ProcessRequest (HttpContext context) 
{
    // check if request is from http://mywebsite/hello.aspx          

    context.Response.ContentType = "text/plain";
    context.Response.Write("test");
}

or... how to disable request handler from different domain?


Solution

  • You can use the UrlReferrer to check if the call is comming from your site. One very simple working example:

    if( !context.Request.UrlReferrer.Contains("site.com/")) ) 
    {
       context.Response.End();
       return;
    }
    

    In some rare cases that users overwrite the Referrer, this fails.