How to protect my GET JsonResult calls?

I know how to use the MVC attribute AntiForgeryToken and its associated HTML helper to help XSRF protect my POST messages.

Is it possible to do something similar for JsonResults that implement GET?

For example, my View contains an onSubmit jQuery call, such as:

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

I want to make sure that this JsonResult is only available from the specified page.

EDIT:

I found this post about a similar question without a specific answer.

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

+5
source share
4 answers

AntiForgeryToken . AntiForgery , XmlHttpRequest.

cookie HTTP "__RequestVerificationToken" , . , / XmlHttpRequest ValidateAntiForgeryToken

EDIT:

AntiForgeryToken Ajax, . javascript:

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

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

- ValidateAntiForgeryToken- .

,

+8

, $.post(url, data, callback, 'json') getJSON? , kleolb02, cookie post, cookie - {__RequestVerificationToken: $.cookie('__ RequestVerificationToken' )}

+1

ASP.NET MVC Ajax. Blur HTML.

, . :

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:

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

- XSRF. , javascript, JSON-url, url , .

XSRF Protection also uses sessionID as a key, but this does not prevent the user from logging in from another website for their own account.

Some session and time based hashes can do the trick. If the user copies the value from JS, he can still execute it from another place, but you can get this value for every x minutes. Another option is to set a cookie with JS and read it on the server.

Hope this gives you some ideas to get you started.

0
source

All Articles