5

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?

4 Answers 4

8

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

2
  • How would you integrate the __RequestVerificationToken value with the $.getJSON or $.ajax call? Remember, this is a GET request.
    – Peter J
    Feb 16, 2009 at 22:58
  • Read "Disclosure of Token in URL" from owasp.org/index.php/… " If sensitive server-side actions are guaranteed to only ever respond to POST requests, then there is no need to include the token in GET requests" The key is to make sure your GET doesn't modify data. Otherwise, you don't need to protect GET requests Mar 22, 2010 at 21:12
1

First of all why not to use $.post(url, data, callback, 'json') instead of getJSON? And as kleolb02 said, you may add value from the cookie to the post data using cookie plugin - {__RequestVerificationToken: $.cookie('__RequestVerificationToken')}

4
  • That sounds good. I was hoping to avoid POST for such a simple ajax call, but I certainly will if it's the only way to secure it.
    – Peter J
    Feb 17, 2009 at 3:57
  • You should use post to update some data on the server. This is a common scenario. And as far as I remember AntiForgeryToken's are working only with post requests (they looks for a value in FormCollection only).
    – zihotki
    Feb 18, 2009 at 4:45
  • This is not an update, it is a simple "get". I would simply like to restrict the URL's consumption to my own page's AJAX calls.
    – Peter J
    Feb 19, 2009 at 23:03
  • Sorry, this is not possible to restrict it. You may check referrer url and some specific cookies but they can be easily emulated. You can only restrict access to url to not authorized users. For this you can use standard login authorization.
    – zihotki
    Feb 20, 2009 at 0:39
1

I have used similar code in an ASP.NET MVC project to use on an element's blur function without having an Ajax form. This code provides filling a text field with server data when a certain HTML element Blur event occurs.

Hope this helps too. Here's my code:

Javascript:

var mytext = { 'myText': 'example text' };
$.post('/MyController/JsonResultMethod', AddAntiForgeryToken(myText), function (resultData) {
        $('#htmlElement').val(resultData);
});
AddAntiForgeryToken = function (data) {
    data.__RequestVerificationToken = $('input[name=__RequestVerificationToken]').val();
    return data;
};

C-Sharp code:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public JsonResult SeoString(string myText)
    {
        try
        {
            // do something here
            return this.Json("result text");
        }
        catch (Exception)
        { return this.Json(string.Empty); }
    }
0

You can do something similar as the anti XSRF methods. Just generate some ID insert it into the javascript and when the user calls your JSON url, have that url include the generated ID and check if it is there.

A defense against XSRF is also using the sessionID as key, this doesn't stop the user executing it from another website for his own account though.

Some hash based on the session and time might do the trick. Ofcourse if the user copies the value from the JS, he can still execute it from another location, but you can have that value expire every x minutes. Another option is to set a cookie with JS and read it serverside.

Hope this gives you some ideas to get you started.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.