Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I secure my JsonResult GET calls?

I know how to use MVC's AntiForgeryToken attribute and it's associated HTML helper to help XSRF-secure my application's form POSTs.

Can something similar can be done for JsonResults that implement GET?

For instance, my View contains an onSubmit jQuery call like such:

$.getJSON("/allowActivity/YesOrNo/" + someFormValue, "{}", function(data) {
  if(data.Allow) {
    //Do something.
  }
});

I want to make certain that this JsonResult is only callable from the intended page.

EDIT:

I found this post about a similar question, with no concrete answer.

What is the easiest way to ensure that my GET(non-destructive) URL is consumed only by an AJAX call from my own page?

like image 627
Peter J Avatar asked Feb 16 '09 21:02

Peter J


1 Answers

You may use the AntiForgeryToken combined with some custom logic. The creation of the AntiForgery token on the server is the same, but by default the value is not included in your XmlHttpRequest.

The value of this token is in the HTTP only cookie "__RequestVerificationToken" and should also be in the form data posted to the server. So include a key/value pair in your XmlHttpRequest and use the ValidateAntiForgeryToken - attribute on your controller

EDIT:

Today I tried using the AntiForgeryToken for Ajax requests myself and it works fine. Just use the following javascript:

$.post('my_url',  $.getAntiForgeryTokenString(), function() { ... });

$.getAntiForgeryTokenString = function() {
    return $(document.getElementsByName("__RequestVerificationToken")).fieldSerialize();
};

On the server side you don't have to change your code - just use the ValidateAntiForgeryToken- attribute for your action.

Hope this helps

like image 167
ollifant Avatar answered Oct 16 '22 22:10

ollifant